solutions: Solutions Guide engine (catalog, rules, wizard state, native config, knowledge index, CLI)

New nested module yetano.dev/yetano/core/solutions: loads the catalog
in assets/solutions on top of the Big Picture, evaluates questions and
conditions, resolves packages/modules/capabilities, generates native
configuration from typed fragments with per-value origins, and builds
architecture graph, plan, lock file and handbook. Knowledge index with
yetano: references, search and lint (incl. manual sections). CLI with
yet's conventions (solution, task, knowledge, open), standalone as
yetano-solutions. No execution, no network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-12-01 08:42:58 +01:00
1 parent 586e76889c
commit 2481a0dd27
48 files changed
+10304

No files matched your search

+325
View File
@@ -0,0 +1,325 @@
// 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()
}
+149
View File
@@ -0,0 +1,149 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
type result struct {
code int
stdout, stderr string
}
func run(t *testing.T, store string, args ...string) result {
t.Helper()
var out, errb bytes.Buffer
code := Run(context.Background(), args, Env{
Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errb,
Program: "yet", StoreDir: store, Catalogs: []string{"../engine/testdata/cat"},
Getenv: func(string) string { return "" },
})
return result{code, out.String(), errb.String()}
}
// Scenario D: CI use without a terminal (ACC-D, CLI-03).
func TestNonInteractive(t *testing.T) {
store := t.TempDir()
out := filepath.Join(t.TempDir(), "gen")
// missing answers: exit 2, never a prompt
r := run(t, store, "solution", "setup", "app-run", "--json")
if r.code != ExitUsage || !strings.Contains(r.stdout, `"missing"`) || !strings.Contains(r.stdout, "hosts") {
t.Fatalf("missing: %d %s %s", r.code, r.stdout, r.stderr)
}
// invalid value: exit 2
if r := run(t, store, "solution", "setup", "app-run", "--set", "hosts=bad_host!"); r.code != ExitUsage {
t.Errorf("invalid value: %d %s", r.code, r.stderr)
}
// unknown question: exit 2
if r := run(t, store, "solution", "setup", "app-run", "--set", "nope=1"); r.code != ExitUsage {
t.Errorf("unknown question: %d", r.code)
}
// unknown solution: exit 3
if r := run(t, store, "solution", "show", "nope"); r.code != ExitNotFound {
t.Errorf("unknown solution: %d", r.code)
}
// complete: files written, instance saved
r = run(t, store, "solution", "setup", "app-run", "--set", "hosts=a.example.org", "--name", "prod", "--save", "--output", out)
if r.code != 0 {
t.Fatalf("setup: %d %s", r.code, r.stderr)
}
for _, f := range []string{"solution.yaml", "solution.lock.yaml", "config/app/app.yaml", "deployment-plan.yaml", "handbook/index.md", "architecture/graph.json"} {
if _, err := os.Stat(filepath.Join(out, f)); err != nil {
t.Errorf("missing %s", f)
}
}
// regenerate from the manifest: same files, exit 0
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out, "--locked"); r.code != 0 {
t.Fatalf("regenerate: %d %s", r.code, r.stderr)
}
// a hand edit: exit 4 (conflict)
os.WriteFile(filepath.Join(out, "config/app/app.yaml"), []byte("# mine\n"), 0o644)
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out); r.code != ExitConflict {
t.Errorf("hand edit: %d %s", r.code, r.stderr)
}
// stored instance works by name
if r := run(t, store, "solution", "validate", "prod"); r.code != 0 {
t.Errorf("validate prod: %d %s %s", r.code, r.stdout, r.stderr)
}
r = run(t, store, "solution", "instance", "list", "--json")
var rows []map[string]string
if err := json.Unmarshal([]byte(r.stdout), &rows); err != nil || len(rows) != 1 || rows[0]["status"] != "Configured" {
t.Errorf("instance list: %s %v", r.stdout, err)
}
// preset from it; a new instance needs only the instance-specific answer
if r := run(t, store, "solution", "preset", "save", "mine", "--from", "prod"); r.code != 0 {
t.Fatalf("preset: %d %s", r.code, r.stderr)
}
if r := run(t, store, "solution", "setup", "app-run", "--preset", "mine", "--set", "hosts=b.example.org", "--json"); r.code != 0 {
t.Errorf("setup with preset: %d %s", r.code, r.stderr)
}
// explain
r = run(t, store, "solution", "config", "explain", "prod", "app/app.yaml", "limits.max")
if r.code != 0 || !strings.Contains(r.stdout, "profile:app/base") {
t.Errorf("explain: %d %s %s", r.code, r.stdout, r.stderr)
}
}
func TestStateJSONIsTheAPI(t *testing.T) {
store := t.TempDir()
f := filepath.Join(t.TempDir(), "s.yaml")
os.WriteFile(f, []byte("apiVersion: yetano.dev/v1\nkind: WizardSession\nmetadata: {name: x}\nspec:\n solution: {id: app-run}\n mode: guided\n parameters: {hosts: [a.example.org], identity: central}\n"), 0o644)
r := run(t, store, "solution", "state", "--file", f)
var st map[string]any
if err := json.Unmarshal([]byte(r.stdout), &st); err != nil {
t.Fatalf("%v: %s %s", err, r.stdout, r.stderr)
}
if st["complete"] != false || st["next"] != "realm" {
t.Errorf("state: complete=%v next=%v", st["complete"], st["next"])
}
}
func TestSearchOpenKnowledge(t *testing.T) {
store := t.TempDir()
if r := run(t, store, "solution", "search", "run", "app"); r.code != 0 || !strings.Contains(r.stdout, "yetano:solution/app-run") {
t.Errorf("search: %d %s", r.code, r.stdout)
}
if r := run(t, store, "open", "yetano:solution/app-run"); r.code != 0 {
t.Errorf("open: %d %s", r.code, r.stderr)
}
if r := run(t, store, "open", "yetano:solution/missing"); r.code != ExitNotFound {
t.Errorf("open missing: %d", r.code)
}
if r := run(t, store, "open", "not a ref"); r.code != ExitUsage {
t.Errorf("open bad: %d", r.code)
}
if r := run(t, store, "solution", "catalog", "validate"); r.code != 0 {
t.Errorf("catalog validate: %d %s %s", r.code, r.stdout, r.stderr)
}
if r := run(t, store, "nonsense"); r.code != ExitUsage {
t.Errorf("unknown command: %d", r.code)
}
}
func TestInteractiveWizard(t *testing.T) {
store := t.TempDir()
out := filepath.Join(t.TempDir(), "gen")
var o, e bytes.Buffer
// size: Enter (default small), hosts: a.example.org, then actions: 6 export, 8 quit
in := strings.NewReader("\na.example.org\n6\n8\n")
code := Run(context.Background(), []string{"solution", "setup", "app-run", "--output", out}, Env{
Stdin: in, Stdout: &o, Stderr: &e, Interactive: true, Program: "yet", StoreDir: store,
Catalogs: []string{"../engine/testdata/cat"}, Getenv: func(string) string { return "" },
})
if code != 0 {
t.Fatalf("%d\n%s\n%s", code, o.String(), e.String())
}
for _, want := range []string{"[1/2] How big?", "(recommended)", "YOUR SOLUTION", "Actions:"} {
if !strings.Contains(o.String(), want) {
t.Errorf("output lacks %q:\n%s", want, o.String())
}
}
if _, err := os.Stat(filepath.Join(out, "config/app/app.yaml")); err != nil {
t.Error("export did not write the configuration")
}
}
+194
View File
@@ -0,0 +1,194 @@
package cli
import (
"context"
"errors"
"fmt"
"net"
"os"
"runtime"
"strings"
"syscall"
"time"
"yetano.dev/yetano/core/solutions/engine"
)
// doctor runs a state's requirement checks on this machine (DR-01/03).
// Only kinds it can really check get PASS/WARNING/ERROR; everything else
// stays NOT_CHECKED with the command to run -- never a fake PASS.
func (a *app) doctor(args []string) error {
fs := a.flags("solution doctor")
f := a.instFlags(fs)
offline := fs.Bool("offline", false, "skip checks that need the network (DNS)")
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(a.ctx, 30*time.Second)
defer cancel()
worst := 0
for i := range st.Checks {
c := &st.Checks[i]
if c.Status == engine.CheckNotApplicable {
continue
}
runCheck(ctx, c, *offline)
if c.Status == engine.CheckError || c.Status == engine.CheckBlocked {
worst = 1
}
}
if a.jsonOut {
if err := a.printJSON(map[string]any{"solution": st.Solution.ID, "instance": st.Instance, "checks": st.Checks}); err != nil {
return err
}
} else {
for _, c := range st.Checks {
a.say("%-14s %s\n", c.Status, c.Title)
if c.Note != "" {
a.say("%-14s %s\n", "", wrap(c.Note, 62, strings.Repeat(" ", 15)))
}
if c.Status == engine.CheckNotChecked && c.Run != "" {
a.say("%-14s run: %s\n", "", c.Run)
}
if (c.Status == engine.CheckWarning || c.Status == engine.CheckError) && c.Hint != "" {
a.say("%-14s hint: %s\n", "", wrap(c.Hint, 60, strings.Repeat(" ", 21)))
}
}
}
if worst > 0 {
return exitErr{ExitError, errors.New("")}
}
return nil
}
func sevStatus(sev string) string {
switch sev {
case "warning":
return engine.CheckWarning
case "info":
return engine.CheckInfo
}
return engine.CheckError
}
func runCheck(ctx context.Context, c *engine.CheckResult, offline bool) {
p := c.Params
switch c.Kind {
case "os":
want := strings.Split(p["want"], ",")
for _, w := range want {
if w == runtime.GOOS {
c.Status, c.Note = engine.CheckPass, runtime.GOOS
return
}
}
c.Status, c.Note = sevStatus(c.Severity), runtime.GOOS+" is not supported"
case "port":
var busy, denied []string
for _, port := range strings.Split(p["port"], ",") {
l, err := net.Listen("tcp", ":"+strings.TrimSpace(port))
if err == nil {
l.Close()
continue
}
if errors.Is(err, syscall.EACCES) || errors.Is(err, os.ErrPermission) {
denied = append(denied, port)
} else {
busy = append(busy, port)
}
}
switch {
case len(busy) > 0:
c.Status, c.Note = sevStatus(c.Severity), "in use: "+strings.Join(busy, ", ")
case len(denied) > 0:
c.Status, c.Note = engine.CheckNotChecked, "no permission to test port(s) "+strings.Join(denied, ", ")+" as this user"
default:
c.Status = engine.CheckPass
}
case "file":
var missing []string
for _, f := range strings.Split(p["paths"], ",") {
if _, err := os.Stat(strings.TrimSpace(f)); err != nil {
missing = append(missing, f)
}
}
if len(missing) > 0 {
c.Status, c.Note = sevStatus(c.Severity), "missing: "+strings.Join(missing, ", ")
} else {
c.Status = engine.CheckPass
}
case "dns":
if offline {
c.Status, c.Note = engine.CheckNotChecked, "offline"
return
}
dnsCheck(ctx, c)
case "manual":
c.Status = engine.CheckInfo
c.Note = "check this yourself"
default:
c.Status = engine.CheckNotChecked
}
}
func dnsCheck(ctx context.Context, c *engine.CheckResult) {
p := c.Params
r := net.DefaultResolver
var problems []string
names := strings.Split(p["names"], ",")
for _, name := range names {
name = p["prefix"] + strings.TrimSpace(name)
if name == "" {
continue
}
qctx, cancel := context.WithTimeout(ctx, 5*time.Second)
switch strings.ToUpper(p["type"]) {
case "MX":
mx, err := r.LookupMX(qctx, name)
if err != nil || len(mx) == 0 {
problems = append(problems, name+": no MX record")
break
}
if want := strings.TrimSuffix(p["want"], "."); want != "" {
ok := false
for _, m := range mx {
ok = ok || strings.EqualFold(strings.TrimSuffix(m.Host, "."), want)
}
if !ok {
problems = append(problems, fmt.Sprintf("%s: MX does not point to %s", name, want))
}
}
case "A":
if ips, err := r.LookupIPAddr(qctx, name); err != nil || len(ips) == 0 {
problems = append(problems, name+": does not resolve")
}
case "TXT":
txt, err := r.LookupTXT(qctx, name)
found := false
for _, t := range txt {
found = found || strings.Contains(t, p["contains"])
}
if err != nil || !found {
problems = append(problems, fmt.Sprintf("%s: no TXT record with %q", name, p["contains"]))
}
default:
c.Status = engine.CheckNotChecked
cancel()
return
}
cancel()
}
if ctx.Err() != nil {
c.Status, c.Note = engine.CheckNotChecked, "timed out"
return
}
if len(problems) > 0 {
c.Status, c.Note = sevStatus(c.Severity), strings.Join(problems, "; ")
return
}
c.Status = engine.CheckPass
}
+623
View File
@@ -0,0 +1,623 @@
package cli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"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/ref"
)
// ---- search --------------------------------------------------------------------
func (a *app) searchCmd(args []string, kinds []string) error {
fs := a.flags("search")
all := fs.Bool("all", false, "search everything (manuals, packages, Big Picture, ...)")
limit := fs.Int("limit", 8, "hits per group")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() == 0 {
return fail(ExitUsage, "usage: search <words>")
}
if err := a.load(); err != nil {
return err
}
if *all {
kinds = nil
}
groups := a.ix.Search(strings.Join(fs.Args(), " "), knowledge.SearchOptions{Kinds: kinds, Limit: *limit, Locale: a.locale})
if a.jsonOut {
if groups == nil {
groups = []knowledge.Group{}
}
return a.printJSON(groups)
}
if len(groups) == 0 {
a.note("nothing found\n")
return exitErr{ExitNotFound, errors.New("")}
}
for _, g := range groups {
a.say("%s\n", g.Title)
for _, h := range g.Hits {
a.say(" %-44s %s\n", trunc(h.Title, 44), h.Ref)
}
a.say("\n")
}
return nil
}
func trunc(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
}
// ---- instances --------------------------------------------------------------------
func (a *app) instance(args []string) error {
if len(args) == 0 {
args = []string{"list"}
}
fs := a.flags("solution instance " + args[0])
if err := a.parse(fs, args[1:]); err != nil {
return err
}
switch args[0] {
case "list", "ls":
inst, err := a.store.Instances()
if err != nil {
return err
}
sess, err := a.store.Sessions()
if err != nil {
return err
}
type row struct {
Name string `json:"name"`
Kind string `json:"kind"`
Solution string `json:"solution"`
Status string `json:"status"`
Updated string `json:"updated"`
}
var rows []row
for _, list := range [][]string{inst, sess} {
for _, n := range list {
in, err := a.store.LoadInstance(n)
if err != nil {
continue
}
status := "Draft"
if in.Kind == catalog.KindInstance {
status = "Configured"
if a.load() == nil {
if st, err := a.evaluate(in, nil); err == nil && !st.Complete {
status = "Invalid"
}
}
}
rows = append(rows, row{n, in.Kind, in.Spec.Solution.ID, status, in.Metadata.Updated})
}
}
if a.jsonOut {
if rows == nil {
rows = []row{}
}
return a.printJSON(rows)
}
if len(rows) == 0 {
a.note("no saved solutions (save one with: %s solution setup <id> --save)\n", a.env.Program)
}
for _, r := range rows {
a.say("%-24s %-14s %-11s %s\n", r.Name, r.Solution, r.Status, r.Updated)
}
return nil
case "show", "export":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance %s <name>", a.env.Program, args[0])
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(in)
}
b, err := engine.Marshal(in)
if err != nil {
return err
}
a.say("%s", b)
return nil
case "import":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance import <file>", a.env.Program)
}
f, err := os.Open(fs.Arg(0))
if err != nil {
return fail(ExitNotFound, "%v", err)
}
defer f.Close()
in, err := engine.ReadInstance(f)
if err != nil {
return fail(ExitUsage, "%v", err)
}
if err := a.load(); err != nil {
return err
}
if _, err := a.evaluate(in, nil); err != nil {
return err
}
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("imported %s\n", in.Metadata.Name)
return nil
case "delete", "rm":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance delete <name>", a.env.Program)
}
return a.store.DeleteInstance(fs.Arg(0))
case "duplicate", "cp":
if fs.NArg() != 2 {
return fail(ExitUsage, "usage: %s solution instance duplicate <name> <new-name>", a.env.Program)
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
in.Metadata.Name, in.Metadata.Created = fs.Arg(1), ""
return a.store.SaveInstance(in)
case "favorite":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance favorite <name>", a.env.Program)
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
in.Metadata.Favorite = !in.Metadata.Favorite
return a.store.SaveInstance(in)
}
return a.usage("solution instance " + args[0])
}
// ---- presets ------------------------------------------------------------------------
func (a *app) preset(args []string) error {
if len(args) == 0 {
args = []string{"list"}
}
fs := a.flags("solution preset " + args[0])
from := fs.String("from", "", "save: the instance to take the answers from")
file := fs.String("file", "", "save: a solution.yaml to take the answers from")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
switch args[0] {
case "list", "ls":
names, err := a.store.Presets()
if err != nil {
return err
}
if a.jsonOut {
if names == nil {
names = []string{}
}
return a.printJSON(names)
}
for _, n := range names {
p, err := a.store.LoadPreset(n)
if err != nil {
continue
}
a.say("%-24s %-14s %d answer(s)\n", n, p.Spec.Solution, len(p.Spec.Parameters))
}
return nil
case "save":
if fs.NArg() != 1 || (*from == "" && *file == "") {
return fail(ExitUsage, "usage: %s solution preset save <name> --from <instance> | --file <solution.yaml>", a.env.Program)
}
if err := a.load(); err != nil {
return err
}
var in *engine.Instance
var err error
if *file != "" {
in, err = a.instanceFrom(*file, fs)
} else {
in, err = a.store.LoadInstance(*from)
}
if err != nil {
return err
}
s := a.cat.Lookup(in.Spec.Solution.ID)
if s == nil {
return fmt.Errorf("%w: solution %s", engine.ErrNotFound, in.Spec.Solution.ID)
}
p := engine.PresetFrom(fs.Arg(0), in, s)
if err := a.store.SavePreset(p); err != nil {
return err
}
a.note("saved preset %s (%d answers; instance-specific and secret answers are left out)\n", p.Metadata.Name, len(p.Spec.Parameters))
return nil
case "show", "export":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset show <name>", a.env.Program)
}
p, err := a.store.LoadPreset(fs.Arg(0))
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(p)
}
b, _ := engine.Marshal(p)
a.say("%s", b)
return nil
case "import":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset import <file>", a.env.Program)
}
f, err := os.Open(fs.Arg(0))
if err != nil {
return fail(ExitNotFound, "%v", err)
}
defer f.Close()
p, err := engine.ReadPreset(f)
if err != nil {
return fail(ExitUsage, "%v", err)
}
return a.store.SavePreset(p)
case "delete", "rm":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset delete <name>", a.env.Program)
}
return a.store.DeletePreset(fs.Arg(0))
}
return a.usage("solution preset " + args[0])
}
// ---- catalog --------------------------------------------------------------------------
func (a *app) catalogCmd(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s solution catalog validate|test|coverage", a.env.Program)
}
fs := a.flags("solution catalog " + args[0])
update := fs.Bool("update", false, "test: rewrite the golden files")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
var ee exitErr
if a.cat != nil && !errors.As(err, &ee) {
// print every load issue, not just the first
for _, i := range a.cat.Issues {
a.note("%s\n", i)
}
}
return err
}
switch args[0] {
case "validate", "lint":
issues := knowledge.Lint(a.ix)
errs := 0
for _, i := range issues {
if i.Severity == "error" {
errs++
}
}
if a.jsonOut {
if issues == nil {
issues = []catalog.Issue{}
}
_ = a.printJSON(issues)
} else {
for _, i := range issues {
a.say("%-7s %s\n", strings.ToUpper(i.Severity), i)
}
a.note("%d solution(s), %d task(s), %d package(s), %d capabilities, %d manual topics: %d error(s), %d warning(s)\n",
len(a.cat.Solutions), len(a.cat.Tasks), len(a.cat.Packages), len(a.cat.Capabilities), len(a.ix.Topics), errs, len(issues)-errs)
}
if errs > 0 {
return exitErr{ExitError, errors.New("")}
}
return nil
case "test":
return a.catalogTest(*update)
case "schema":
dir := filepath.Join(a.cat.Root, "schema")
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
for _, name := range sortedKeys(catalog.SchemaKinds) {
b, err := json.MarshalIndent(catalog.JSONSchema(name), "", " ")
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, name+".schema.json"), append(b, '\n'), 0o644); err != nil {
return err
}
}
a.note("wrote %d schemas to %s\n", len(catalog.SchemaKinds), dir)
return nil
case "coverage":
cov := knowledge.ComputeCoverage(a.ix)
if a.jsonOut {
return a.printJSON(cov)
}
a.say("Yetano Knowledge Coverage (%d packages in the catalog)\n\n", cov.Packages)
for _, m := range cov.Metrics {
a.say(" %-38s %5.1f%% (%d/%d)\n", m.Name, m.Pct, m.Have, m.Total)
}
if len(cov.ProgramsWithout) > 0 {
a.say("\nBig Picture programs not in the catalog yet: %s\n", strings.Join(cov.ProgramsWithout, ", "))
}
return nil
}
return a.usage("solution catalog " + args[0])
}
// catalogTest evaluates every example, generates its output and compares
// it with the golden files next to the solution (EX-02, QS-08). An example
// that stops being complete or changes output fails (ACC-J).
func (a *app) catalogTest(update bool) error {
failed := 0
for _, key := range catalog.SortedIDs(a.cat.Examples) {
x := a.cat.Examples[key]
s := a.cat.Lookup(x.Spec.Solution)
in := engine.NewInstance(x.Meta.ID, s, x.Spec.Mode)
in.Kind = catalog.KindInstance
for k, v := range x.Spec.Parameters {
in.Spec.Parameters[k] = v
}
in.Spec.Locale = "en"
st, err := a.eng.Evaluate(in, nil)
if err != nil {
return err
}
out, err := a.eng.Generate(st, in, nil, false)
if err != nil {
a.say("FAIL %s: %v\n", key, err)
failed++
continue
}
dir := filepath.Join(a.cat.Root, filepath.FromSlash(path.Dir(path.Dir(x.File))), "testdata", x.Meta.ID)
if update {
if err := os.RemoveAll(dir); err != nil {
return err
}
for _, f := range out.Files {
if f.Kind == "lock" {
continue // hashes of the whole catalog: not stable across unrelated edits
}
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
if err := os.WriteFile(p, f.Content, 0o644); err != nil {
return err
}
}
a.say("UPDATED %s (%d files)\n", key, len(out.Files)-1)
continue
}
var diffs []string
want := map[string]bool{}
for _, f := range out.Files {
if f.Kind == "lock" {
continue
}
want[f.Path] = true
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f.Path)))
if err != nil {
diffs = append(diffs, f.Path+" (no golden file)")
} else if !bytes.Equal(b, f.Content) {
diffs = append(diffs, f.Path+" ("+firstDiff(b, f.Content)+")")
}
}
_ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
if err == nil && !d.IsDir() {
rel, _ := filepath.Rel(dir, p)
if !want[filepath.ToSlash(rel)] {
diffs = append(diffs, filepath.ToSlash(rel)+" (no longer generated)")
}
}
return nil
})
sort.Strings(diffs)
if len(diffs) > 0 {
a.say("FAIL %s\n", key)
for _, d := range diffs {
a.say(" %s\n", d)
}
failed++
continue
}
a.say("ok %s\n", key)
}
if failed > 0 {
a.note("%d example(s) failed; after an intended change: make golden (catalog test --update) and review the diff\n", failed)
return exitErr{ExitError, errors.New("")}
}
return nil
}
func firstDiff(a, b []byte) string {
la, lb := strings.Split(string(a), "\n"), strings.Split(string(b), "\n")
for i := 0; i < len(la) || i < len(lb); i++ {
var x, y string
if i < len(la) {
x = la[i]
}
if i < len(lb) {
y = lb[i]
}
if x != y {
return fmt.Sprintf("line %d: golden %q, now %q", i+1, trunc(x, 50), trunc(y, 50))
}
}
return "differs"
}
// ---- knowledge, open ------------------------------------------------------------------
func (a *app) knowledge(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s knowledge search|show|status|backlinks|coverage|validate", a.env.Program)
}
switch args[0] {
case "search":
return a.searchCmd(args[1:], nil)
case "show":
return a.open(args[1:])
case "validate", "lint":
return a.catalogCmd(append([]string{"validate"}, args[1:]...))
case "coverage":
return a.catalogCmd(append([]string{"coverage"}, args[1:]...))
case "status", "index":
fs := a.flags("knowledge " + args[0])
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
kinds := map[string]int{}
for _, e := range a.ix.Entries {
kinds[e.Kind]++
}
st := map[string]any{"catalog": a.cat.Root, "id": a.cat.Meta.ID, "version": a.cat.Meta.Version, "hash": a.cat.Hash(),
"entries": len(a.ix.Entries), "byKind": kinds, "manualTopics": len(a.ix.Topics), "sourcesNotAvailable": a.ix.Missing}
if args[0] == "index" {
st["index"] = a.ix.Entries
}
if a.jsonOut {
return a.printJSON(st)
}
a.say("catalog %s %s (%s)\nentries %d\n", a.cat.Meta.ID, a.cat.Meta.Version, a.cat.Root, len(a.ix.Entries))
for _, k := range sortedKeys(kinds) {
a.say(" %-12s %d\n", k, kinds[k])
}
if len(a.ix.Missing) > 0 {
a.say("not available locally: %s\n", strings.Join(a.ix.Missing, ", "))
}
return nil
case "backlinks":
fs := a.flags("knowledge backlinks")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s knowledge backlinks <yetano:ref>", a.env.Program)
}
bl := a.ix.BacklinksOf(fs.Arg(0))
if a.jsonOut {
if bl == nil {
bl = []string{}
}
return a.printJSON(bl)
}
for _, b := range bl {
a.say("%s\n", b)
}
return nil
}
return a.usage("knowledge " + args[0])
}
// open shows a reference in the terminal (REF-04): manual text, a
// solution's details, or where it lives.
func (a *app) open(args []string) error {
fs := a.flags("open")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s open <yetano:reference>", a.env.Program)
}
if err := a.load(); err != nil {
return err
}
r := fs.Arg(0)
if !strings.HasPrefix(r, "yetano:") {
r = "yetano:" + r
}
res, err := a.ix.Resolve(r)
if err != nil {
return fail(ExitUsage, "%v", err)
}
if !res.Exists {
return fmt.Errorf("%w: %s", engine.ErrNotFound, r)
}
if !res.SectionExists {
return fmt.Errorf("%w: %s has no such section", engine.ErrNotFound, r)
}
if a.jsonOut {
return a.printJSON(res)
}
p, _ := ref.Parse(r)
switch p.Kind {
case ref.Solution:
return a.show([]string{p.Path[0]}, false)
case ref.Task:
return a.show([]string{p.Path[0]}, true)
case ref.Package:
return a.packageCmd([]string{p.Path[0]})
case ref.Manual:
if _, md, err := a.ix.Read(r); err == nil {
a.say("%s", md)
return nil
}
case ref.Example:
if x := a.cat.Examples[p.Path[0]+"/"+p.Path[1]]; x != nil {
b, _ := engine.Marshal(x.Spec)
a.say("# %s\n%s", x.Meta.Title, b)
return nil
}
case ref.Profile:
if pr := a.cat.Profiles[p.Path[0]+"/"+p.Path[1]]; pr != nil {
b, _ := engine.Marshal(pr.Spec)
a.say("# %s\n%s", firstNonEmpty(pr.Meta.Title, pr.Meta.ID), b)
return nil
}
case ref.Capability:
a.say("%s -- %s\n", res.Title, res.Summary)
for _, pr := range a.cat.ProvidersOf(p.Path[0]) {
a.say(" provided by %s\n", pr)
}
for _, b := range a.ix.BacklinksOf(r) {
a.say(" used by %s\n", b)
}
return nil
}
a.say("%s\n", res.Title)
if res.Summary != "" {
a.say("%s\n", wrap(res.Summary, 76, ""))
}
if res.Web != "" {
a.say("web: %s\n", res.Web)
}
if res.CLI != "" {
a.say("cli: %s\n", res.CLI)
}
if res.Note != "" {
a.say("note: %s\n", res.Note)
}
return nil
}
+494
View File
@@ -0,0 +1,494 @@
package cli
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/engine"
"yetano.dev/yetano/core/solutions/ref"
"yetano.dev/yetano/core/solutions/store"
)
func (a *app) setup(args []string, task bool) error {
cmd := "solution setup"
if task {
cmd = "task run"
}
fs := a.flags(cmd)
quick := fs.Bool("quick", false, "quick setup: only what is needed, recommended defaults")
guided := fs.Bool("guided", false, "guided setup: the relevant choices, with explanations")
advanced := fs.Bool("advanced", false, "advanced setup: every option")
presetName := fs.String("preset", "", "take answers from a saved preset")
example := fs.String("example", "", "start from an example of the solution")
answers := fs.String("answers", "", "start from the answers in a solution.yaml")
name := fs.String("name", "", "name of the instance (default: the solution ID)")
output := fs.String("output", "", "generate the files into this directory when complete")
save := fs.Bool("save", false, "save the instance (incomplete: as a draft session)")
nonInteractive := fs.Bool("non-interactive", false, "never ask; fail listing what is missing (the default without a terminal)")
platform := fs.String("platform", "", "target platform (linux, freebsd, darwin, windows)")
force := fs.Bool("force", false, "with --output: overwrite files changed by hand")
var sets multi
fs.Var(&sets, "set", "answer as question=value (repeatable; lists comma-separated)")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s %s <id> [--quick|--guided|--advanced] [--set q=v]...", a.env.Program, cmd)
}
if err := a.load(); err != nil {
return err
}
s, err := a.lookup(fs.Arg(0), task)
if err != nil {
return err
}
mode := catalog.LevelQuick
switch {
case *advanced:
mode = catalog.LevelAdvanced
case *guided:
mode = catalog.LevelGuided
}
nm := firstNonEmpty(*name, s.Meta.ID)
if err := store.ValidName(nm); err != nil {
return fail(ExitUsage, "%v", err)
}
in := engine.NewInstance(nm, s, mode)
in.Spec.Locale = a.locale
in.Spec.Platform = *platform
if *example != "" {
x := a.cat.Examples[s.Meta.ID+"/"+*example]
if x == nil {
return fmt.Errorf("%w: example %s of %s", engine.ErrNotFound, *example, s.Meta.ID)
}
for k, v := range x.Spec.Parameters {
in.Spec.Parameters[k] = v
}
if !*quick && !*guided && !*advanced && x.Spec.Mode != "" {
in.Spec.Mode = x.Spec.Mode
}
}
if *answers != "" {
f, err := os.Open(*answers)
if err != nil {
return fail(ExitNotFound, "%v", err)
}
from, err := engine.ReadInstance(f)
f.Close()
if err != nil {
return fail(ExitUsage, "%s: %v", *answers, err)
}
for k, v := range from.Spec.Parameters {
in.Spec.Parameters[k] = v
}
in.Spec.Overrides = from.Spec.Overrides
}
for _, kv := range sets {
k, v, ok := strings.Cut(kv, "=")
if !ok {
return fail(ExitUsage, "--set %q: want question=value", kv)
}
if q, _ := s.Question(k); q == nil {
return fail(ExitUsage, "--set %s: %s has no question %q", kv, s.Meta.ID, k)
}
in.Spec.Parameters[k] = v
}
var preset *engine.Preset
if *presetName != "" {
preset, err = a.presetFor(in, *presetName)
if err != nil {
return err
}
in.Spec.Preset = preset.Metadata.Name
if preset.Spec.Mode != "" && !*quick && !*guided && !*advanced {
in.Spec.Mode = preset.Spec.Mode
}
}
kind := ref.Solution
if task {
kind = ref.Task
}
_ = a.store.Touch(ref.For(kind, s.Meta.ID), nm)
if a.env.Interactive && !*nonInteractive && !a.jsonOut {
return a.wizard(in, preset, *output, *force)
}
st, err := a.evaluate(in, preset)
if err != nil {
return err
}
if !st.Complete {
if *save {
in.Kind = catalog.KindSession
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("saved draft %s\n", nm)
}
if a.jsonOut {
_ = a.printJSON(map[string]any{"complete": false, "missing": st.Progress.Missing, "messages": st.Messages, "state": st})
return exitErr{ExitUsage, errors.New("")}
}
for _, m := range st.Progress.Missing {
q := findQ(st, m)
a.note("missing: %s (%s) -- --set %s=...\n", m, q.Title, m)
}
for _, q := range st.Questions {
for _, e := range q.Errors {
a.note("invalid: %s: %s\n", q.ID, e)
}
}
a.printMessages(st)
return fmt.Errorf("%w (%s)", engine.ErrIncomplete, strings.Join(st.Progress.Missing, ", "))
}
if *save {
in.Kind = catalog.KindInstance
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("saved instance %s\n", nm)
}
if *output != "" {
return a.writeOut(in, st, *output, *force, false, false)
}
if a.jsonOut {
return a.printJSON(st)
}
a.summary(st)
b, _ := engine.Marshal(in)
a.note("\nAnswers (save with --save, or as solution.yaml for '%s solution generate --file'):\n", a.env.Program)
a.say("%s", b)
return nil
}
func findQ(st *engine.State, id string) engine.QuestionState {
for _, q := range st.Questions {
if q.ID == id {
return q
}
}
return engine.QuestionState{ID: id}
}
// summary prints "YOUR SOLUTION" (CLI-02).
func (a *app) summary(st *engine.State) {
w := a.env.Stdout
line := strings.Repeat("-", 60)
fmt.Fprintf(w, "%s\nYOUR SOLUTION: %s\n\n", line, st.Solution.Title)
fmt.Fprintf(w, "Packages:\n")
for _, p := range st.Packages {
if p.Selected {
var mods []string
for _, m := range p.Modules {
if m.Enabled && m.Program != "" {
mods = append(mods, m.Program)
}
}
fmt.Fprintf(w, " + %-10s %s\n", p.ID, strings.Join(mods, " "))
}
}
for _, p := range st.Packages {
if !p.Selected {
fmt.Fprintf(w, " ? %-10s recommended: %s\n", p.ID, strings.Join(p.Reasons, "; "))
}
}
fmt.Fprintf(w, "\nCapabilities:\n")
for _, c := range st.Capabilities {
switch c.Status {
case engine.StRequired, engine.StSelected, engine.StExternal:
fmt.Fprintf(w, " + %s\n", c.Title)
case engine.StRecommended:
fmt.Fprintf(w, " ? %s (recommended)\n", c.Title)
case engine.StMissing, engine.StConflicting:
fmt.Fprintf(w, " ! %s (%s)\n", c.Title, c.Status)
}
}
fmt.Fprintf(w, "\nConfiguration: %d file(s)", len(st.Files))
if st.Complete {
fmt.Fprintf(w, ", complete\n")
} else {
fmt.Fprintf(w, ", INCOMPLETE: %s\n", strings.Join(st.Progress.Missing, ", "))
}
if len(st.Messages) > 0 {
fmt.Fprintf(w, "\nNotes:\n")
for _, m := range st.Messages {
fmt.Fprintf(w, " %-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 66, " "))
}
}
nc := 0
for _, c := range st.Checks {
if c.Status == engine.CheckNotChecked {
nc++
}
}
if nc > 0 {
fmt.Fprintf(w, "\nEnvironment: %d check(s) not run yet -- '%s solution doctor' runs them on the target.\n", nc, a.env.Program)
}
fmt.Fprintf(w, "%s\n", line)
}
// wizard is the interactive CLI wizard (CLI-02). All decisions come from
// the engine: this only asks what the state says, in its order.
func (a *app) wizard(in *engine.Instance, preset *engine.Preset, output string, force bool) error {
r := bufio.NewReader(a.env.Stdin)
w := a.env.Stdout
done := map[string]bool{}
var history []string
st, err := a.evaluate(in, preset)
if err != nil {
return err
}
fmt.Fprintf(w, "Yetano Solutions Guide\n%s\n%s (%s setup)\n\n", strings.Repeat("-", 40), st.Solution.Title, st.Mode)
fmt.Fprintf(w, "Enter keeps the value in [brackets]. ? explains, m manual, a architecture, b back, q save and quit.\n\n")
for {
st, err = a.evaluate(in, preset)
if err != nil {
return err
}
var q *engine.QuestionState
for i := range st.Questions {
x := &st.Questions[i]
if x.Visible && x.Asked && !done[x.ID] {
q = x
break
}
}
if q == nil {
break
}
step, total := 0, 0
for _, x := range st.Questions {
if x.Visible && x.Asked {
total++
if done[x.ID] || x.ID == q.ID {
step++
}
}
}
fmt.Fprintf(w, "[%d/%d] %s\n", step, total, q.Title)
if q.Help != "" {
fmt.Fprintf(w, " %s\n", wrap(q.Help, 70, " "))
}
for i, o := range q.Options {
mark := " "
if !o.Enabled {
mark = "x"
}
rec := ""
if o.Recommended {
rec = " (recommended)"
}
fmt.Fprintf(w, " %s %d. %s%s\n", mark, i+1, o.Title, rec)
if !o.Enabled && o.Disabled != "" {
fmt.Fprintf(w, " not available: %s\n", wrap(o.Disabled, 62, " "))
}
}
def := ""
if q.Value != nil {
def = displayValue(q, q.Value)
}
prompt := "> "
if def != "" {
prompt = fmt.Sprintf("[%s] > ", def)
}
fmt.Fprint(w, prompt)
line, err := a.readLine(r)
if err != nil {
fmt.Fprintln(w)
return a.saveDraft(in, "input ended")
}
switch line {
case "?":
a.explain(q)
continue
case "m":
a.showManual(q, st)
continue
case "a":
fmt.Fprintf(w, "\n%s\n", engine.GraphText(st.Graph))
continue
case "b":
if len(history) > 0 {
last := history[len(history)-1]
history = history[:len(history)-1]
delete(done, last)
}
continue
case "q":
return a.saveDraft(in, "")
case "":
if q.Value == nil && q.Required {
fmt.Fprintf(w, " an answer is needed\n")
continue
}
if q.Value != nil {
in.Spec.Parameters[q.ID] = q.Value
}
default:
in.Spec.Parameters[q.ID] = line
}
st2, err := a.evaluate(in, preset)
if err != nil {
return err
}
if q2 := findQ(st2, q.ID); len(q2.Errors) > 0 {
fmt.Fprintf(w, " %s\n", strings.Join(q2.Errors, "; "))
delete(in.Spec.Parameters, q.ID)
continue
}
for _, s := range st2.Stale {
if s.Question == q.ID {
fmt.Fprintf(w, " %s\n", s.Reason)
delete(in.Spec.Parameters, q.ID)
goto next
}
}
done[q.ID] = true
history = append(history, q.ID)
fmt.Fprintln(w)
next:
}
a.summary(st)
for {
fmt.Fprintf(w, "\nActions:\n 1. Show configuration\n 2. Show architecture\n 3. Show plan\n 4. Read related manual\n 5. Save solution\n 6. Export configuration (generate files)\n 7. Change an answer\n 8. Quit\n> ")
line, err := a.readLine(r)
if err != nil {
return nil
}
switch line {
case "1":
for _, f := range st.Files {
fmt.Fprintf(w, "--- %s\n%s\n", f.Path, f.Content)
}
case "2":
fmt.Fprintf(w, "%s", engine.GraphText(st.Graph))
case "3":
for i, s := range st.Steps {
fmt.Fprintf(w, "%3d. [%s] %s\n", i+1, s.Phase, s.Title)
if s.Run != "" {
fmt.Fprintf(w, " $ %s\n", s.Run)
}
}
case "4":
for _, rf := range st.References {
if res, err := a.ix.Resolve(rf); err == nil {
fmt.Fprintf(w, " %s\n", refLine(res))
}
}
case "5":
in.Kind = catalog.KindInstance
if !st.Complete {
in.Kind = catalog.KindSession
}
if err := a.store.SaveInstance(in); err != nil {
return err
}
fmt.Fprintf(w, "saved %s (%s)\n", in.Metadata.Name, in.Kind)
case "6":
dir := output
if dir == "" {
fmt.Fprintf(w, "directory [./%s] > ", in.Metadata.Name)
d, _ := a.readLine(r)
dir = firstNonEmpty(d, "./"+in.Metadata.Name)
}
if err := a.writeOut(in, st, dir, force, false, false); err != nil {
fmt.Fprintf(w, "error: %v\n", err)
}
case "7":
fmt.Fprintf(w, "question id > ")
id, _ := a.readLine(r)
if _, ok := in.Spec.Parameters[id]; ok || findQ(st, id).Title != "" {
delete(in.Spec.Parameters, id)
return a.wizard(in, preset, output, force)
}
fmt.Fprintf(w, "no such question\n")
case "8", "q", "":
return nil
}
}
}
func (a *app) saveDraft(in *engine.Instance, why string) error {
in.Kind = catalog.KindSession
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("saved the draft as %s; continue with '%s solution setup %s --answers <(%s solution instance export %s)'\n",
in.Metadata.Name, a.env.Program, in.Spec.Solution.ID, a.env.Program, in.Metadata.Name)
if why != "" {
return fail(ExitUsage, "%s", why)
}
return nil
}
func displayValue(q *engine.QuestionState, v any) string {
if l, ok := v.([]any); ok {
var parts []string
for _, x := range l {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ", ")
}
s := catalog.Scalar(v)
for i, o := range q.Options {
if o.ID == s {
return fmt.Sprintf("%d", i+1)
}
}
return s
}
// explain is "Help me decide" (HELP-01/02).
func (a *app) explain(q *engine.QuestionState) {
w := a.env.Stdout
if q.Decide != "" {
fmt.Fprintf(w, "\n %s\n", wrap(q.Decide, 72, " "))
}
if q.Description != "" {
fmt.Fprintf(w, "\n %s\n", wrap(q.Description, 72, " "))
}
for _, o := range q.Options {
line := o.Title
if o.Description != "" {
line += ": " + o.Description
}
if o.Recommended && o.Reason != "" {
line += " Recommended: " + o.Reason
}
if !o.Enabled {
line += " Not available: " + o.Disabled
}
fmt.Fprintf(w, " - %s\n", wrap(line, 70, " "))
}
if q.Recommended != nil && q.Reason != "" {
fmt.Fprintf(w, " Recommended: %v -- %s\n", q.Recommended, q.Reason)
}
fmt.Fprintln(w)
}
func (a *app) showManual(q *engine.QuestionState, st *engine.State) {
w := a.env.Stdout
refs := append([]string{}, q.References...)
for _, o := range q.Options {
refs = append(refs, o.References...)
}
refs = append(refs, st.References...)
for _, r := range refs {
if !strings.HasPrefix(r, "yetano:manual/") {
continue
}
title, md, ok := a.ix.Excerpt(r, 30)
res, _ := a.ix.Resolve(r)
if !ok {
fmt.Fprintf(w, "\n %s\n\n", refLine(res))
return
}
fmt.Fprintf(w, "\n=== %s\n%s\n=== full text: %s\n\n", title, md, firstNonEmpty(res.CLI, res.File))
return
}
fmt.Fprintf(w, " no manual reference for this question\n")
}
+727
View File
@@ -0,0 +1,727 @@
package cli
import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/engine"
"yetano.dev/yetano/core/solutions/knowledge"
"yetano.dev/yetano/core/solutions/ref"
"yetano.dev/yetano/core/solutions/store"
)
// multi is a repeatable flag.
type multi []string
func (m *multi) String() string { return strings.Join(*m, ",") }
func (m *multi) Set(s string) error { *m = append(*m, s); return nil }
func (a *app) solution(args []string) error {
if len(args) == 0 {
return a.usage("")
}
sub, rest := args[0], args[1:]
switch sub {
case "list", "ls":
return a.list(rest, false)
case "search":
return a.searchCmd(rest, []string{ref.Solution, ref.Task, ref.Example})
case "show":
return a.show(rest, false)
case "setup", "new":
return a.setup(rest, false)
case "state", "evaluate":
return a.stateCmd(rest)
case "generate":
return a.generate(rest)
case "validate":
return a.validate(rest)
case "plan":
return a.plan(rest)
case "doctor":
return a.doctor(rest)
case "config":
return a.config(rest)
case "architecture", "arch":
return a.architecture(rest)
case "handbook":
return a.handbook(rest)
case "package":
return a.packageCmd(rest)
case "instance", "instances":
return a.instance(rest)
case "preset", "presets":
return a.preset(rest)
case "catalog":
return a.catalogCmd(rest)
}
return a.usage("solution " + sub)
}
func (a *app) task(args []string) error {
if len(args) == 0 {
return a.usage("")
}
sub, rest := args[0], args[1:]
switch sub {
case "list", "ls":
return a.list(rest, true)
case "search":
return a.searchCmd(rest, []string{ref.Task})
case "show":
return a.show(rest, true)
case "run", "setup":
return a.setup(rest, true)
}
return a.usage("task " + sub)
}
// ---- list, show ------------------------------------------------------------
type listItem struct {
ID string `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Summary string `json:"summary"`
Category string `json:"category,omitempty"`
Status catalog.Support `json:"status"`
Featured bool `json:"featured,omitempty"`
TaskKind string `json:"taskKind,omitempty"`
}
func (a *app) items(tasks bool) []listItem {
m := a.cat.Solutions
if tasks {
m = a.cat.Tasks
}
var out []listItem
for _, id := range catalog.SortedIDs(m) {
s := m[id]
e := a.ix.Entry(ref.For(map[bool]string{false: ref.Solution, true: ref.Task}[tasks], id))
title, summary := s.Meta.Title, s.Meta.Summary
if e != nil {
title, summary = e.Title, e.Summary
}
st := s.Meta.Status
if st == "" {
st = catalog.Supported
}
out = append(out, listItem{ID: id, Kind: strings.ToLower(s.Kind), Title: a.tr(s.Meta.Translations, "title", title),
Summary: a.tr(s.Meta.Translations, "summary", summary), Category: s.Meta.Category, Status: st, Featured: s.Meta.Featured, TaskKind: s.Spec.Kind})
}
return out
}
func (a *app) list(args []string, tasks bool) error {
fs := a.flags("list")
category := fs.String("category", "", "only this category")
if err := a.parse(fs, args); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
items := a.items(tasks)
if *category != "" {
var f []listItem
for _, it := range items {
if it.Category == *category {
f = append(f, it)
}
}
items = f
}
if a.jsonOut {
if items == nil {
items = []listItem{}
}
return a.printJSON(items)
}
for _, it := range items {
mark := ""
if it.Status != catalog.Supported {
mark = " [" + string(it.Status) + "]"
}
a.say("%-22s %s%s\n%-22s %s\n", it.ID, it.Title, mark, "", wrap(it.Summary, 70, strings.Repeat(" ", 23)))
}
if len(items) == 0 {
a.note("nothing found\n")
}
return nil
}
func (a *app) lookup(id string, tasks bool) (*catalog.Solution, error) {
s := a.cat.Lookup(id)
if s == nil {
var hint string
if groups := a.ix.Search(id, knowledge.SearchOptions{Kinds: []string{ref.Solution, ref.Task}, Limit: 3}); len(groups) > 0 {
hint = " -- did you mean " + strings.TrimPrefix(strings.TrimPrefix(groups[0].Hits[0].Ref, "yetano:solution/"), "yetano:task/") + "?"
}
return nil, fmt.Errorf("%w: %s%s", engine.ErrNotFound, id, hint)
}
return s, nil
}
type showOut struct {
listItem
Goals []string `json:"goals,omitempty"`
Scenarios []string `json:"scenarios,omitempty"`
NotFor []string `json:"notFor,omitempty"`
Outcome string `json:"outcome,omitempty"`
Packages []string `json:"packages"`
Capabilities catalog.CapSets `json:"capabilities"`
Platforms []string `json:"platforms,omitempty"`
Questions int `json:"questions"`
Quick []string `json:"quickQuestions"`
Examples []map[string]string `json:"examples"`
References []knowledge.Resolution `json:"references"`
Related []string `json:"related,omitempty"`
Backlinks []string `json:"backlinks,omitempty"`
Version string `json:"version"`
}
func (a *app) show(args []string, tasks bool) error {
fs := a.flags("show")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s %s show <id>", a.env.Program, map[bool]string{false: "solution", true: "task"}[tasks])
}
if err := a.load(); err != nil {
return err
}
s, err := a.lookup(fs.Arg(0), tasks)
if err != nil {
return err
}
var item listItem
for _, it := range a.items(s.IsTask()) {
if it.ID == s.Meta.ID {
item = it
}
}
o := showOut{listItem: item, Goals: s.Spec.Goals, Scenarios: s.Spec.Scenarios, NotFor: s.Spec.NotFor,
Capabilities: s.Spec.Capabilities, Platforms: s.Spec.Platforms, Questions: len(s.Spec.Questions), Related: s.Spec.Related,
Version: s.Meta.Version, Examples: []map[string]string{}}
if bp := a.cat.BigPicture; bp != nil {
if g, ok := bp.Stories[s.Spec.BigPicture]; ok {
o.Outcome = g.Outcome
}
}
seen := map[string]bool{}
for _, p := range s.Spec.Packages {
if !seen[p.ID] {
seen[p.ID] = true
o.Packages = append(o.Packages, p.ID)
}
}
for _, q := range s.Spec.Questions {
if q.Level == "" || q.Level == catalog.LevelQuick {
o.Quick = append(o.Quick, q.ID)
}
}
for _, k := range catalog.SortedIDs(a.cat.Examples) {
x := a.cat.Examples[k]
if x.Spec.Solution == s.Meta.ID {
o.Examples = append(o.Examples, map[string]string{"id": x.Meta.ID, "title": a.tr(x.Meta.Translations, "title", x.Meta.Title), "summary": x.Meta.Summary})
}
}
for _, r := range s.Spec.References.All() {
if res, err := a.ix.Resolve(r); err == nil {
o.References = append(o.References, res)
}
}
kind := ref.Solution
if s.IsTask() {
kind = ref.Task
}
o.Backlinks = a.ix.BacklinksOf(ref.For(kind, s.Meta.ID))
if a.jsonOut {
return a.printJSON(o)
}
a.say("%s (%s %s, %s)\n\n", o.Title, o.ID, o.Version, o.Status)
a.say("%s\n", wrap(o.Summary, 76, ""))
if o.Outcome != "" {
a.say("\nResult: %s\n", wrap(o.Outcome, 76, " "))
}
section := func(title string, list []string) {
if len(list) > 0 {
a.say("\n%s\n", title)
for _, l := range list {
a.say(" - %s\n", wrap(l, 72, " "))
}
}
}
section("Goals", o.Goals)
section("Good for", o.Scenarios)
section("Not for", o.NotFor)
a.say("\nPackages: %s\n", strings.Join(o.Packages, ", "))
a.say("Needs: %s\n", strings.Join(o.Capabilities.Required, ", "))
if len(o.Platforms) > 0 {
a.say("Platforms: %s\n", strings.Join(o.Platforms, ", "))
}
a.say("Questions: %d (quick setup asks %d)\n", o.Questions, len(o.Quick))
if len(o.Examples) > 0 {
a.say("\nExamples\n")
for _, x := range o.Examples {
a.say(" %-16s %s\n", x["id"], x["title"])
}
}
if len(o.References) > 0 {
a.say("\nRead more\n")
for _, r := range o.References {
a.say(" %s\n", refLine(r))
}
}
cmd := "solution setup"
if s.IsTask() {
cmd = "task run"
}
a.say("\nStart: %s %s %s [--quick|--guided|--advanced] [--example <id>]\n", a.env.Program, cmd, o.ID)
return nil
}
func refLine(r knowledge.Resolution) string {
where := r.Web
if r.CLI != "" && (where == "" || r.Kind == ref.Manual) {
where = r.CLI
}
title := r.Title
if title == "" {
title = r.Ref
}
if !r.Exists {
title += " (missing)"
}
return fmt.Sprintf("%-40s %s", title, where)
}
// ---- instances from files or the store ----------------------------------------
// instanceFrom reads --file, or a stored instance named by the first argument.
func (a *app) instanceFrom(file string, fs *flag.FlagSet) (*engine.Instance, error) {
if file != "" {
var f *os.File
var err error
if file == "-" {
b := bufio.NewReader(a.env.Stdin)
in, err := engine.ReadInstance(b)
if err != nil {
return nil, fail(ExitUsage, "stdin: %v", err)
}
return in, nil
}
f, err = os.Open(file)
if err != nil {
return nil, fail(ExitNotFound, "%v", err)
}
defer f.Close()
in, err := engine.ReadInstance(f)
if err != nil {
return nil, fail(ExitUsage, "%s: %v", file, err)
}
return in, nil
}
if fs.NArg() < 1 {
return nil, fail(ExitUsage, "name a saved instance or pass --file <solution.yaml>")
}
return a.store.LoadInstance(fs.Arg(0))
}
func (a *app) presetFor(in *engine.Instance, name string) (*engine.Preset, error) {
if name == "" {
name = in.Spec.Preset
}
if name == "" {
return nil, nil
}
if strings.HasSuffix(name, ".yaml") || strings.Contains(name, string(filepath.Separator)) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
return engine.ReadPreset(f)
}
return a.store.LoadPreset(name)
}
func (a *app) evaluate(in *engine.Instance, preset *engine.Preset) (*engine.State, error) {
if in.Spec.Locale == "" {
in.Spec.Locale = a.locale
}
return a.eng.Evaluate(in, preset)
}
// common flags of the commands that take an instance
type instFlags struct {
file *string
preset *string
}
func (a *app) instFlags(fs *flag.FlagSet) instFlags {
return instFlags{
file: fs.String("file", "", "solution.yaml (SolutionInstance or WizardSession); - for stdin"),
preset: fs.String("preset", "", "preset name or file (default: the instance's)"),
}
}
func (a *app) stateOf(fs *flag.FlagSet, f instFlags) (*engine.Instance, *engine.State, error) {
if err := a.load(); err != nil {
return nil, nil, err
}
in, err := a.instanceFrom(*f.file, fs)
if err != nil {
return nil, nil, err
}
p, err := a.presetFor(in, *f.preset)
if err != nil {
return nil, nil, err
}
st, err := a.evaluate(in, p)
return in, st, err
}
// stateCmd prints the full engine state: the shared client API as JSON
// (API-01); GUI and web clients render exactly this.
func (a *app) stateCmd(args []string) error {
fs := a.flags("solution state")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
a.jsonOut = true
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
return a.printJSON(st)
}
// ---- generate, validate, plan -------------------------------------------------
func (a *app) generate(args []string) error {
fs := a.flags("solution generate")
f := a.instFlags(fs)
output := fs.String("output", "", "output directory (required)")
force := fs.Bool("force", false, "overwrite files changed by hand")
locked := fs.Bool("locked", false, "fail if the catalog changed the meaning since the last generation (solution.lock.yaml)")
dry := fs.Bool("dry-run", false, "list the files, write nothing")
if err := a.parse(fs, args); err != nil {
return err
}
if *output == "" && !*dry {
return fail(ExitUsage, "--output <dir> is required")
}
in, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
return a.writeOut(in, st, *output, *force, *locked, *dry)
}
func (a *app) writeOut(in *engine.Instance, st *engine.State, dir string, force, locked, dry bool) error {
out, err := a.eng.Generate(st, in, a.ix, false)
if err != nil {
return err
}
if dir != "" && !dry {
if prev, err := engine.ReadLock(dir); err == nil && prev != nil {
if drift := engine.LockDrift(prev, out.Lock); len(drift) > 0 {
if locked {
return fail(ExitConflict, "the catalog changed since the last generation: %s (run without --locked to accept)", strings.Join(drift, "; "))
}
a.note("note: since the last generation: %s\n", strings.Join(drift, "; "))
}
}
if err := engine.Write(dir, out, force); err != nil {
return err
}
}
if a.jsonOut {
return a.printJSON(map[string]any{"output": dir, "dryRun": dry, "files": out.Files, "complete": st.Complete, "messages": st.Messages})
}
verb := "wrote"
if dry {
verb = "would write"
}
a.note("%s %d files to %s\n", verb, len(out.Files), dir)
for _, f := range out.Files {
a.say(" %s\n", f.Path)
}
a.printMessages(st)
return nil
}
func (a *app) printMessages(st *engine.State) {
for _, m := range st.Messages {
a.note("%-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 70, " "))
}
}
// validate: is the instance complete and valid; with --native also run
// the programs' own validators on a generated directory.
func (a *app) validate(args []string) error {
fs := a.flags("solution validate")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
type qerr struct {
Question string `json:"question"`
Errors []string `json:"errors"`
}
var qerrs []qerr
for _, q := range st.Questions {
if len(q.Errors) > 0 {
qerrs = append(qerrs, qerr{q.ID, q.Errors})
}
}
if a.jsonOut {
if err := a.printJSON(map[string]any{"complete": st.Complete, "missing": st.Progress.Missing, "errors": qerrs, "stale": st.Stale, "messages": st.Messages}); err != nil {
return err
}
} else {
for _, q := range qerrs {
a.say("ERROR %s: %s\n", q.Question, strings.Join(q.Errors, "; "))
}
for _, m := range st.Progress.Missing {
a.say("MISSING %s\n", m)
}
for _, s := range st.Stale {
a.say("STALE %s=%v: %s\n", s.Question, s.Value, s.Reason)
}
a.printMessages(st)
if st.Complete {
a.say("valid: %s is complete\n", st.Solution.ID)
}
}
if !st.Complete {
return exitErr{ExitError, errors.New("")}
}
return nil
}
func (a *app) plan(args []string) error {
fs := a.flags("solution plan")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
p := engine.PlanOf(st)
if a.jsonOut {
return a.printJSON(p)
}
a.say("Plan for %s (%s) -- nothing is executed by the guide.\n", firstNonEmpty(st.Instance, st.Solution.ID), p.Spec.Solution)
phase := ""
for i, s := range p.Spec.Steps {
if s.Phase != phase {
phase = s.Phase
a.say("\n%s\n", strings.ToUpper(phase))
}
mark := " "
if s.Mutating {
mark = "*"
}
a.say("%3d.%s %s\n", i+1, mark, s.Title)
if s.Run != "" {
a.say(" $ %s\n", s.Run)
}
}
a.say("\n* changes the system\n")
if !st.Complete {
a.printMessages(st)
return fail(ExitUsage, "the solution is incomplete: %s", strings.Join(st.Progress.Missing, ", "))
}
return nil
}
func firstNonEmpty(a ...string) string {
for _, s := range a {
if s != "" {
return s
}
}
return ""
}
// ---- config, architecture, handbook ------------------------------------------
func (a *app) config(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s solution config show|explain ...", a.env.Program)
}
switch args[0] {
case "show":
fs := a.flags("solution config show")
f := a.instFlags(fs)
fs.Bool("effective", true, "show the effective, merged configuration (the default)")
origins := fs.Bool("origins", false, "show where each value comes from")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(st.Files)
}
for _, file := range st.Files {
a.say("--- %s\n%s\n", file.Path, file.Content)
if *origins {
for _, k := range sortedKeys(file.Origins) {
o := file.Origins[k]
a.say(" %-40s %s %s\n", k, o.Source, strings.Join(o.Params, ","))
}
a.say("\n")
}
}
return nil
case "explain":
fs := a.flags("solution config explain")
f := a.instFlags(fs)
if err := a.parse(fs, args[1:]); err != nil {
return err
}
// [instance] <file> <path>
pos := fs.Args()
var file, path string
switch {
case *f.file != "" && len(pos) == 2:
file, path = pos[0], pos[1]
case *f.file == "" && len(pos) == 3:
file, path = pos[1], pos[2]
default:
return fail(ExitUsage, "usage: %s solution config explain <instance>|--file f <file> <path> (e.g. yamase/yamase.yaml tls.cert-file)", a.env.Program)
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
ex := engine.Explain(st, file, path)
if a.jsonOut {
return a.printJSON(ex)
}
if !ex.Found {
return fail(ExitNotFound, "%s: %s is not set by the guide (the program's built-in default applies)", ex.File, path)
}
a.say("%s %s\n set by %s (%s layer)\n", ex.File, path, ex.Origin.Source, ex.Origin.Layer)
for _, p := range sortedKeys(ex.Answers) {
a.say(" uses answer %s = %v (%s)\n", p, ex.Answers[p], ex.Origins[p])
}
return nil
}
return a.usage("solution config " + args[0])
}
func (a *app) architecture(args []string) error {
fs := a.flags("solution architecture")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(st.Graph)
}
a.say("%s", engine.GraphText(st.Graph))
return nil
}
func (a *app) handbook(args []string) error {
fs := a.flags("solution handbook")
f := a.instFlags(fs)
output := fs.String("output", "", "directory to write the handbook to (default: print index)")
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
pages := a.eng.Handbook(st, a.ix)
if *output == "" {
for _, p := range pages {
a.say("%s\n", p.Content)
}
return nil
}
for _, p := range pages {
path := filepath.Join(*output, filepath.FromSlash(strings.TrimPrefix(p.Path, "handbook/")))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if err := os.WriteFile(path, p.Content, 0o644); err != nil {
return err
}
}
a.note("wrote %d pages to %s\n", len(pages), *output)
return nil
}
func (a *app) packageCmd(args []string) error {
fs := a.flags("solution package")
if err := a.parse(fs, args); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution package <id>", a.env.Program)
}
p := a.cat.Packages[fs.Arg(0)]
if p == nil {
return fmt.Errorf("%w: package %s", engine.ErrNotFound, fs.Arg(0))
}
r := ref.For(ref.Package, p.Meta.ID)
back := a.ix.BacklinksOf(r)
if a.jsonOut {
return a.printJSON(map[string]any{"package": p, "summary": a.eng.PackageSummary(p.Meta.ID), "usedBy": back})
}
a.say("%s -- %s\n\n", p.Meta.ID, wrap(a.eng.PackageSummary(p.Meta.ID), 70, " "))
for _, m := range p.Spec.Modules {
sup := ""
if m.Support != "" && m.Support != catalog.Supported {
sup = " [" + string(m.Support) + "]"
}
a.say(" %-14s %s%s\n", m.ID, m.Title, sup)
if len(m.Provides) > 0 {
a.say(" %-14s provides %s\n", "", strings.Join(m.Provides, ", "))
}
}
if len(back) > 0 {
a.say("\nWhat would you like to do with %s?\n", p.Meta.ID)
for _, b := range back {
if strings.HasPrefix(b, "yetano:solution/") || strings.HasPrefix(b, "yetano:task/") {
res, _ := a.ix.Resolve(b)
a.say(" %-30s %s\n", res.Title, res.CLI)
}
}
}
if res, err := a.ix.Resolve(ref.For(ref.Microsite, p.Meta.ID)); err == nil && res.Web != "" {
a.say("\nMicrosite: %s\n", res.Web)
}
return nil
}
var _ = store.ErrNotFound