package cli import ( "context" "encoding/json" "flag" "fmt" "os" "runtime" "sort" "strings" "text/tabwriter" "time" "git.starwarslab.us/ATOM_IT/Deployr/internal/catalog" "git.starwarslab.us/ATOM_IT/Deployr/internal/detect" "git.starwarslab.us/ATOM_IT/Deployr/internal/engine" "git.starwarslab.us/ATOM_IT/Deployr/internal/logx" "git.starwarslab.us/ATOM_IT/Deployr/internal/platform" "git.starwarslab.us/ATOM_IT/Deployr/internal/provider" "git.starwarslab.us/ATOM_IT/Deployr/internal/run" "git.starwarslab.us/ATOM_IT/Deployr/internal/version" ) // ------------------------------------------------- install/update/remove --- func actionCommand(ctx context.Context, action string, args []string) int { var g globals fs := flag.NewFlagSet("deployr "+action, flag.ContinueOnError) g.registerAction(fs) all := fs.Bool("all", false, "apply to every catalog app that is installed on this machine") names, err := parseFlags(fs, args) if err != nil { return ExitUsage } if !platform.Supported() { fmt.Fprintf(os.Stderr, "deployr: %s is not a supported platform\n", runtime.GOOS) return ExitUsage } cat, err := loadCatalog(g.catalogs) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } var apps []*catalog.App switch { case *all && len(names) == 0: apps = installedApps(cat) if len(apps) == 0 { fmt.Fprintln(os.Stderr, "deployr: nothing from the catalog is installed on this machine") return ExitOK } case *all: fmt.Fprintln(os.Stderr, "deployr: --all takes no app arguments") return ExitUsage default: apps, err = resolveApps(cat, names) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } } log := g.newLogger() defer log.Close() if code := checkPrivileges(&g, log); code != ExitOK { return code } log.Infof("%s: %s on %s (%s/%s)%s", version.String(), action, platform.Hostname(), runtime.GOOS, runtime.GOARCH, dryRunNote(g.dryRun)) summary := engine.Run(ctx, apps, engine.Config{ Action: engine.Action(action), DryRun: g.dryRun, Force: g.force, Strict: g.strict, Timeout: g.timeout, CacheDir: platform.CacheDir(), RequireChecksum: g.requireChecksum, KeepDownloads: g.keepDownloads, OnlyProvider: g.only, Log: log, }) if g.json { if err := writeJSON(summary); err != nil { log.Errorf("%v", err) return ExitFailure } } else { log.Infof("%s", summaryLine(summary)) if summary.RebootRequired { log.Infof("a reboot is required to finish") } } return summary.ExitCode() } func dryRunNote(dry bool) string { if dry { return " [dry run]" } return "" } func summaryLine(s engine.Summary) string { return fmt.Sprintf("%d changed, %d skipped, %d failed, %d unsupported in %s", s.Changed, s.Skipped, s.Failed, s.Unsupported, (time.Duration(s.DurationMS) * time.Millisecond).Round(time.Second)) } // installedApps returns the catalog apps present on this machine, which is what // `--all` means for an update run. func installedApps(cat *catalog.Catalog) []*catalog.App { var out []*catalog.App for _, app := range cat.ForPlatform(runtime.GOOS) { target := app.TargetFor(runtime.GOOS) if ok, _ := detect.Installed(target.Detect); ok { out = append(out, app) } } return out } // checkPrivileges refuses to start a run that cannot possibly succeed. Windows // needs a real elevated token; Unix accepts either root or passwordless sudo. func checkPrivileges(g *globals, log *logx.Logger) int { if platform.IsElevated() { return ExitOK } if runtime.GOOS != "windows" && run.CanEscalate() { log.Debugf("not root; escalating individual commands with sudo -n") return ExitOK } if g.allowUnelevated || g.dryRun { log.Warnf("running without administrator/root rights; most installs will fail") return ExitOK } log.Errorf("administrator/root rights are required: %s", platform.PrivilegeHint()) log.Errorf("pass --allow-unelevated to try anyway") return ExitPrivilege } // ------------------------------------------------------------------ list --- type listRow struct { App string `json:"app"` Name string `json:"name"` Platforms []string `json:"platforms"` Categories []string `json:"categories,omitempty"` Installed *bool `json:"installed,omitempty"` Version string `json:"version,omitempty"` } func listCommand(_ context.Context, args []string) int { var g globals fs := flag.NewFlagSet("deployr list", flag.ContinueOnError) g.register(fs) category := fs.String("category", "", "only show apps in this category") everywhere := fs.Bool("all-platforms", false, "include apps with no recipe for this platform") onlyInstalled := fs.Bool("installed", false, "only show apps present on this machine") names, err := parseFlags(fs, args) if err != nil { return ExitUsage } if len(names) > 0 { fmt.Fprintln(os.Stderr, "deployr: list takes no arguments; did you mean `deployr status`?") return ExitUsage } cat, err := loadCatalog(g.catalogs) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } apps := cat.Apps if !*everywhere { apps = cat.ForPlatform(runtime.GOOS) } rows := make([]listRow, 0, len(apps)) for _, app := range apps { if *category != "" && !app.HasCategory(*category) { continue } row := listRow{App: app.ID, Name: app.Name, Platforms: app.Platforms(), Categories: app.Categories} if target := app.TargetFor(runtime.GOOS); target != nil { present, ver := detect.Installed(target.Detect) row.Installed = &present row.Version = ver } if *onlyInstalled && (row.Installed == nil || !*row.Installed) { continue } rows = append(rows, row) } if g.json { if err := writeJSON(rows); err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitFailure } return ExitOK } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintln(w, "APP\tNAME\tPLATFORMS\tCATEGORIES\tINSTALLED") for _, r := range rows { fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", r.App, r.Name, strings.Join(shortPlatforms(r.Platforms), ","), strings.Join(r.Categories, ","), installedCell(r)) } w.Flush() fmt.Printf("\n%d apps\n", len(rows)) return ExitOK } func installedCell(r listRow) string { switch { case r.Installed == nil: return "-" case !*r.Installed: return "no" case r.Version != "": return "yes " + r.Version default: return "yes" } } func shortPlatforms(p []string) []string { out := make([]string, 0, len(p)) for _, os := range p { switch os { case "windows": out = append(out, "win") case "darwin": out = append(out, "mac") default: out = append(out, os) } } return out } // ---------------------------------------------------------------- status --- type statusRow struct { App string `json:"app"` Name string `json:"name"` Installed bool `json:"installed"` Version string `json:"version,omitempty"` Supported bool `json:"supported"` } func statusCommand(_ context.Context, args []string) int { var g globals fs := flag.NewFlagSet("deployr status", flag.ContinueOnError) g.register(fs) names, err := parseFlags(fs, args) if err != nil { return ExitUsage } cat, err := loadCatalog(g.catalogs) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } apps := cat.ForPlatform(runtime.GOOS) if len(names) > 0 { apps, err = resolveApps(cat, names) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } } rows := make([]statusRow, 0, len(apps)) for _, app := range apps { row := statusRow{App: app.ID, Name: app.Name} if target := app.TargetFor(runtime.GOOS); target != nil { row.Supported = true row.Installed, row.Version = detect.Installed(target.Detect) } rows = append(rows, row) } if g.json { if err := writeJSON(rows); err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitFailure } return ExitOK } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintln(w, "APP\tNAME\tSTATE\tVERSION") installed := 0 for _, r := range rows { state := "not installed" switch { case !r.Supported: state = "unsupported" case r.Installed: state = "installed" installed++ } fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", r.App, r.Name, state, r.Version) } w.Flush() fmt.Printf("\n%d of %d installed\n", installed, len(rows)) return ExitOK } // ------------------------------------------------------------------ info --- func infoCommand(args []string) int { var g globals fs := flag.NewFlagSet("deployr info", flag.ContinueOnError) g.register(fs) names, err := parseFlags(fs, args) if err != nil { return ExitUsage } if len(names) != 1 { fmt.Fprintln(os.Stderr, "deployr: info takes exactly one app") return ExitUsage } cat, err := loadCatalog(g.catalogs) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } app, ok := cat.Get(names[0]) if !ok { fmt.Fprintf(os.Stderr, "deployr: unknown app %q\n", names[0]) if s := cat.Suggest(names[0]); len(s) > 0 { fmt.Fprintf(os.Stderr, " did you mean: %s\n", strings.Join(s, ", ")) } return ExitUsage } if g.json { if err := writeJSON(app); err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitFailure } return ExitOK } fmt.Printf("%s (%s)\n", app.Name, app.ID) if app.Description != "" { fmt.Printf(" %s\n", app.Description) } if app.Homepage != "" { fmt.Printf(" homepage: %s\n", app.Homepage) } if len(app.Categories) > 0 { fmt.Printf(" categories: %s\n", strings.Join(app.Categories, ", ")) } if len(app.Aliases) > 0 { fmt.Printf(" aliases: %s\n", strings.Join(app.Aliases, ", ")) } for _, goos := range app.Platforms() { target := app.TargetFor(goos) fmt.Printf("\n %s\n", goos) for i, src := range target.Sources { id := src.ID if src.Provider == "direct" { id = src.URLFor(runtime.GOARCH) if id == "" { id = src.URL } } fmt.Printf(" %d. %-8s %s\n", i+1, src.Provider, id) } if !target.Detect.Empty() { fmt.Printf(" detect: %s\n", describeDetect(target.Detect)) } if target.Notes != "" { fmt.Printf(" note: %s\n", target.Notes) } if goos == runtime.GOOS { present, ver := detect.Installed(target.Detect) state := "not installed" if present { state = "installed" if ver != "" { state += " " + ver } } fmt.Printf(" state: %s\n", state) } } return ExitOK } func describeDetect(d catalog.Detect) string { var parts []string if len(d.Registry) > 0 { parts = append(parts, "registry "+strings.Join(d.Registry, " | ")) } if len(d.Paths) > 0 { parts = append(parts, "paths "+strings.Join(d.Paths, " | ")) } if len(d.Commands) > 0 { parts = append(parts, "commands "+strings.Join(d.Commands, " | ")) } return strings.Join(parts, "; ") } // -------------------------------------------------------------- profiles --- func profilesCommand(args []string) int { var g globals fs := flag.NewFlagSet("deployr profiles", flag.ContinueOnError) g.register(fs) names, err := parseFlags(fs, args) if err != nil { return ExitUsage } if len(names) > 0 { fmt.Fprintln(os.Stderr, "deployr: profiles takes no arguments") return ExitUsage } cat, err := loadCatalog(g.catalogs) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } if g.json { if err := writeJSON(cat.Profiles); err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitFailure } return ExitOK } profileNames := cat.ProfileNames() if len(profileNames) == 0 { fmt.Println("no profiles defined") return ExitOK } for _, name := range profileNames { members := append([]string(nil), cat.Profiles[name]...) sort.Strings(members) fmt.Printf("@%s (%d apps)\n %s\n\n", name, len(members), strings.Join(members, " ")) } return ExitOK } // ---------------------------------------------------------------- doctor --- type doctorReport struct { Version string `json:"version"` Host string `json:"host"` OS string `json:"os"` Arch string `json:"arch"` Elevated bool `json:"elevated"` CanSudo bool `json:"can_escalate"` Dirs map[string]string `json:"dirs"` CatalogApp int `json:"catalog_apps"` ForThisOS int `json:"catalog_apps_this_os"` Profiles int `json:"profiles"` Providers map[string]bool `json:"providers"` } func doctorCommand(ctx context.Context, args []string) int { var g globals fs := flag.NewFlagSet("deployr doctor", flag.ContinueOnError) g.register(fs) names, err := parseFlags(fs, args) if err != nil { return ExitUsage } if len(names) > 0 { fmt.Fprintln(os.Stderr, "deployr: doctor takes no arguments") return ExitUsage } cat, err := loadCatalog(g.catalogs) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } rep := doctorReport{ Version: version.Version, Host: platform.Hostname(), OS: runtime.GOOS, Arch: runtime.GOARCH, Elevated: platform.IsElevated(), CanSudo: run.CanEscalate(), Dirs: map[string]string{ "data": platform.DataDir(), "logs": platform.LogDir(), "cache": platform.CacheDir(), }, CatalogApp: len(cat.Apps), ForThisOS: len(cat.ForPlatform(runtime.GOOS)), Profiles: len(cat.Profiles), Providers: map[string]bool{}, } opts := provider.Opts{Timeout: 30 * time.Second} providers := provider.ForOS(runtime.GOOS) for _, p := range providers { rep.Providers[p.Name()] = p.Available(ctx, opts) } if g.json { if err := writeJSON(rep); err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitFailure } return ExitOK } fmt.Println(version.String()) fmt.Printf("\nhost: %s\n", rep.Host) fmt.Printf("platform: %s/%s\n", rep.OS, rep.Arch) fmt.Printf("elevated: %s\n", yesNo(rep.Elevated)) if runtime.GOOS != "windows" { fmt.Printf("sudo -n: %s\n", yesNo(rep.CanSudo)) } fmt.Printf("\ncatalog: %d apps (%d for %s), %d profiles\n", rep.CatalogApp, rep.ForThisOS, rep.OS, rep.Profiles) fmt.Println("overlays:") for _, dir := range platform.CatalogDirs() { fmt.Printf(" %s\n", dir) } fmt.Println("directories:") for _, key := range []string{"data", "logs", "cache"} { fmt.Printf(" %-6s %s\n", key, rep.Dirs[key]) } fmt.Println("providers:") w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) for _, p := range providers { state := "missing" if rep.Providers[p.Name()] { state = "available" } fmt.Fprintf(w, " %s\t%s\t%s\n", p.Name(), state, p.Label()) } w.Flush() return ExitOK } func yesNo(b bool) string { if b { return "yes" } return "no" } // --------------------------------------------------------------- catalog --- func catalogCommand(args []string) int { if len(args) == 0 { fmt.Fprintln(os.Stderr, "deployr: catalog needs a subcommand (validate)") return ExitUsage } switch args[0] { case "validate": cat, err := loadCatalog(args[1:]) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } fmt.Printf("catalog ok: %d apps, %d profiles\n", len(cat.Apps), len(cat.Profiles)) for _, goos := range []string{"windows", "darwin", "linux"} { fmt.Printf(" %-8s %d apps\n", goos, len(cat.ForPlatform(goos))) } return ExitOK default: fmt.Fprintf(os.Stderr, "deployr: unknown catalog subcommand %q\n", args[0]) return ExitUsage } } func writeJSON(v any) error { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") return enc.Encode(v) }