// 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. Area (a group such as "config" or // "services") and Hint (what to do about a failed check) are optional // and omitted from the JSON form when empty, so a report without them // looks exactly as before they existed. type Check struct { Area string `json:"area,omitempty"` Name string `json:"name"` OK bool `json:"ok"` Note string `json:"note,omitempty"` Hint string `json:"hint,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}) } // Add records a check with all its fields, for a program that groups its // checks into areas or gives hints. func (r *Report) Add(c Check) { r.Checks = append(r.Checks, c) } // 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) } // The AREA and HINT columns only appear when some check uses them, // so the table of a program without them is unchanged. withArea, withHint := false, false for _, c := range r.Checks { withArea = withArea || c.Area != "" withHint = withHint || c.Hint != "" } row := func(area, name, ok, note, hint string) { cols := []string{name, ok, note} if withArea { cols = append([]string{area}, cols...) } if withHint { cols = append(cols, hint) } fmt.Fprintln(tw, strings.Join(cols, "\t")) } row("AREA", "CHECK", "OK", "NOTE", "HINT") for _, c := range r.Checks { row(c.Area, c.Name, yesNo(c.OK), c.Note, c.Hint) } 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 }