325 lines
8.2 KiB
Go
325 lines
8.2 KiB
Go
// Package cli implements the guide's commands -- solution, task,
|
|||
|
|
// knowledge and open -- with yet's conventions (stdlib flag, --json on
|
||
|
|
// every command, data on stdout, messages on stderr, stable exit codes),
|
||
|
|
// so yet mounts them with one case in its dispatcher:
|
||
|
|
//
|
||
|
|
// case "solution", "task", "knowledge", "open":
|
||
|
|
// return cli.Run(ctx, args, env)
|
||
|
|
//
|
||
|
|
// The same package backs the standalone yetano-solutions binary.
|
||
|
|
package cli
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bufio"
|
||
|
|
"context"
|
||
|
|
"encoding/json"
|
||
|
|
"errors"
|
||
|
|
"flag"
|
||
|
|
"fmt"
|
||
|
|
"io"
|
||
|
|
"os"
|
||
|
|
"path/filepath"
|
||
|
|
"sort"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"yetano.dev/yetano/core/solutions/catalog"
|
||
|
|
"yetano.dev/yetano/core/solutions/engine"
|
||
|
|
"yetano.dev/yetano/core/solutions/knowledge"
|
||
|
|
"yetano.dev/yetano/core/solutions/store"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Exit codes, the same as yet's (yet/internal/cliutil).
|
||
|
|
const (
|
||
|
|
ExitOK = 0
|
||
|
|
ExitError = 1
|
||
|
|
ExitUsage = 2
|
||
|
|
ExitNotFound = 3
|
||
|
|
ExitConflict = 4
|
||
|
|
)
|
||
|
|
|
||
|
|
// Env is what the embedding program provides.
|
||
|
|
type Env struct {
|
||
|
|
Stdin io.Reader
|
||
|
|
Stdout io.Writer
|
||
|
|
Stderr io.Writer
|
||
|
|
// Interactive: stdin and stdout are a terminal. Without it no command
|
||
|
|
// ever waits for input (CLI-03).
|
||
|
|
Interactive bool
|
||
|
|
// Program is the command name in messages ("yet" or "yetano-solutions").
|
||
|
|
Program string
|
||
|
|
// Catalogs are default catalog directories (an installed knowledge
|
||
|
|
// bundle); --catalog and $YETANO_SOLUTIONS_CATALOG come first.
|
||
|
|
Catalogs []string
|
||
|
|
// StoreDir keeps instances, sessions, presets (from core/paths).
|
||
|
|
StoreDir string
|
||
|
|
// Version is stamped into lock files.
|
||
|
|
Version string
|
||
|
|
// Getenv defaults to os.Getenv.
|
||
|
|
Getenv func(string) string
|
||
|
|
}
|
||
|
|
|
||
|
|
type app struct {
|
||
|
|
env Env
|
||
|
|
ctx context.Context
|
||
|
|
catDir string
|
||
|
|
locale string
|
||
|
|
cat *catalog.Catalog
|
||
|
|
ix *knowledge.Index
|
||
|
|
eng *engine.Engine
|
||
|
|
store store.Store
|
||
|
|
jsonOut bool
|
||
|
|
}
|
||
|
|
|
||
|
|
// exitErr carries an exit code.
|
||
|
|
type exitErr struct {
|
||
|
|
code int
|
||
|
|
err error
|
||
|
|
}
|
||
|
|
|
||
|
|
func (e exitErr) Error() string { return e.err.Error() }
|
||
|
|
|
||
|
|
func fail(code int, f string, a ...any) error { return exitErr{code, fmt.Errorf(f, a...)} }
|
||
|
|
|
||
|
|
// Run runs one command; args start with the command name.
|
||
|
|
func Run(ctx context.Context, args []string, env Env) int {
|
||
|
|
if env.Getenv == nil {
|
||
|
|
env.Getenv = os.Getenv
|
||
|
|
}
|
||
|
|
if env.Program == "" {
|
||
|
|
env.Program = "yet"
|
||
|
|
}
|
||
|
|
if env.Stdin == nil {
|
||
|
|
env.Stdin = os.Stdin
|
||
|
|
}
|
||
|
|
a := &app{env: env, ctx: ctx, store: store.Store{Dir: env.StoreDir}}
|
||
|
|
if env.Version != "" {
|
||
|
|
engine.GeneratorVersion = env.Version
|
||
|
|
}
|
||
|
|
err := a.dispatch(args)
|
||
|
|
if err == nil {
|
||
|
|
return ExitOK
|
||
|
|
}
|
||
|
|
if errors.Is(err, flag.ErrHelp) {
|
||
|
|
return ExitOK
|
||
|
|
}
|
||
|
|
code := ExitError
|
||
|
|
var ee exitErr
|
||
|
|
if errors.As(err, &ee) {
|
||
|
|
code = ee.code
|
||
|
|
}
|
||
|
|
switch {
|
||
|
|
case errors.Is(err, engine.ErrNotFound), errors.Is(err, store.ErrNotFound):
|
||
|
|
code = ExitNotFound
|
||
|
|
case errors.Is(err, engine.ErrModified):
|
||
|
|
code = ExitConflict
|
||
|
|
case errors.Is(err, engine.ErrIncomplete):
|
||
|
|
code = ExitUsage
|
||
|
|
}
|
||
|
|
if a.jsonOut {
|
||
|
|
enc := json.NewEncoder(env.Stdout)
|
||
|
|
enc.SetIndent("", " ")
|
||
|
|
_ = enc.Encode(map[string]any{"error": err.Error(), "code": code})
|
||
|
|
} else if err.Error() != "" {
|
||
|
|
fmt.Fprintf(env.Stderr, "error: %v\n", err)
|
||
|
|
}
|
||
|
|
return code
|
||
|
|
}
|
||
|
|
|
||
|
|
func (a *app) dispatch(args []string) error {
|
||
|
|
// global flags before the command (--catalog dir solution list) move
|
||
|
|
// behind it, where every subcommand's flag set parses them
|
||
|
|
var lead []string
|
||
|
|
for len(args) > 0 && strings.HasPrefix(args[0], "-") && args[0] != "-h" && args[0] != "--help" {
|
||
|
|
lead = append(lead, args[0])
|
||
|
|
name := strings.TrimLeft(args[0], "-")
|
||
|
|
args = args[1:]
|
||
|
|
if (name == "catalog" || name == "locale") && len(args) > 0 {
|
||
|
|
lead = append(lead, args[0])
|
||
|
|
args = args[1:]
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if len(lead) > 0 && len(args) > 0 {
|
||
|
|
args = append(append([]string{}, args...), lead...)
|
||
|
|
}
|
||
|
|
if len(args) == 0 {
|
||
|
|
return a.usage("")
|
||
|
|
}
|
||
|
|
cmd, rest := args[0], args[1:]
|
||
|
|
switch cmd {
|
||
|
|
case "solution", "solutions":
|
||
|
|
return a.solution(rest)
|
||
|
|
case "task", "tasks":
|
||
|
|
return a.task(rest)
|
||
|
|
case "knowledge":
|
||
|
|
return a.knowledge(rest)
|
||
|
|
case "open":
|
||
|
|
return a.open(rest)
|
||
|
|
case "help", "-h", "--help":
|
||
|
|
return a.usage("")
|
||
|
|
}
|
||
|
|
return a.usage(cmd)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Usage is the help text (also for yet's usage()).
|
||
|
|
const Usage = `Solutions Guide -- describe what you want to achieve, get native configuration:
|
||
|
|
|
||
|
|
solution list|search|show|setup|generate|validate|plan|doctor
|
||
|
|
solution config show|explain, architecture, handbook, package
|
||
|
|
solution instance list|show|export|import|delete
|
||
|
|
solution preset list|save|show|export|import|delete
|
||
|
|
solution catalog validate|test|coverage
|
||
|
|
task list|search|show|run
|
||
|
|
knowledge search|show|status|backlinks|coverage
|
||
|
|
open <yetano:reference>
|
||
|
|
|
||
|
|
Common flags: --catalog DIR, --locale de, --json.
|
||
|
|
`
|
||
|
|
|
||
|
|
func (a *app) usage(unknown string) error {
|
||
|
|
if unknown != "" {
|
||
|
|
fmt.Fprintf(a.env.Stderr, "unknown command %q\n\n", unknown)
|
||
|
|
}
|
||
|
|
fmt.Fprint(a.env.Stderr, Usage)
|
||
|
|
if unknown != "" {
|
||
|
|
return exitErr{ExitUsage, errors.New("")}
|
||
|
|
}
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// flags makes a flag set with the common flags.
|
||
|
|
func (a *app) flags(name string) *flag.FlagSet {
|
||
|
|
fs := flag.NewFlagSet(a.env.Program+" "+name, flag.ContinueOnError)
|
||
|
|
fs.SetOutput(a.env.Stderr)
|
||
|
|
fs.StringVar(&a.catDir, "catalog", "", "catalog directory (default: $YETANO_SOLUTIONS_CATALOG, then the installed bundle)")
|
||
|
|
fs.StringVar(&a.locale, "locale", "", "language of texts (en, de); default from $LANG")
|
||
|
|
fs.BoolVar(&a.jsonOut, "json", false, "machine-readable output")
|
||
|
|
return fs
|
||
|
|
}
|
||
|
|
|
||
|
|
func (a *app) parse(fs *flag.FlagSet, args []string) error {
|
||
|
|
// allow flags after positional arguments (yet does the same)
|
||
|
|
var flags, pos []string
|
||
|
|
for i := 0; i < len(args); i++ {
|
||
|
|
s := args[i]
|
||
|
|
if s == "--" {
|
||
|
|
pos = append(pos, args[i+1:]...)
|
||
|
|
break
|
||
|
|
}
|
||
|
|
if strings.HasPrefix(s, "-") && len(s) > 1 {
|
||
|
|
flags = append(flags, s)
|
||
|
|
name := strings.TrimLeft(s, "-")
|
||
|
|
if !strings.Contains(name, "=") {
|
||
|
|
if f := fs.Lookup(name); f != nil {
|
||
|
|
if bf, ok := f.Value.(interface{ IsBoolFlag() bool }); !ok || !bf.IsBoolFlag() {
|
||
|
|
if i+1 < len(args) {
|
||
|
|
flags = append(flags, args[i+1])
|
||
|
|
i++
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
pos = append(pos, s)
|
||
|
|
}
|
||
|
|
if err := fs.Parse(flags); err != nil {
|
||
|
|
if errors.Is(err, flag.ErrHelp) {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
return exitErr{ExitUsage, err}
|
||
|
|
}
|
||
|
|
return fs.Parse(append([]string{"--"}, pos...))
|
||
|
|
}
|
||
|
|
|
||
|
|
// load finds and loads the catalog and the index.
|
||
|
|
func (a *app) load() error {
|
||
|
|
if a.cat != nil {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
if a.locale == "" {
|
||
|
|
lang := a.env.Getenv("LANG")
|
||
|
|
if strings.HasPrefix(lang, "de") {
|
||
|
|
a.locale = "de"
|
||
|
|
} else {
|
||
|
|
a.locale = "en"
|
||
|
|
}
|
||
|
|
}
|
||
|
|
candidates := []string{a.catDir, a.env.Getenv("YETANO_SOLUTIONS_CATALOG")}
|
||
|
|
candidates = append(candidates, a.env.Catalogs...)
|
||
|
|
dir := ""
|
||
|
|
for _, c := range candidates {
|
||
|
|
if c == "" {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if _, err := os.Stat(filepath.Join(c, "catalog.yaml")); err == nil {
|
||
|
|
dir = c
|
||
|
|
break
|
||
|
|
}
|
||
|
|
if c == a.catDir {
|
||
|
|
return fail(ExitUsage, "--catalog %s: no catalog.yaml there", c)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if dir == "" {
|
||
|
|
return fail(ExitNotFound, "no solutions catalog found: pass --catalog <dir> or set YETANO_SOLUTIONS_CATALOG (the meta-repo's assets/solutions)")
|
||
|
|
}
|
||
|
|
c, err := catalog.Load(dir)
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
a.cat = c
|
||
|
|
a.ix = knowledge.Build(c)
|
||
|
|
a.eng = engine.New(c)
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func (a *app) out() io.Writer { return a.env.Stdout }
|
||
|
|
|
||
|
|
func (a *app) printJSON(v any) error {
|
||
|
|
enc := json.NewEncoder(a.env.Stdout)
|
||
|
|
enc.SetIndent("", " ")
|
||
|
|
return enc.Encode(v)
|
||
|
|
}
|
||
|
|
|
||
|
|
func (a *app) say(f string, args ...any) { fmt.Fprintf(a.env.Stdout, f, args...) }
|
||
|
|
|
||
|
|
func (a *app) note(f string, args ...any) { fmt.Fprintf(a.env.Stderr, f, args...) }
|
||
|
|
|
||
|
|
// tr localizes a meta field.
|
||
|
|
func (a *app) tr(t catalog.Translations, field, base string) string {
|
||
|
|
return engine.Tr(t, a.locale, field, base)
|
||
|
|
}
|
||
|
|
|
||
|
|
func (a *app) readLine(r *bufio.Reader) (string, error) {
|
||
|
|
s, err := r.ReadString('\n')
|
||
|
|
if err != nil && (s == "" || !errors.Is(err, io.EOF)) {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
return strings.TrimSpace(s), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func sortedKeys[V any](m map[string]V) []string {
|
||
|
|
out := make([]string, 0, len(m))
|
||
|
|
for k := range m {
|
||
|
|
out = append(out, k)
|
||
|
|
}
|
||
|
|
sort.Strings(out)
|
||
|
|
return out
|
||
|
|
}
|
||
|
|
|
||
|
|
func wrap(s string, width int, indent string) string {
|
||
|
|
words := strings.Fields(s)
|
||
|
|
var b strings.Builder
|
||
|
|
line := 0
|
||
|
|
for _, w := range words {
|
||
|
|
if line > 0 && line+len(w)+1 > width {
|
||
|
|
b.WriteString("\n" + indent)
|
||
|
|
line = 0
|
||
|
|
} else if line > 0 {
|
||
|
|
b.WriteByte(' ')
|
||
|
|
line++
|
||
|
|
}
|
||
|
|
b.WriteString(w)
|
||
|
|
line += len(w)
|
||
|
|
}
|
||
|
|
return b.String()
|
||
|
|
}
|