// Package cli parses the command line and wires the catalog, providers and // engine together. package cli import ( "context" "errors" "flag" "fmt" "io" "os" "os/signal" "path/filepath" "strings" "time" "git.starwarslab.us/ATOM_IT/Deployr/internal/catalog" "git.starwarslab.us/ATOM_IT/Deployr/internal/logx" "git.starwarslab.us/ATOM_IT/Deployr/internal/platform" "git.starwarslab.us/ATOM_IT/Deployr/internal/version" ) // Exit codes. These are the contract with whatever script calls deployr. const ( // ExitOK means every requested app ended in the desired state. ExitOK = 0 // ExitFailure means at least one app could not be handled. ExitFailure = 1 // ExitUsage means the command line or catalog was wrong. ExitUsage = 2 // ExitPrivilege means deployr does not have the rights to install software. ExitPrivilege = 3 ) // globals are the flags every action-taking command accepts. type globals struct { json bool dryRun bool verbose bool quiet bool force bool strict bool requireChecksum bool keepDownloads bool allowUnelevated bool only string logFile string noLog bool timeout time.Duration catalogs multiFlag } type multiFlag []string func (m *multiFlag) String() string { return strings.Join(*m, ",") } func (m *multiFlag) Set(v string) error { *m = append(*m, v) return nil } func (g *globals) register(fs *flag.FlagSet) { fs.BoolVar(&g.json, "json", false, "emit a machine-readable summary on stdout") fs.BoolVar(&g.dryRun, "dry-run", false, "show what would happen without changing anything") fs.BoolVar(&g.verbose, "verbose", false, "log every command that is run") fs.BoolVar(&g.quiet, "quiet", false, "only report failures") fs.Var(&g.catalogs, "catalog", "extra catalog file or directory (repeatable)") fs.DurationVar(&g.timeout, "timeout", 30*time.Minute, "per-installer timeout") fs.StringVar(&g.logFile, "log-file", "", "write the run log here (default: the deployr log directory)") fs.BoolVar(&g.noLog, "no-log", false, "do not write a log file") } func (g *globals) registerAction(fs *flag.FlagSet) { g.register(fs) fs.BoolVar(&g.force, "force", false, "act even when the app is already in the desired state") fs.BoolVar(&g.strict, "strict", false, "fail instead of falling through to the next source") fs.BoolVar(&g.requireChecksum, "require-checksum", false, "refuse vendor downloads that have no sha256 in the catalog") fs.BoolVar(&g.keepDownloads, "keep-downloads", false, "keep downloaded installers in the cache directory") fs.BoolVar(&g.allowUnelevated, "allow-unelevated", false, "continue without administrator/root rights") fs.StringVar(&g.only, "provider", "", "restrict every app to a single provider (e.g. winget, direct)") } func (g *globals) level() logx.Level { switch { case g.verbose: return logx.LevelDebug case g.quiet: return logx.LevelError default: return logx.LevelInfo } } // newLogger sends progress to stdout normally, and to stderr in --json mode so // stdout carries nothing but the JSON document. func (g *globals) newLogger() *logx.Logger { var console io.Writer = os.Stdout if g.json { console = os.Stderr } log := logx.New(console, g.level()) if !g.noLog { path := g.logFile if path == "" { path = filepath.Join(platform.LogDir(), "deployr.log") } if err := log.AttachFile(path); err != nil { log.Debugf("log file unavailable (%v); continuing without one", err) } } return log } // Main runs the CLI and returns the process exit code. func Main(args []string) int { if len(args) == 0 { usage(os.Stdout) return ExitUsage } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() cmd := args[0] rest := args[1:] switch cmd { case "install", "i": return actionCommand(ctx, "install", rest) case "update", "upgrade": return actionCommand(ctx, "update", rest) case "uninstall", "remove": return actionCommand(ctx, "uninstall", rest) case "list", "ls": return listCommand(ctx, rest) case "status": return statusCommand(ctx, rest) case "info", "show": return infoCommand(rest) case "profiles": return profilesCommand(rest) case "doctor": return doctorCommand(ctx, rest) case "catalog": return catalogCommand(rest) case "version", "--version", "-v": fmt.Println(version.String()) return ExitOK case "help", "--help", "-h": usage(os.Stdout) return ExitOK default: fmt.Fprintf(os.Stderr, "deployr: unknown command %q\n\n", cmd) usage(os.Stderr) return ExitUsage } } // parseFlags parses args and returns the non-flag operands. The standard flag // package stops at the first operand, which would make `deployr install chrome // --json` silently treat --json as an app name. Repeatedly parsing what is left // after each operand gives the flags-anywhere behaviour every other CLI has. func parseFlags(fs *flag.FlagSet, args []string) ([]string, error) { var operands []string for { if err := fs.Parse(args); err != nil { return nil, err } rest := fs.Args() if len(rest) == 0 { return operands, nil } operands = append(operands, rest[0]) args = rest[1:] } } // loadCatalog reads the embedded catalog plus overlays, reporting a usage error // rather than a stack trace when an overlay is malformed. func loadCatalog(paths []string) (*catalog.Catalog, error) { cat, err := catalog.Load(paths) if err != nil { return nil, fmt.Errorf("catalog: %w", err) } return cat, nil } // resolveApps maps command-line names onto catalog entries, printing a // "did you mean" hint for anything unrecognised. func resolveApps(cat *catalog.Catalog, names []string) ([]*catalog.App, error) { apps, unknown := cat.Resolve(names) if len(unknown) > 0 { var msg strings.Builder fmt.Fprintf(&msg, "unknown app or profile: %s", strings.Join(unknown, ", ")) if suggestions := cat.Suggest(unknown[0]); len(suggestions) > 0 { fmt.Fprintf(&msg, "\n did you mean: %s", strings.Join(suggestions, ", ")) } msg.WriteString("\n run `deployr list` to see the catalog") return nil, errors.New(msg.String()) } if len(apps) == 0 { return nil, errors.New("no apps given") } return apps, nil } func usage(w io.Writer) { fmt.Fprint(w, `deployr - cross-platform application deployment for Windows, macOS and Linux USAGE deployr [flags] [apps...] COMMANDS install ... install applications update ... update installed applications (--all for everything present) uninstall ... remove applications list show the catalog status [app...] report what is installed info show one app's install recipe profiles list the bundles defined in the catalog doctor report platform, privileges and available providers catalog validate [path] check a catalog overlay for errors version print the build version COMMON FLAGS --json machine-readable output on stdout --dry-run plan without changing the machine --verbose log every command executed --catalog PATH extra catalog file or directory (repeatable) --timeout 30m per-installer timeout EXAMPLES deployr install chrome 7zip vlc deployr install @standard --json deployr update --all deployr status --json deployr list --category browser EXIT CODES 0 success 1 one or more apps failed 2 usage error 3 insufficient privileges `) }