package cli import ( "bufio" "context" "flag" "fmt" "os" "runtime" "sort" "strconv" "strings" "text/tabwriter" "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/platform" "git.starwarslab.us/ATOM_IT/Deployr/internal/ui" "git.starwarslab.us/ATOM_IT/Deployr/internal/version" ) // -------------------------------------------------------------------- ui --- func uiCommand(ctx context.Context, args []string) int { var g globals fs := flag.NewFlagSet("deployr ui", flag.ContinueOnError) g.register(fs) addr := fs.String("addr", "127.0.0.1:0", "address to serve the UI on (loopback only by default)") noBrowser := fs.Bool("no-browser", false, "do not open a browser, just print the URL") allowUnelevated := fs.Bool("allow-unelevated", false, "start even without administrator/root rights") names, err := parseFlags(fs, args) if err != nil { return ExitUsage } if len(names) > 0 { fmt.Fprintln(os.Stderr, "deployr: ui takes no arguments") return ExitUsage } cat, err := loadCatalog(g.catalogs) if err != nil { fmt.Fprintln(os.Stderr, "deployr:", err) return ExitUsage } log := g.newLogger() defer log.Close() // The UI warns about this in the page too, but a technician who launched it // from the wrong shell deserves to hear it before the browser opens. if !platform.IsElevated() && !*allowUnelevated && !g.dryRun && runtime.GOOS == "windows" { log.Errorf("administrator rights are required: %s", platform.PrivilegeHint()) log.Errorf("pass --allow-unelevated to open the UI anyway") return ExitPrivilege } err = ui.Serve(ctx, ui.Config{ Catalog: cat, Log: log, Addr: *addr, NoBrowser: *noBrowser, Timeout: g.timeout, DryRun: g.dryRun, }) if err != nil { log.Errorf("%v", err) return ExitFailure } return ExitOK } // ------------------------------------------------------------------ menu --- // menuCommand is the terminal equivalent of the UI, for machines reached over // SSH or a bare recovery console where no browser exists. func menuCommand(ctx context.Context, args []string) int { var g globals fs := flag.NewFlagSet("deployr menu", flag.ContinueOnError) g.registerAction(fs) names, err := parseFlags(fs, args) if err != nil { return ExitUsage } if len(names) > 0 { fmt.Fprintln(os.Stderr, "deployr: menu takes no arguments") 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(apps) == 0 { fmt.Fprintf(os.Stderr, "deployr: the catalog has no apps for %s\n", runtime.GOOS) return ExitUsage } installed := map[string]string{} present := map[string]bool{} for _, app := range apps { ok, ver := detect.Installed(app.TargetFor(runtime.GOOS).Detect) present[app.ID] = ok installed[app.ID] = ver } printMenu(cat, apps, present, installed) in := bufio.NewScanner(os.Stdin) chosen, ok := promptSelection(in, cat, apps, present) if !ok { fmt.Println("nothing selected") return ExitOK } action, ok := promptAction(in) if !ok { fmt.Println("cancelled") return ExitOK } log := g.newLogger() defer log.Close() if code := checkPrivileges(&g, log); code != ExitOK { return code } fmt.Printf("\n%s %d app(s)...\n\n", action, len(chosen)) summary := engine.Run(ctx, chosen, 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, }) fmt.Println() log.Infof("%s", summaryLine(summary)) if summary.RebootRequired { log.Infof("a reboot is required to finish") } return summary.ExitCode() } func printMenu(cat *catalog.Catalog, apps []*catalog.App, present map[string]bool, installed map[string]string) { fmt.Printf("\n%s\n%s (%s/%s)\n\n", version.String(), platform.Hostname(), runtime.GOOS, runtime.GOARCH) byCat := map[string][]*catalog.App{} for _, app := range apps { key := "other" if len(app.Categories) > 0 { key = app.Categories[0] } byCat[key] = append(byCat[key], app) } cats := make([]string, 0, len(byCat)) for c := range byCat { cats = append(cats, c) } sort.Strings(cats) // Numbering follows the display order so what the operator types matches // what they are looking at. index := menuIndex(apps) position := map[string]int{} for i, app := range index { position[app.ID] = i + 1 } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) for _, c := range cats { fmt.Fprintf(w, " %s\n", strings.ToUpper(c)) for _, app := range byCat[c] { state := "" if present[app.ID] { state = "[installed" if v := installed[app.ID]; v != "" { state += " " + v } state += "]" } fmt.Fprintf(w, " %3d)\t%s\t%s\t%s\n", position[app.ID], app.ID, app.Name, state) } fmt.Fprintln(w) } w.Flush() if profiles := cat.ProfileNames(); len(profiles) > 0 { fmt.Printf(" profiles: @%s\n\n", strings.Join(profiles, " @")) } } // menuIndex is the stable, numbered ordering of the menu: grouped by category // exactly as printMenu displays it. func menuIndex(apps []*catalog.App) []*catalog.App { byCat := map[string][]*catalog.App{} for _, app := range apps { key := "other" if len(app.Categories) > 0 { key = app.Categories[0] } byCat[key] = append(byCat[key], app) } cats := make([]string, 0, len(byCat)) for c := range byCat { cats = append(cats, c) } sort.Strings(cats) var out []*catalog.App for _, c := range cats { out = append(out, byCat[c]...) } return out } func promptSelection(in *bufio.Scanner, cat *catalog.Catalog, apps []*catalog.App, present map[string]bool) ([]*catalog.App, bool) { index := menuIndex(apps) fmt.Print("Select apps (numbers, ranges like 4-9, ids, @profile), " + "'missing' for everything not installed, 'installed', 'all', or 'q' to quit\n> ") if !in.Scan() { return nil, false } line := strings.TrimSpace(in.Text()) if line == "" || strings.EqualFold(line, "q") || strings.EqualFold(line, "quit") { return nil, false } seen := map[string]bool{} var chosen []*catalog.App add := func(app *catalog.App) { if !seen[app.ID] { seen[app.ID] = true chosen = append(chosen, app) } } for _, field := range strings.Fields(line) { switch { case strings.EqualFold(field, "all"): for _, app := range index { add(app) } case strings.EqualFold(field, "missing"): for _, app := range index { if !present[app.ID] { add(app) } } case strings.EqualFold(field, "installed"): for _, app := range index { if present[app.ID] { add(app) } } case strings.Contains(field, "-") && !strings.HasPrefix(field, "@"): lo, hi, ok := parseRange(field, len(index)) if !ok { fmt.Fprintf(os.Stderr, " ignoring %q\n", field) continue } for i := lo; i <= hi; i++ { add(index[i-1]) } default: if n, err := strconv.Atoi(field); err == nil { if n < 1 || n > len(index) { fmt.Fprintf(os.Stderr, " ignoring out-of-range %d\n", n) continue } add(index[n-1]) continue } resolved, unknown := cat.Resolve([]string{field}) if len(unknown) > 0 { fmt.Fprintf(os.Stderr, " ignoring unknown %q\n", field) continue } for _, app := range resolved { if app.TargetFor(runtime.GOOS) != nil { add(app) } } } } return chosen, len(chosen) > 0 } func parseRange(field string, max int) (int, int, bool) { parts := strings.SplitN(field, "-", 2) lo, err1 := strconv.Atoi(strings.TrimSpace(parts[0])) hi, err2 := strconv.Atoi(strings.TrimSpace(parts[1])) if err1 != nil || err2 != nil || lo < 1 || hi > max || lo > hi { return 0, 0, false } return lo, hi, true } func promptAction(in *bufio.Scanner) (string, bool) { fmt.Print("\nAction: [i]nstall (default), [u]pdate, [r]emove, [q]uit\n> ") if !in.Scan() { return "", false } switch strings.ToLower(strings.TrimSpace(in.Text())) { case "", "i", "install": return "install", true case "u", "update", "upgrade": return "update", true case "r", "remove", "uninstall": return "uninstall", true default: return "", false } }