Files
Deployr/internal/cli/cli.go
T
ClaudeandClaude Opus 5 4909edee2d Deployr 0.1.0: cross-platform application deployment CLI
Replaces Ninite for endpoint software: one catalog, one command line, and the
same behaviour on Windows, macOS and Linux. Single static binary, no server and
no agent, driven from an RMM script runner or by hand.

- catalog of ~50 apps compiled into the binary, extendable with YAML overlays
  in catalog.d or via --catalog, no rebuild required
- providers: winget, choco, brew, cask, apt, dnf/yum, zypper, pacman, flatpak,
  snap, plus direct vendor downloads (msi/exe/msu/dmg/pkg/deb/rpm/zip/tar.gz/
  AppImage)
- sources are tried in order and fall through, so one catalog entry covers
  winget on Windows, a cask on macOS and the vendor .deb on Debian
- provider-independent detection (registry, paths, commands) makes runs
  idempotent even for software installed by hand
- unattended by construction: stdin closed, silent flags, per-command timeouts
- handles the traps that break naive wrappers: winget missing under SYSTEM,
  Homebrew refusing root, 1641/3010 reboot exits, "already installed" reported
  as failure
- --json summary on stdout with progress on stderr, and RMM-friendly exit codes
  (0 ok, 1 failed, 2 usage, 3 privileges)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 16:55:13 -05:00

243 lines
7.4 KiB
Go

// 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 <command> [flags] [apps...]
COMMANDS
install <app|@profile>... install applications
update <app|@profile>... update installed applications (--all for everything present)
uninstall <app|@profile>... remove applications
list show the catalog
status [app...] report what is installed
info <app> 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
`)
}