Files
core/solutions/cli/setup.go
T

494 lines
13 KiB
Go
Raw Normal View History

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")
}