diff --git a/README.md b/README.md index d0f55ef..2ae1f4b 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,8 @@ yetano.dev/yetano/core yetano.dev/yetano/core/paths yetano.dev/yetano/core/config yetano.dev/yetano/core/manual +yetano.dev/yetano/core/completion +yetano.dev/yetano/core/doctor ``` Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions @@ -268,6 +270,19 @@ heading). `Run` serves `manual`, `manual ` and `manual --json markdown}`) is what yet reads to show an installed program's manual (`yet manual --package`, its TUI and yet-gui). +## core/completion and core/doctor + +The other two standard commands of every Yetano program (see +docs/program-conventions.md in the meta-repository): + +- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or + PowerShell completion script generated from a static `completion.Tree` + of the program's commands. +- `doctor.Report` collects the locations the program resolves + (`AddPaths(app)` adds the standard `core/paths` ones) and named checks; + `Run(args, stdout, stderr)` prints a table or `--json` and returns the + exit code (0 all good, 1 a check failed, 2 usage). + ## Security - Environment expansion is variable substitution only -- never shell diff --git a/completion/completion.go b/completion/completion.go new file mode 100644 index 0000000..2b5fdd6 --- /dev/null +++ b/completion/completion.go @@ -0,0 +1,165 @@ +// Package completion is the shared " completion " command +// of the Yetano program standard (see docs/program-conventions.md in the +// yetano meta-repository): it prints a shell completion script for bash, +// zsh, fish or PowerShell, generated from a static command tree. +// +// The scripts are deliberately simple, word-based completion of command +// and subcommand names (not flag-aware): they join the words typed so far +// into a prefix and look up what may follow it. +// +// var tree = completion.Tree{ +// "serve": nil, +// "config": completion.Leaf("create", "validate", "path"), +// "manual": nil, +// "doctor": nil, +// "completion": completion.Leaf(completion.Shells...), +// "version": nil, +// } +// case "completion": +// err := completion.Run("yasl", tree, args[1:], os.Stdout) +package completion + +import ( + "errors" + "fmt" + "io" + "regexp" + "sort" + "strings" +) + +// Tree is one level of a program's commands: a name maps to its +// subcommands, or to nil for a command without any. +type Tree map[string]Tree + +// Leaf is a level of commands that have no subcommands themselves. +func Leaf(names ...string) Tree { + t := make(Tree, len(names)) + for _, n := range names { + t[n] = nil + } + return t +} + +// Shells are the supported shells, in the order help texts list them. +var Shells = []string{"bash", "zsh", "fish", "powershell"} + +// ErrUsage is returned by Run for a missing or unknown shell. +var ErrUsage = errors.New("usage: completion ") + +var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`) + +// entry is a prefix (words typed so far, space-joined) and what may follow. +type entry struct { + prefix string + words []string +} + +func flatten(tree Tree) ([]entry, error) { + var out []entry + var walk func(prefix string, t Tree) error + walk = func(prefix string, t Tree) error { + names := make([]string, 0, len(t)) + for n := range t { + if !safeWord.MatchString(n) { + return fmt.Errorf("completion: command name %q is not a plain word", n) + } + names = append(names, n) + } + sort.Strings(names) + out = append(out, entry{prefix, names}) + for _, n := range names { + if sub := t[n]; len(sub) > 0 { + p := n + if prefix != "" { + p = prefix + " " + n + } + if err := walk(p, sub); err != nil { + return err + } + } + } + return nil + } + return out, walk("", tree) +} + +// Script returns the completion script for shell. +func Script(program, shell string, tree Tree) (string, error) { + if !safeWord.MatchString(program) { + return "", fmt.Errorf("completion: program name %q is not a plain word", program) + } + entries, err := flatten(tree) + if err != nil { + return "", err + } + fn := "_" + strings.NewReplacer("-", "_", ".", "_", ":", "_", "+", "_").Replace(program) + "_complete" + var b strings.Builder + switch shell { + case "bash": + fmt.Fprintf(&b, "# %s bash completion. Install with:\n# source <(%s completion bash)\n", program, program) + fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn) + for _, e := range entries { + fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " ")) + } + fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program) + case "zsh": + fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program) + fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\"\n local -a completions\n case \"$prefix\" in\n", fn) + for _, e := range entries { + fmt.Fprintf(&b, " %q) completions=(%s) ;;\n", e.prefix, strings.Join(e.words, " ")) + } + fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n}\n") + fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program) + case "fish": + fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program) + fmt.Fprintf(&b, "function %s\n set -l tokens (commandline -opc)\n set -l prefix (string join ' ' -- $tokens[2..-1])\n switch \"$prefix\"\n", fn) + for _, e := range entries { + if e.prefix == "" { + b.WriteString(" case ''\n") + } else { + fmt.Fprintf(&b, " case %q\n", e.prefix) + } + quoted := make([]string, len(e.words)) + for i, w := range e.words { + quoted[i] = fmt.Sprintf("%q", w) + } + fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " ")) + } + fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn) + case "powershell": + fmt.Fprintf(&b, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", program, program) + fmt.Fprintf(&b, "Register-ArgumentCompleter -Native -CommandName '%s', '%s.exe' -ScriptBlock {\n", program, program) + b.WriteString(" param($wordToComplete, $commandAst, $cursorPosition)\n") + b.WriteString(" $words = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.ToString() })\n") + b.WriteString(" if ($wordToComplete -ne '' -and $words.Count -gt 0) { $words = @($words | Select-Object -First ($words.Count - 1)) }\n") + b.WriteString(" $prefix = $words -join ' '\n $candidates = switch ($prefix) {\n") + for _, e := range entries { + quoted := make([]string, len(e.words)) + for i, w := range e.words { + quoted[i] = "'" + w + "'" + } + fmt.Fprintf(&b, " '%s' { @(%s) }\n", e.prefix, strings.Join(quoted, ", ")) + } + b.WriteString(" default { @() }\n }\n") + b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n") + b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n") + default: + return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell) + } + return b.String(), nil +} + +// Run serves " completion " -- args are the arguments +// after "completion" -- writing the script to w. +func Run(program string, tree Tree, args []string, w io.Writer) error { + if len(args) != 1 { + return ErrUsage + } + script, err := Script(program, args[0], tree) + if err != nil { + return err + } + _, err = io.WriteString(w, script) + return err +} diff --git a/completion/completion_test.go b/completion/completion_test.go new file mode 100644 index 0000000..b5a9db1 --- /dev/null +++ b/completion/completion_test.go @@ -0,0 +1,50 @@ +package completion + +import ( + "errors" + "os/exec" + "strings" + "testing" +) + +var tree = Tree{ + "serve": nil, + "config": Leaf("create", "validate"), + "completion": Leaf(Shells...), +} + +func TestScripts(t *testing.T) { + for _, shell := range Shells { + s, err := Script("my-tool", shell, tree) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"config", "create", "validate", "powershell"} { + if !strings.Contains(s, want) { + t.Errorf("%s script lacks %q", shell, want) + } + } + } + if _, err := Script("tool", "tcsh", tree); !errors.Is(err, ErrUsage) { + t.Errorf("unknown shell: %v", err) + } + if _, err := Script("tool", "bash", Tree{"a b": nil}); err == nil { + t.Error("a name with a space must be refused") + } + var b strings.Builder + if err := Run("tool", tree, nil, &b); !errors.Is(err, ErrUsage) { + t.Errorf("no shell: %v", err) + } +} + +// TestBashCompletes runs the generated bash function, when bash is there. +func TestBashCompletes(t *testing.T) { + if _, err := exec.LookPath("bash"); err != nil { + t.Skip("no bash") + } + s, _ := Script("tool", "bash", tree) + out, err := exec.Command("bash", "-c", s+"\nCOMP_WORDS=(tool config v); COMP_CWORD=2; _tool_complete; echo \"${COMPREPLY[@]}\"").CombinedOutput() + if err != nil || strings.TrimSpace(string(out)) != "validate" { + t.Fatalf("bash completion: %v %q", err, out) + } +} diff --git a/doctor/doctor.go b/doctor/doctor.go new file mode 100644 index 0000000..9862dee --- /dev/null +++ b/doctor/doctor.go @@ -0,0 +1,198 @@ +// Package doctor is the shared " doctor [--json]" command of the +// Yetano program standard (see docs/program-conventions.md in the yetano +// meta-repository): one report shape -- the locations the program +// resolves, and named checks -- printed as a table or as JSON, with one +// exit-code rule. +// +// r := doctor.Report{Program: "yasl"} +// r.AddPaths(app) // core/paths locations +// r.Check("config file valid", err == nil, note) // program-specific +// os.Exit(r.Run(args, os.Stdout, os.Stderr)) +// +// A doctor only observes: it never creates a directory or file (a +// writability check may create and remove a probe file in a directory +// that already exists, and must say so in its note). +package doctor + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "text/tabwriter" + + "yetano.dev/yetano/core" + "yetano.dev/yetano/core/paths" +) + +// Path is one location the program resolves. Exists is only observed. +type Path struct { + Name string `json:"name"` + Path string `json:"path,omitempty"` + Target string `json:"target,omitempty"` // symlink-resolved Path, when it differs + Exists bool `json:"exists"` + Error string `json:"error,omitempty"` +} + +// Check is one named check. +type Check struct { + Name string `json:"name"` + OK bool `json:"ok"` + Note string `json:"note,omitempty"` +} + +// Report is " doctor --json"'s output. +type Report struct { + Program string `json:"program,omitempty"` + Scope string `json:"scope,omitempty"` // "user" or "system" + Paths []Path `json:"paths"` + Checks []Check `json:"checks"` +} + +// Exit codes of Run. +const ( + ExitOK = 0 // every check passed + ExitProblems = 1 // at least one check failed + ExitUsage = 2 // bad arguments +) + +// AddPath records a location, observing whether it exists. +func (r *Report) AddPath(name, path string, err error) { + p := Path{Name: name, Path: path} + if err != nil { + p.Error = err.Error() + } else if path != "" { + if _, statErr := os.Stat(path); statErr == nil { + p.Exists = true + } + if target, lerr := filepath.EvalSymlinks(path); lerr == nil && target != path { + p.Target = target + } + } + r.Paths = append(r.Paths, p) +} + +// AddPaths records the standard core/paths locations of app (config, data, +// state, cache, log; runtime only where the platform has one) and sets +// Scope. +func (r *Report) AddPaths(app core.Application) { + r.Scope = "user" + if app.Scope == core.SystemScope { + r.Scope = "system" + } + res, err := paths.For(app) + if err != nil { + r.AddPath("paths", "", err) + return + } + for _, c := range []struct { + name string + fn func() (string, error) + }{ + {"config dir", res.ConfigDir}, + {"data dir", res.DataDir}, + {"state dir", res.StateDir}, + {"cache dir", res.CacheDir}, + {"log dir", res.LogDir}, + } { + p, err := c.fn() + r.AddPath(c.name, p, err) + } + if p, err := res.RuntimeDir(); err == nil && p != "" { + r.AddPath("runtime dir", p, nil) + } +} + +// Check records a named check. +func (r *Report) Check(name string, ok bool, note string) { + r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note}) +} + +// Problems counts failed checks. +func (r Report) Problems() int { + n := 0 + for _, c := range r.Checks { + if !c.OK { + n++ + } + } + return n +} + +// Write prints the report: JSON, or a paths table and a checks table. +func (r Report) Write(w io.Writer, asJSON bool) error { + if asJSON { + if r.Paths == nil { + r.Paths = []Path{} + } + if r.Checks == nil { + r.Checks = []Check{} + } + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(r) + } + tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) + if len(r.Paths) > 0 { + fmt.Fprintf(tw, "PATH\tLOCATION\tEXISTS\n") + for _, p := range r.Paths { + loc := p.Path + if p.Error != "" { + loc = "error: " + p.Error + } else if p.Target != "" { + loc += " -> " + p.Target + } + fmt.Fprintf(tw, "%s\t%s\t%s\n", p.Name, loc, yesNo(p.Exists)) + } + fmt.Fprintln(tw) + } + fmt.Fprintf(tw, "CHECK\tOK\tNOTE\n") + for _, c := range r.Checks { + fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Name, yesNo(c.OK), c.Note) + } + return tw.Flush() +} + +func yesNo(b bool) string { + if b { + return "yes" + } + return "no" +} + +// Run serves " doctor [--json]" -- args are the arguments after +// "doctor" -- and returns the exit code: ExitOK, ExitProblems (also +// reported on stderr), or ExitUsage. +func (r Report) Run(args []string, stdout, stderr io.Writer) int { + asJSON := false + for _, a := range args { + switch a { + case "--json", "-json": + asJSON = true + case "-h", "--help", "-help": + fmt.Fprintf(stdout, "usage: %s doctor [--json]\n", nameOr(r.Program)) + return ExitOK + default: + fmt.Fprintf(stderr, "usage: %s doctor [--json] (unknown argument %q)\n", nameOr(r.Program), a) + return ExitUsage + } + } + if err := r.Write(stdout, asJSON); err != nil { + fmt.Fprintln(stderr, err) + return ExitProblems + } + if n := r.Problems(); n > 0 { + fmt.Fprintf(stderr, "%s doctor: %d problem(s) found\n", nameOr(r.Program), n) + return ExitProblems + } + return ExitOK +} + +func nameOr(s string) string { + if strings.TrimSpace(s) == "" { + return "program" + } + return s +} diff --git a/doctor/doctor_test.go b/doctor/doctor_test.go new file mode 100644 index 0000000..6219e41 --- /dev/null +++ b/doctor/doctor_test.go @@ -0,0 +1,51 @@ +package doctor + +import ( + "encoding/json" + "errors" + "path/filepath" + "strings" + "testing" + + "yetano.dev/yetano/core" +) + +func TestRun(t *testing.T) { + dir := t.TempDir() + r := Report{Program: "tool"} + r.AddPath("data dir", dir, nil) + r.AddPath("missing", filepath.Join(dir, "nope"), nil) + r.AddPath("broken", "", errors.New("no home")) + r.Check("config valid", true, "") + + var out, errOut strings.Builder + if code := r.Run([]string{"--json"}, &out, &errOut); code != ExitOK { + t.Fatalf("exit %d: %s", code, errOut.String()) + } + var got Report + if err := json.Unmarshal([]byte(out.String()), &got); err != nil || len(got.Paths) != 3 || !got.Paths[0].Exists || got.Paths[1].Exists || got.Paths[2].Error != "no home" { + t.Fatalf("json: %v %+v", err, got) + } + + r.Check("listener port free", false, "port 514 in use") + out.Reset() + if code := r.Run(nil, &out, &errOut); code != ExitProblems || !strings.Contains(out.String(), "port 514 in use") || !strings.Contains(errOut.String(), "1 problem") { + t.Fatalf("problems: %d %q %q", code, out.String(), errOut.String()) + } + if code := r.Run([]string{"--bogus"}, &out, &errOut); code != ExitUsage { + t.Fatalf("usage: %d", code) + } +} + +func TestAddPaths(t *testing.T) { + var r Report + r.AddPaths(core.Application{Name: "doctor-test", Kind: core.CLI}) + if r.Scope != "user" || len(r.Paths) < 5 || r.Paths[0].Name != "config dir" { + t.Fatalf("paths: %+v", r) + } + for _, p := range r.Paths { + if p.Error == "" && p.Path == "" { + t.Errorf("%s: no path", p.Name) + } + } +}