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>
This commit is contained in:
commit
4909edee2d
40 files changed
+6714
No files matched your search
@@ -0,0 +1,200 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||
)
|
||||
|
||||
// brew drives Homebrew, as either a formula ("brew") or a cask ("cask")
|
||||
// provider. The two share every code path except the --cask flag.
|
||||
type brew struct {
|
||||
cask bool
|
||||
|
||||
once sync.Once
|
||||
path string
|
||||
user string // account to run brew as; empty means "the current user"
|
||||
ok bool
|
||||
}
|
||||
|
||||
func (b *brew) Name() string {
|
||||
if b.cask {
|
||||
return "cask"
|
||||
}
|
||||
return "brew"
|
||||
}
|
||||
|
||||
func (b *brew) OSes() []string {
|
||||
if b.cask {
|
||||
return []string{"darwin"}
|
||||
}
|
||||
return []string{"darwin", "linux"}
|
||||
}
|
||||
|
||||
func (b *brew) Label() string {
|
||||
if b.cask {
|
||||
return "Homebrew Cask"
|
||||
}
|
||||
return "Homebrew"
|
||||
}
|
||||
|
||||
// brewPaths are the standard prefixes: Apple silicon, Intel macOS, and
|
||||
// Linuxbrew. PATH is checked first for a non-standard install.
|
||||
var brewPaths = []string{
|
||||
"/opt/homebrew/bin/brew",
|
||||
"/usr/local/bin/brew",
|
||||
"/home/linuxbrew/.linuxbrew/bin/brew",
|
||||
}
|
||||
|
||||
// resolve locates brew and decides which account should run it. Homebrew
|
||||
// refuses to run as root, so a root context (RMM, MDM, sudo) has to drop to the
|
||||
// account that owns the Homebrew prefix. When there is no such account, this
|
||||
// route is simply unavailable and the engine falls through to the next source.
|
||||
func (b *brew) resolve() (string, string, bool) {
|
||||
b.once.Do(func() {
|
||||
if runtime.GOOS == "windows" {
|
||||
return
|
||||
}
|
||||
if p, found := run.Which("brew"); found {
|
||||
b.path = p
|
||||
} else {
|
||||
for _, p := range brewPaths {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
b.path = p
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if b.path == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if os.Geteuid() != 0 {
|
||||
b.ok = true
|
||||
return
|
||||
}
|
||||
// Running as root: the owner of the brew binary is the account that
|
||||
// installed it and the one whose permissions the cellar expects.
|
||||
if owner, found := fileOwner(b.path); found && owner != "root" {
|
||||
b.user, b.ok = owner, true
|
||||
return
|
||||
}
|
||||
if u := platform.ConsoleUser(); u != "" {
|
||||
b.user, b.ok = u, true
|
||||
return
|
||||
}
|
||||
})
|
||||
return b.path, b.user, b.ok
|
||||
}
|
||||
|
||||
func (b *brew) Available(context.Context, Opts) bool {
|
||||
_, _, ok := b.resolve()
|
||||
return ok
|
||||
}
|
||||
|
||||
func (b *brew) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||
path, user, _ := b.resolve()
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: path,
|
||||
Args: args,
|
||||
AsUser: user,
|
||||
Env: []string{
|
||||
"NONINTERACTIVE=1",
|
||||
"HOMEBREW_NO_ENV_HINTS=1",
|
||||
"HOMEBREW_NO_ANALYTICS=1",
|
||||
},
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
// flag returns --cask for the cask provider, or nothing.
|
||||
func (b *brew) flag() []string {
|
||||
if b.cask {
|
||||
return []string{"--cask"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *brew) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
args := append([]string{"install"}, b.flag()...)
|
||||
args = append(args, src.ID)
|
||||
args = append(args, src.Args...)
|
||||
res := b.exec(ctx, o, args...)
|
||||
return b.outcome(res, src, o, "install")
|
||||
}
|
||||
|
||||
func (b *brew) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
args := append([]string{"upgrade"}, b.flag()...)
|
||||
if b.cask {
|
||||
// Casks whose app self-updates are skipped by default; --greedy is the
|
||||
// only way a patching tool actually patches them.
|
||||
args = append(args, "--greedy")
|
||||
}
|
||||
args = append(args, src.ID)
|
||||
res := b.exec(ctx, o, args...)
|
||||
return b.outcome(res, src, o, "upgrade")
|
||||
}
|
||||
|
||||
func (b *brew) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
args := append([]string{"uninstall"}, b.flag()...)
|
||||
args = append(args, src.ID)
|
||||
res := b.exec(ctx, o, args...)
|
||||
return b.outcome(res, src, o, "uninstall")
|
||||
}
|
||||
|
||||
func (b *brew) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
args := append([]string{"list", "--versions"}, b.flag()...)
|
||||
args = append(args, src.ID)
|
||||
res := b.exec(ctx, o, args...)
|
||||
if res.Failed() {
|
||||
return "", false
|
||||
}
|
||||
fields := strings.Fields(res.Stdout)
|
||||
if len(fields) >= 2 {
|
||||
return fields[len(fields)-1], true
|
||||
}
|
||||
if len(fields) == 1 {
|
||||
return "", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (b *brew) benign(res run.Result) bool {
|
||||
for _, phrase := range []string{
|
||||
"already installed",
|
||||
"it seems there is already an app at",
|
||||
"no available upgrade",
|
||||
"already up-to-date",
|
||||
} {
|
||||
if res.Contains(phrase) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (b *brew) outcome(res run.Result, src catalog.Source, o Opts, verb string) (Outcome, error) {
|
||||
if o.DryRun {
|
||||
return Outcome{Message: "dry run"}, nil
|
||||
}
|
||||
switch {
|
||||
case !res.Failed():
|
||||
if b.benign(res) {
|
||||
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||
}
|
||||
return Outcome{}, nil
|
||||
case b.benign(res):
|
||||
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("brew %s %s: %s", verb, src.ID, res.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/detect"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/download"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||
)
|
||||
|
||||
// direct installs straight from a vendor download. It is the fallback for
|
||||
// software the native package managers handle badly or not at all, and the only
|
||||
// route on a machine with no package manager configured.
|
||||
type direct struct{}
|
||||
|
||||
func (d *direct) Name() string { return "direct" }
|
||||
func (d *direct) OSes() []string { return []string{"windows", "darwin", "linux"} }
|
||||
func (d *direct) Label() string { return "Direct vendor download" }
|
||||
|
||||
// Available is always true: there is no local tool to probe. A missing network
|
||||
// surfaces as a download error, which is more useful than silently skipping.
|
||||
func (d *direct) Available(context.Context, Opts) bool { return true }
|
||||
|
||||
func (d *direct) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
url := src.URLFor(o.Arch)
|
||||
if url == "" {
|
||||
return Outcome{}, fmt.Errorf("no download URL for %s/%s", runtime.GOOS, o.Arch)
|
||||
}
|
||||
kind := strings.ToLower(src.Kind)
|
||||
if kind == "" {
|
||||
kind = InferKind(url)
|
||||
}
|
||||
if kind == "" {
|
||||
return Outcome{}, fmt.Errorf("cannot tell the installer type of %s; set `kind` in the catalog", url)
|
||||
}
|
||||
|
||||
if o.DryRun {
|
||||
if o.Log != nil {
|
||||
o.Log.Debugf("would download %s (%s) and install it", url, kind)
|
||||
}
|
||||
return Outcome{Message: "dry run"}, nil
|
||||
}
|
||||
|
||||
path, err := download.Fetch(ctx, download.Options{
|
||||
URL: url,
|
||||
SHA256: src.SHA256,
|
||||
Dir: o.CacheDir,
|
||||
Timeout: o.Timeout,
|
||||
RequireChecksum: o.RequireChecksum,
|
||||
Log: o.Log,
|
||||
})
|
||||
if err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
if !o.KeepDownloads {
|
||||
defer os.Remove(path)
|
||||
}
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return d.installWindows(ctx, path, kind, src, o)
|
||||
case "darwin":
|
||||
return d.installDarwin(ctx, path, kind, src, o)
|
||||
case "linux":
|
||||
return d.installLinux(ctx, path, kind, src, o)
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("direct installs are not supported on %s", runtime.GOOS)
|
||||
}
|
||||
}
|
||||
|
||||
// Update reinstalls from the catalog URL. Vendor "latest" links are evergreen,
|
||||
// so a reinstall is how you patch anything that has no package manager behind
|
||||
// it. Installers of this kind are in-place upgrades, not duplicates.
|
||||
func (d *direct) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
return d.Install(ctx, src, o)
|
||||
}
|
||||
|
||||
// Query cannot report a version: the download tells us nothing about what is on
|
||||
// disk. Presence and version come from the catalog's detect rules instead.
|
||||
func (d *direct) Query(context.Context, catalog.Source, Opts) (string, bool) { return "", false }
|
||||
|
||||
// -------------------------------------------------------------- windows ---
|
||||
|
||||
func (d *direct) installWindows(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) {
|
||||
var res run.Result
|
||||
switch kind {
|
||||
case "msi":
|
||||
args := append([]string{"/i", path, "/qn", "/norestart"}, src.SilentArgs...)
|
||||
res = run.Exec(ctx, run.Options{Name: "msiexec", Args: args, Timeout: o.Timeout, Log: o.Log})
|
||||
case "msu":
|
||||
res = run.Exec(ctx, run.Options{Name: "wusa", Args: []string{path, "/quiet", "/norestart"}, Timeout: o.Timeout, Log: o.Log})
|
||||
case "exe":
|
||||
if len(src.SilentArgs) == 0 {
|
||||
// Running a bare vendor .exe would pop a wizard on someone's
|
||||
// screen and then hang until the timeout. Refuse instead.
|
||||
return Outcome{}, errors.New("exe installer needs silent_args in the catalog")
|
||||
}
|
||||
res = run.Exec(ctx, run.Options{Name: path, Args: src.SilentArgs, Timeout: o.Timeout, Log: o.Log})
|
||||
case "zip":
|
||||
dest := platform.ExpandPath(src.Dest)
|
||||
if dest == "" {
|
||||
return Outcome{}, errors.New("zip payload needs a dest in the catalog")
|
||||
}
|
||||
if err := extractZip(path, dest); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
return Outcome{}, nil
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("unsupported installer kind %q on windows", kind)
|
||||
}
|
||||
|
||||
switch {
|
||||
case !res.Failed():
|
||||
return Outcome{}, nil
|
||||
case isRebootExit(res.ExitCode):
|
||||
return Outcome{RebootRequired: true}, nil
|
||||
case res.ExitCode == 1618:
|
||||
return Outcome{}, errors.New("another Windows installation is already in progress")
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("installer failed: %s", res.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- darwin ---
|
||||
|
||||
func (d *direct) installDarwin(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) {
|
||||
switch kind {
|
||||
case "pkg":
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "/usr/sbin/installer", Args: []string{"-pkg", path, "-target", "/"},
|
||||
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("installer -pkg: %s", res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
|
||||
case "dmg":
|
||||
return d.installDMG(ctx, path, src, o)
|
||||
|
||||
case "zip":
|
||||
dest := platform.ExpandPath(src.Dest)
|
||||
if dest == "" {
|
||||
dest = "/Applications"
|
||||
}
|
||||
// ditto preserves resource forks and code signatures; unzip does not.
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "/usr/bin/ditto", Args: []string{"-x", "-k", path, dest},
|
||||
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("ditto: %s", res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
|
||||
case "tar.gz", "tgz":
|
||||
return untar(ctx, path, src, o, "/usr/local")
|
||||
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("unsupported installer kind %q on macOS", kind)
|
||||
}
|
||||
}
|
||||
|
||||
// installDMG mounts a disk image, installs whatever is inside it, and always
|
||||
// detaches -- a leaked mount blocks the next run.
|
||||
func (d *direct) installDMG(ctx context.Context, path string, src catalog.Source, o Opts) (Outcome, error) {
|
||||
mount, err := os.MkdirTemp("", "deployr-dmg-")
|
||||
if err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
defer os.RemoveAll(mount)
|
||||
|
||||
attach := run.Exec(ctx, run.Options{
|
||||
Name: "/usr/bin/hdiutil",
|
||||
Args: []string{"attach", path, "-nobrowse", "-noverify", "-quiet", "-mountpoint", mount},
|
||||
Timeout: o.Timeout,
|
||||
Log: o.Log,
|
||||
})
|
||||
if attach.Failed() {
|
||||
return Outcome{}, fmt.Errorf("hdiutil attach: %s", attach.Error())
|
||||
}
|
||||
defer func() {
|
||||
detachCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
run.Exec(detachCtx, run.Options{
|
||||
Name: "/usr/bin/hdiutil", Args: []string{"detach", mount, "-quiet", "-force"}, Log: o.Log,
|
||||
})
|
||||
}()
|
||||
|
||||
entries, err := os.ReadDir(mount)
|
||||
if err != nil {
|
||||
return Outcome{}, fmt.Errorf("read mounted image: %w", err)
|
||||
}
|
||||
|
||||
// A .pkg inside the image is the vendor's own installer: prefer it.
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(strings.ToLower(e.Name()), ".pkg") {
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "/usr/sbin/installer", Args: []string{"-pkg", filepath.Join(mount, e.Name()), "-target", "/"},
|
||||
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("installer -pkg: %s", res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
}
|
||||
}
|
||||
|
||||
appName := src.AppName
|
||||
if appName == "" {
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e.Name(), ".app") {
|
||||
appName = e.Name()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if appName == "" {
|
||||
return Outcome{}, errors.New("no .app or .pkg found in the disk image; set app_name in the catalog")
|
||||
}
|
||||
|
||||
source := filepath.Join(mount, appName)
|
||||
if _, err := os.Stat(source); err != nil {
|
||||
return Outcome{}, fmt.Errorf("%s not found in the disk image", appName)
|
||||
}
|
||||
target := filepath.Join("/Applications", appName)
|
||||
|
||||
// ditto onto an existing bundle merges directories and leaves stale files
|
||||
// behind, so replace it outright.
|
||||
if _, err := os.Stat(target); err == nil {
|
||||
rm := run.Exec(ctx, run.Options{Name: "/bin/rm", Args: []string{"-rf", target}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||
if rm.Failed() {
|
||||
return Outcome{}, fmt.Errorf("replace %s: %s", target, rm.Error())
|
||||
}
|
||||
}
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "/usr/bin/ditto", Args: []string{source, target},
|
||||
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("copy %s: %s", appName, res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- linux ---
|
||||
|
||||
func (d *direct) installLinux(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) {
|
||||
switch kind {
|
||||
case "deb":
|
||||
// apt-get resolves the dependencies dpkg -i would leave broken.
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "apt-get", Args: append(append([]string{"install", "-y"}, aptConfArgs...), path),
|
||||
Env: aptEnv, NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("apt-get install %s: %s", filepath.Base(path), res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
|
||||
case "rpm":
|
||||
for _, mgr := range []struct {
|
||||
bin string
|
||||
args []string
|
||||
}{
|
||||
{"dnf", []string{"install", "-y", path}},
|
||||
{"zypper", []string{"--non-interactive", "install", "--allow-unsigned-rpm", path}},
|
||||
{"yum", []string{"install", "-y", path}},
|
||||
{"rpm", []string{"-Uvh", path}},
|
||||
} {
|
||||
if !run.Available(mgr.bin) {
|
||||
continue
|
||||
}
|
||||
res := run.Exec(ctx, run.Options{Name: mgr.bin, Args: mgr.args, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("%s install: %s", mgr.bin, res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
}
|
||||
return Outcome{}, errors.New("no RPM-capable package manager found")
|
||||
|
||||
case "sh", "run":
|
||||
if err := os.Chmod(path, 0o755); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "/bin/sh", Args: append([]string{path}, src.SilentArgs...),
|
||||
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("install script: %s", res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
|
||||
case "appimage":
|
||||
dest := platform.ExpandPath(src.Dest)
|
||||
if dest == "" {
|
||||
dest = filepath.Join("/usr/local/bin", strings.TrimSuffix(src.ID, ".AppImage"))
|
||||
}
|
||||
if err := copyFile(path, dest, 0o755); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
return Outcome{}, nil
|
||||
|
||||
case "zip":
|
||||
dest := platform.ExpandPath(src.Dest)
|
||||
if dest == "" {
|
||||
return Outcome{}, errors.New("zip payload needs a dest in the catalog")
|
||||
}
|
||||
if err := extractZip(path, dest); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
return Outcome{}, nil
|
||||
|
||||
case "tar.gz", "tgz":
|
||||
return untar(ctx, path, src, o, "/usr/local")
|
||||
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("unsupported installer kind %q on linux", kind)
|
||||
}
|
||||
}
|
||||
|
||||
func untar(ctx context.Context, path string, src catalog.Source, o Opts, fallbackDest string) (Outcome, error) {
|
||||
dest := platform.ExpandPath(src.Dest)
|
||||
if dest == "" {
|
||||
dest = fallbackDest
|
||||
}
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "tar", Args: []string{"-xzf", path, "-C", dest},
|
||||
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("tar: %s", res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ uninstall ---
|
||||
|
||||
func (d *direct) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
if o.DryRun {
|
||||
return Outcome{Message: "dry run"}, nil
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return d.uninstallWindows(ctx, src, o)
|
||||
case "darwin":
|
||||
name := src.AppName
|
||||
if name == "" {
|
||||
return Outcome{}, errors.New("no app_name in the catalog; remove this app manually")
|
||||
}
|
||||
target := filepath.Join("/Applications", name)
|
||||
if _, err := os.Stat(target); err != nil {
|
||||
return Outcome{NoOp: true, Message: "not installed"}, nil
|
||||
}
|
||||
res := run.Exec(ctx, run.Options{Name: "/bin/rm", Args: []string{"-rf", target}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("remove %s: %s", target, res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
default:
|
||||
pkg := src.UninstallID
|
||||
if pkg == "" {
|
||||
return Outcome{}, errors.New("no uninstall_id in the catalog; remove this app manually")
|
||||
}
|
||||
for _, mgr := range [][]string{
|
||||
{"apt-get", "remove", "-y", pkg},
|
||||
{"dnf", "remove", "-y", pkg},
|
||||
{"zypper", "--non-interactive", "remove", pkg},
|
||||
} {
|
||||
if !run.Available(mgr[0]) {
|
||||
continue
|
||||
}
|
||||
res := run.Exec(ctx, run.Options{Name: mgr[0], Args: mgr[1:], Env: aptEnv, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||
if res.Failed() {
|
||||
return Outcome{}, fmt.Errorf("%s: %s", mgr[0], res.Error())
|
||||
}
|
||||
return Outcome{}, nil
|
||||
}
|
||||
return Outcome{}, errors.New("no package manager available to remove this app")
|
||||
}
|
||||
}
|
||||
|
||||
// uninstallWindows finds the app's uninstall registry entry -- which exists no
|
||||
// matter how it was installed -- and runs it silently.
|
||||
func (d *direct) uninstallWindows(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
patterns := o.Detect.Registry
|
||||
if src.UninstallID != "" {
|
||||
patterns = append([]string{src.UninstallID}, patterns...)
|
||||
}
|
||||
entry, ok := detect.FindRegistry(patterns)
|
||||
if !ok {
|
||||
return Outcome{NoOp: true, Message: "no uninstall entry found"}, nil
|
||||
}
|
||||
|
||||
if guid, isMSI := msiProductCode(entry.UninstallString); isMSI {
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "msiexec", Args: []string{"/x", guid, "/qn", "/norestart"},
|
||||
Timeout: o.Timeout, Log: o.Log,
|
||||
})
|
||||
if res.Failed() && !isRebootExit(res.ExitCode) {
|
||||
return Outcome{}, fmt.Errorf("msiexec /x: %s", res.Error())
|
||||
}
|
||||
return Outcome{RebootRequired: isRebootExit(res.ExitCode)}, nil
|
||||
}
|
||||
|
||||
cmdline := entry.QuietUninstallString
|
||||
if cmdline == "" {
|
||||
// Without a quiet string the vendor uninstaller would open a window on
|
||||
// the user's desktop and wait. That is worse than reporting failure.
|
||||
return Outcome{}, fmt.Errorf("%s has no silent uninstall command; remove it manually", entry.DisplayName)
|
||||
}
|
||||
name, args := splitCommandLine(cmdline)
|
||||
if name == "" {
|
||||
return Outcome{}, fmt.Errorf("cannot parse uninstall command %q", cmdline)
|
||||
}
|
||||
res := run.Exec(ctx, run.Options{Name: name, Args: args, Timeout: o.Timeout, Log: o.Log})
|
||||
if res.Failed() && !isRebootExit(res.ExitCode) {
|
||||
return Outcome{}, fmt.Errorf("uninstall %s: %s", entry.DisplayName, res.Error())
|
||||
}
|
||||
return Outcome{RebootRequired: isRebootExit(res.ExitCode)}, nil
|
||||
}
|
||||
|
||||
// msiProductCode extracts the {GUID} from an MSI uninstall string such as
|
||||
// `MsiExec.exe /I{90160000-008C-0000-1000-0000000FF1CE}`.
|
||||
func msiProductCode(uninstall string) (string, bool) {
|
||||
if !strings.Contains(strings.ToLower(uninstall), "msiexec") {
|
||||
return "", false
|
||||
}
|
||||
start := strings.Index(uninstall, "{")
|
||||
end := strings.Index(uninstall, "}")
|
||||
if start < 0 || end < start {
|
||||
return "", false
|
||||
}
|
||||
return uninstall[start : end+1], true
|
||||
}
|
||||
|
||||
// splitCommandLine splits a Windows command line into program and arguments,
|
||||
// honouring double quotes around paths with spaces.
|
||||
func splitCommandLine(s string) (string, []string) {
|
||||
var parts []string
|
||||
var cur strings.Builder
|
||||
inQuote := false
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r == '"':
|
||||
inQuote = !inQuote
|
||||
case (r == ' ' || r == '\t') && !inQuote:
|
||||
if cur.Len() > 0 {
|
||||
parts = append(parts, cur.String())
|
||||
cur.Reset()
|
||||
}
|
||||
default:
|
||||
cur.WriteRune(r)
|
||||
}
|
||||
}
|
||||
if cur.Len() > 0 {
|
||||
parts = append(parts, cur.String())
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
return parts[0], parts[1:]
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- misc ---
|
||||
|
||||
// InferKind guesses the installer format from the URL file extension. It is
|
||||
// exported so a catalog test can check that every direct source resolves to a
|
||||
// kind deployr knows how to install.
|
||||
func InferKind(rawURL string) string {
|
||||
lower := strings.ToLower(rawURL)
|
||||
if i := strings.IndexAny(lower, "?#"); i >= 0 {
|
||||
lower = lower[:i]
|
||||
}
|
||||
for _, ext := range []string{".tar.gz", ".tgz", ".msi", ".msu", ".exe", ".dmg", ".pkg", ".deb", ".rpm", ".zip", ".appimage"} {
|
||||
if strings.HasSuffix(lower, ext) {
|
||||
switch ext {
|
||||
case ".tgz":
|
||||
return "tar.gz"
|
||||
case ".appimage":
|
||||
return "appimage"
|
||||
default:
|
||||
return strings.TrimPrefix(ext, ".")
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func copyFile(src, dest string, mode os.FileMode) error {
|
||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(out, in); err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
return out.Close()
|
||||
}
|
||||
|
||||
// extractZip unpacks an archive, rejecting entries that would escape the
|
||||
// destination directory (zip slip).
|
||||
func extractZip(archive, dest string) error {
|
||||
r, err := zip.OpenReader(archive)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open %s: %w", archive, err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := filepath.Abs(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, f := range r.File {
|
||||
target := filepath.Join(root, filepath.FromSlash(f.Name))
|
||||
if !strings.HasPrefix(target, root+string(os.PathSeparator)) && target != root {
|
||||
return fmt.Errorf("refusing to extract %q outside %s", f.Name, dest)
|
||||
}
|
||||
if f.FileInfo().IsDir() {
|
||||
if err := os.MkdirAll(target, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.Mode()|0o200)
|
||||
if err != nil {
|
||||
rc.Close()
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(out, rc)
|
||||
rc.Close()
|
||||
closeErr := out.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||
)
|
||||
|
||||
// ------------------------------------------------------------------- apt ---
|
||||
|
||||
type apt struct {
|
||||
refreshOnce sync.Once
|
||||
}
|
||||
|
||||
func newApt() *apt { return &apt{} }
|
||||
|
||||
func (a *apt) Name() string { return "apt" }
|
||||
func (a *apt) OSes() []string { return []string{"linux"} }
|
||||
func (a *apt) Label() string { return "APT (Debian/Ubuntu)" }
|
||||
|
||||
func (a *apt) Available(context.Context, Opts) bool {
|
||||
return runtime.GOOS == "linux" && run.Available("apt-get")
|
||||
}
|
||||
|
||||
// aptEnv keeps dpkg from opening a curses prompt and from asking about changed
|
||||
// config files -- either one hangs an unattended run forever.
|
||||
var aptEnv = []string{"DEBIAN_FRONTEND=noninteractive", "APT_LISTCHANGES_FRONTEND=none"}
|
||||
|
||||
var aptConfArgs = []string{
|
||||
"-o", "Dpkg::Options::=--force-confdef",
|
||||
"-o", "Dpkg::Options::=--force-confold",
|
||||
}
|
||||
|
||||
func (a *apt) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: "apt-get",
|
||||
Args: args,
|
||||
Env: aptEnv,
|
||||
NeedRoot: true,
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
// refresh updates the package index once per process. A stale index is the most
|
||||
// common reason an install fails on a machine that has been off for a while.
|
||||
func (a *apt) refresh(ctx context.Context, o Opts) {
|
||||
a.refreshOnce.Do(func() {
|
||||
if o.DryRun {
|
||||
return
|
||||
}
|
||||
if res := a.exec(ctx, o, "update", "-qq"); res.Failed() && o.Log != nil {
|
||||
o.Log.Debugf("apt-get update failed (continuing): %s", res.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (a *apt) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
a.refresh(ctx, o)
|
||||
args := append([]string{"install", "-y"}, aptConfArgs...)
|
||||
args = append(args, src.ID)
|
||||
args = append(args, src.Args...)
|
||||
res := a.exec(ctx, o, args...)
|
||||
return simpleOutcome(res, o, "apt-get install", src.ID)
|
||||
}
|
||||
|
||||
func (a *apt) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
a.refresh(ctx, o)
|
||||
args := append([]string{"install", "--only-upgrade", "-y"}, aptConfArgs...)
|
||||
args = append(args, src.ID)
|
||||
res := a.exec(ctx, o, args...)
|
||||
return simpleOutcome(res, o, "apt-get upgrade", src.ID)
|
||||
}
|
||||
|
||||
func (a *apt) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := a.exec(ctx, o, "remove", "-y", src.ID)
|
||||
return simpleOutcome(res, o, "apt-get remove", src.ID)
|
||||
}
|
||||
|
||||
func (a *apt) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "dpkg-query",
|
||||
Args: []string{"-W", "-f=${Version}", src.ID},
|
||||
Timeout: o.Timeout,
|
||||
Log: o.Log,
|
||||
})
|
||||
if res.Failed() || strings.TrimSpace(res.Stdout) == "" {
|
||||
return "", false
|
||||
}
|
||||
return strings.TrimSpace(res.Stdout), true
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ dnf/zypper ---
|
||||
|
||||
// rpmMgr covers the RPM-family managers, which differ only in their
|
||||
// non-interactive switch and subcommand names.
|
||||
type rpmMgr struct {
|
||||
name string // provider name: dnf or zypper
|
||||
bins []string // candidate executables, in preference order
|
||||
|
||||
once sync.Once
|
||||
bin string
|
||||
}
|
||||
|
||||
func (r *rpmMgr) Name() string { return r.name }
|
||||
func (r *rpmMgr) OSes() []string { return []string{"linux"} }
|
||||
|
||||
func (r *rpmMgr) Label() string {
|
||||
if r.name == "zypper" {
|
||||
return "Zypper (openSUSE)"
|
||||
}
|
||||
return "DNF/YUM (Fedora/RHEL)"
|
||||
}
|
||||
|
||||
func (r *rpmMgr) resolve() string {
|
||||
r.once.Do(func() {
|
||||
if runtime.GOOS != "linux" {
|
||||
return
|
||||
}
|
||||
for _, b := range r.bins {
|
||||
if run.Available(b) {
|
||||
r.bin = b
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
return r.bin
|
||||
}
|
||||
|
||||
func (r *rpmMgr) Available(context.Context, Opts) bool { return r.resolve() != "" }
|
||||
|
||||
func (r *rpmMgr) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||
if r.name == "zypper" {
|
||||
args = append([]string{"--non-interactive"}, args...)
|
||||
} else {
|
||||
args = append(args, "-y")
|
||||
}
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: r.resolve(),
|
||||
Args: args,
|
||||
NeedRoot: true,
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *rpmMgr) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := r.exec(ctx, o, append([]string{"install", src.ID}, src.Args...)...)
|
||||
return simpleOutcome(res, o, r.name+" install", src.ID)
|
||||
}
|
||||
|
||||
func (r *rpmMgr) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
verb := "upgrade"
|
||||
if r.name == "zypper" {
|
||||
verb = "update"
|
||||
}
|
||||
res := r.exec(ctx, o, verb, src.ID)
|
||||
return simpleOutcome(res, o, r.name+" "+verb, src.ID)
|
||||
}
|
||||
|
||||
func (r *rpmMgr) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := r.exec(ctx, o, "remove", src.ID)
|
||||
return simpleOutcome(res, o, r.name+" remove", src.ID)
|
||||
}
|
||||
|
||||
func (r *rpmMgr) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: "rpm",
|
||||
Args: []string{"-q", "--qf", "%{VERSION}-%{RELEASE}", src.ID},
|
||||
Timeout: o.Timeout,
|
||||
Log: o.Log,
|
||||
})
|
||||
if res.Failed() || strings.TrimSpace(res.Stdout) == "" {
|
||||
return "", false
|
||||
}
|
||||
return strings.TrimSpace(res.Stdout), true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- pacman ---
|
||||
|
||||
type pacman struct{}
|
||||
|
||||
func (p *pacman) Name() string { return "pacman" }
|
||||
func (p *pacman) OSes() []string { return []string{"linux"} }
|
||||
func (p *pacman) Label() string { return "pacman (Arch)" }
|
||||
|
||||
func (p *pacman) Available(context.Context, Opts) bool {
|
||||
return runtime.GOOS == "linux" && run.Available("pacman")
|
||||
}
|
||||
|
||||
func (p *pacman) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: "pacman",
|
||||
Args: args,
|
||||
NeedRoot: true,
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
func (p *pacman) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := p.exec(ctx, o, append([]string{"-S", "--noconfirm", "--needed", src.ID}, src.Args...)...)
|
||||
return simpleOutcome(res, o, "pacman -S", src.ID)
|
||||
}
|
||||
|
||||
func (p *pacman) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
// Arch does not support upgrading a single package against a stale index;
|
||||
// -Syu with a target is the supported way to avoid a partial upgrade.
|
||||
res := p.exec(ctx, o, "-Syu", "--noconfirm", src.ID)
|
||||
return simpleOutcome(res, o, "pacman -Syu", src.ID)
|
||||
}
|
||||
|
||||
func (p *pacman) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := p.exec(ctx, o, "-Rns", "--noconfirm", src.ID)
|
||||
return simpleOutcome(res, o, "pacman -Rns", src.ID)
|
||||
}
|
||||
|
||||
func (p *pacman) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
res := run.Exec(ctx, run.Options{Name: "pacman", Args: []string{"-Q", src.ID}, Timeout: o.Timeout, Log: o.Log})
|
||||
if res.Failed() {
|
||||
return "", false
|
||||
}
|
||||
fields := strings.Fields(res.Stdout)
|
||||
if len(fields) >= 2 {
|
||||
return fields[1], true
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- flatpak ---
|
||||
|
||||
type flatpak struct{}
|
||||
|
||||
func (f *flatpak) Name() string { return "flatpak" }
|
||||
func (f *flatpak) OSes() []string { return []string{"linux"} }
|
||||
func (f *flatpak) Label() string { return "Flatpak" }
|
||||
|
||||
func (f *flatpak) Available(context.Context, Opts) bool {
|
||||
return runtime.GOOS == "linux" && run.Available("flatpak")
|
||||
}
|
||||
|
||||
// scope installs system-wide when we have root and per-user otherwise, so an
|
||||
// unprivileged run still succeeds instead of erroring out.
|
||||
func (f *flatpak) scope() string {
|
||||
if os.Geteuid() == 0 {
|
||||
return "--system"
|
||||
}
|
||||
return "--user"
|
||||
}
|
||||
|
||||
func (f *flatpak) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: "flatpak",
|
||||
Args: args,
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
func (f *flatpak) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
repo := src.Repo
|
||||
if repo == "" {
|
||||
repo = "flathub"
|
||||
}
|
||||
args := []string{"install", f.scope(), "-y", "--noninteractive", repo, src.ID}
|
||||
res := f.exec(ctx, o, append(args, src.Args...)...)
|
||||
return simpleOutcome(res, o, "flatpak install", src.ID)
|
||||
}
|
||||
|
||||
func (f *flatpak) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := f.exec(ctx, o, "update", f.scope(), "-y", "--noninteractive", src.ID)
|
||||
return simpleOutcome(res, o, "flatpak update", src.ID)
|
||||
}
|
||||
|
||||
func (f *flatpak) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := f.exec(ctx, o, "uninstall", f.scope(), "-y", "--noninteractive", src.ID)
|
||||
return simpleOutcome(res, o, "flatpak uninstall", src.ID)
|
||||
}
|
||||
|
||||
func (f *flatpak) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
res := f.exec(ctx, o, "info", src.ID)
|
||||
if res.Failed() {
|
||||
return "", false
|
||||
}
|
||||
for _, line := range strings.Split(res.Stdout, "\n") {
|
||||
if strings.HasPrefix(strings.TrimSpace(line), "Version:") {
|
||||
return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "Version:")), true
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ snap ---
|
||||
|
||||
type snap struct{}
|
||||
|
||||
func (s *snap) Name() string { return "snap" }
|
||||
func (s *snap) OSes() []string { return []string{"linux"} }
|
||||
func (s *snap) Label() string { return "Snap" }
|
||||
|
||||
func (s *snap) Available(context.Context, Opts) bool {
|
||||
return runtime.GOOS == "linux" && run.Available("snap")
|
||||
}
|
||||
|
||||
func (s *snap) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: "snap",
|
||||
Args: args,
|
||||
NeedRoot: true,
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *snap) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := s.exec(ctx, o, append([]string{"install", src.ID}, src.Args...)...)
|
||||
return simpleOutcome(res, o, "snap install", src.ID)
|
||||
}
|
||||
|
||||
func (s *snap) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := s.exec(ctx, o, "refresh", src.ID)
|
||||
return simpleOutcome(res, o, "snap refresh", src.ID)
|
||||
}
|
||||
|
||||
func (s *snap) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := s.exec(ctx, o, "remove", src.ID)
|
||||
return simpleOutcome(res, o, "snap remove", src.ID)
|
||||
}
|
||||
|
||||
func (s *snap) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
res := run.Exec(ctx, run.Options{Name: "snap", Args: []string{"list", src.ID}, Timeout: o.Timeout, Log: o.Log})
|
||||
if res.Failed() {
|
||||
return "", false
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(res.Stdout), "\n")
|
||||
if len(lines) < 2 {
|
||||
return "", true
|
||||
}
|
||||
fields := strings.Fields(lines[1])
|
||||
if len(fields) >= 2 {
|
||||
return fields[1], true
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- shared ---
|
||||
|
||||
// noOpPhrases are the ways the Linux managers say "there was nothing to do".
|
||||
var noOpPhrases = []string{
|
||||
"is already the newest version",
|
||||
"nothing to do",
|
||||
"no packages marked for update",
|
||||
"nothing to upgrade",
|
||||
"is already installed",
|
||||
"reinstalling",
|
||||
"no updates available",
|
||||
"already installed",
|
||||
}
|
||||
|
||||
// simpleOutcome maps a package manager result onto an Outcome, treating
|
||||
// "nothing to do" as success rather than an error.
|
||||
func simpleOutcome(res run.Result, o Opts, what, id string) (Outcome, error) {
|
||||
if o.DryRun {
|
||||
return Outcome{Message: "dry run"}, nil
|
||||
}
|
||||
noop := false
|
||||
for _, phrase := range noOpPhrases {
|
||||
if res.Contains(phrase) {
|
||||
noop = true
|
||||
break
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case !res.Failed():
|
||||
if noop {
|
||||
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||
}
|
||||
return Outcome{}, nil
|
||||
case noop:
|
||||
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("%s %s: %s", what, id, res.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//go:build !windows
|
||||
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// fileOwner returns the account name that owns path.
|
||||
func fileOwner(path string) (string, bool) {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
u, err := user.LookupId(strconv.FormatUint(uint64(stat.Uid), 10))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return u.Username, true
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package provider
|
||||
|
||||
// fileOwner is only meaningful for the Unix privilege-dropping path.
|
||||
func fileOwner(string) (string, bool) { return "", false }
|
||||
@@ -0,0 +1,130 @@
|
||||
// Package provider wraps the package managers and installer formats deployr can
|
||||
// drive. Every provider answers the same five questions — am I present, can I
|
||||
// install, update, uninstall, and what version is here — so the engine can walk
|
||||
// a catalog entry's sources without caring which route wins.
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||
)
|
||||
|
||||
// Opts is the ambient configuration for a provider operation.
|
||||
type Opts struct {
|
||||
DryRun bool
|
||||
Timeout time.Duration
|
||||
Log *logx.Logger
|
||||
CacheDir string
|
||||
Arch string
|
||||
RequireChecksum bool
|
||||
// Detect carries the app's presence rules, which the direct provider needs
|
||||
// to locate an uninstall entry it did not create.
|
||||
Detect catalog.Detect
|
||||
// KeepDownloads leaves fetched installers in the cache directory.
|
||||
KeepDownloads bool
|
||||
}
|
||||
|
||||
// Outcome describes what a provider actually did.
|
||||
type Outcome struct {
|
||||
// Version installed, when the provider can report it.
|
||||
Version string
|
||||
// RebootRequired is set when the installer returned 3010/1641.
|
||||
RebootRequired bool
|
||||
// NoOp is set when the request was already satisfied.
|
||||
NoOp bool
|
||||
// Message is a short human explanation, e.g. "already up to date".
|
||||
Message string
|
||||
}
|
||||
|
||||
// Provider is one install route.
|
||||
type Provider interface {
|
||||
// Name is the identifier used in catalog sources.
|
||||
Name() string
|
||||
// OSes lists the GOOS values this provider can operate on.
|
||||
OSes() []string
|
||||
// Label is a human description for `deployr doctor`.
|
||||
Label() string
|
||||
// Available reports whether this route is usable on this machine right now.
|
||||
Available(ctx context.Context, o Opts) bool
|
||||
// Install makes the package present.
|
||||
Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error)
|
||||
// Update brings an installed package to the latest version.
|
||||
Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error)
|
||||
// Uninstall removes the package.
|
||||
Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error)
|
||||
// Query returns the version this provider believes is installed.
|
||||
Query(ctx context.Context, src catalog.Source, o Opts) (string, bool)
|
||||
}
|
||||
|
||||
var registry = map[string]Provider{}
|
||||
|
||||
func register(p Provider) { registry[p.Name()] = p }
|
||||
|
||||
func init() {
|
||||
register(&winget{})
|
||||
register(&choco{})
|
||||
register(&brew{cask: false})
|
||||
register(&brew{cask: true})
|
||||
register(newApt())
|
||||
register(&rpmMgr{name: "dnf", bins: []string{"dnf5", "dnf", "yum"}})
|
||||
register(&rpmMgr{name: "zypper", bins: []string{"zypper"}})
|
||||
register(&pacman{})
|
||||
register(&flatpak{})
|
||||
register(&snap{})
|
||||
register(&direct{})
|
||||
}
|
||||
|
||||
// Get returns the provider registered under name.
|
||||
func Get(name string) (Provider, bool) {
|
||||
p, ok := registry[strings.ToLower(strings.TrimSpace(name))]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// All returns every provider, sorted by name.
|
||||
func All() []Provider {
|
||||
out := make([]Provider, 0, len(registry))
|
||||
for _, p := range registry {
|
||||
out = append(out, p)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
|
||||
return out
|
||||
}
|
||||
|
||||
// ForOS returns the providers that can run on a GOOS, sorted by name.
|
||||
func ForOS(goos string) []Provider {
|
||||
var out []Provider
|
||||
for _, p := range All() {
|
||||
for _, os := range p.OSes() {
|
||||
if os == goos {
|
||||
out = append(out, p)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Names lists every registered provider name.
|
||||
func Names() []string {
|
||||
out := make([]string, 0, len(registry))
|
||||
for name := range registry {
|
||||
out = append(out, name)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// Windows installers signal "done, but reboot" rather than failing.
|
||||
const (
|
||||
exitRebootInitiated = 1641
|
||||
exitRebootRequired = 3010
|
||||
)
|
||||
|
||||
func isRebootExit(code int) bool {
|
||||
return code == exitRebootInitiated || code == exitRebootRequired
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInferKind(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"https://x.test/setup.msi": "msi",
|
||||
"https://x.test/setup.EXE": "exe",
|
||||
"https://x.test/app.dmg": "dmg",
|
||||
"https://x.test/app.pkg": "pkg",
|
||||
"https://x.test/app_amd64.deb": "deb",
|
||||
"https://x.test/app.x86_64.rpm": "rpm",
|
||||
"https://x.test/tool.zip": "zip",
|
||||
"https://x.test/tool.tar.gz": "tar.gz",
|
||||
"https://x.test/tool.tgz": "tar.gz",
|
||||
"https://x.test/Tool-1.2.AppImage": "appimage",
|
||||
"https://x.test/download?product=firefox&os=win64": "",
|
||||
// The extension has to be in the path, not the query string: a
|
||||
// download endpoint that merely mentions .msi in a parameter tells us
|
||||
// nothing reliable, and such entries must set `kind` explicitly.
|
||||
"https://download.mozilla.org/?product=firefox-msi-latest-ssl": "",
|
||||
"https://x.test/setup.msi?token=abc#frag": "msi",
|
||||
}
|
||||
for url, want := range cases {
|
||||
if got := InferKind(url); got != want {
|
||||
t.Errorf("InferKind(%q) = %q, want %q", url, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMSIProductCode(t *testing.T) {
|
||||
guid, ok := msiProductCode(`MsiExec.exe /I{90160000-008C-0000-1000-0000000FF1CE}`)
|
||||
if !ok || guid != "{90160000-008C-0000-1000-0000000FF1CE}" {
|
||||
t.Errorf("got %q, %v", guid, ok)
|
||||
}
|
||||
if _, ok := msiProductCode(`"C:\Program Files\App\uninstall.exe" /S`); ok {
|
||||
t.Error("a non-MSI uninstall string should not yield a product code")
|
||||
}
|
||||
if _, ok := msiProductCode("MsiExec.exe /I no-braces"); ok {
|
||||
t.Error("a malformed MSI string should not yield a product code")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitCommandLine(t *testing.T) {
|
||||
name, args := splitCommandLine(`"C:\Program Files\App\uninst.exe" /S /norestart`)
|
||||
if name != `C:\Program Files\App\uninst.exe` {
|
||||
t.Errorf("name = %q", name)
|
||||
}
|
||||
if len(args) != 2 || args[0] != "/S" || args[1] != "/norestart" {
|
||||
t.Errorf("args = %v", args)
|
||||
}
|
||||
|
||||
if name, args := splitCommandLine("uninst.exe"); name != "uninst.exe" || len(args) != 0 {
|
||||
t.Errorf("bare command parsed as %q %v", name, args)
|
||||
}
|
||||
if name, _ := splitCommandLine(" "); name != "" {
|
||||
t.Errorf("blank command line parsed as %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWingetListVersion(t *testing.T) {
|
||||
out := "Name Id Version Available Source\n" +
|
||||
"-----------------------------------------------------------------\n" +
|
||||
"Google Chrome Google.Chrome 129.0.6668.90 winget\n"
|
||||
if got := wingetListVersion(out, "Google.Chrome"); got != "129.0.6668.90" {
|
||||
t.Errorf("version = %q", got)
|
||||
}
|
||||
if got := wingetListVersion(out, "Mozilla.Firefox"); got != "" {
|
||||
t.Errorf("expected no version for an absent id, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractZipRejectsPathTraversal(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
archive := filepath.Join(dir, "evil.zip")
|
||||
|
||||
f, err := os.Create(archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
w, err := zw.Create("../escaped.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write([]byte("nope")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
dest := filepath.Join(dir, "out")
|
||||
if err := extractZip(archive, dest); err == nil {
|
||||
t.Fatal("expected extractZip to refuse an entry outside the destination")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "escaped.txt")); err == nil {
|
||||
t.Fatal("a file escaped the destination directory")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractZipWritesFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
archive := filepath.Join(dir, "good.zip")
|
||||
|
||||
f, err := os.Create(archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
w, err := zw.Create("bin/tool.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write([]byte("hello")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
dest := filepath.Join(dir, "out")
|
||||
if err := extractZip(archive, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(dest, "bin", "tool.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "hello" {
|
||||
t.Errorf("content = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryCoversEveryCatalogProvider makes sure a provider named in the
|
||||
// catalog can actually be looked up, and that the OS lists are sane.
|
||||
func TestRegistryIsConsistent(t *testing.T) {
|
||||
for _, name := range Names() {
|
||||
p, ok := Get(name)
|
||||
if !ok {
|
||||
t.Fatalf("Names() returned %q but Get() does not know it", name)
|
||||
}
|
||||
if p.Name() != name {
|
||||
t.Errorf("provider registered as %q reports Name() = %q", name, p.Name())
|
||||
}
|
||||
if len(p.OSes()) == 0 {
|
||||
t.Errorf("provider %q supports no operating systems", name)
|
||||
}
|
||||
if p.Label() == "" {
|
||||
t.Errorf("provider %q has no label", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForOSFiltersByPlatform(t *testing.T) {
|
||||
for _, goos := range []string{"windows", "darwin", "linux"} {
|
||||
providers := ForOS(goos)
|
||||
if len(providers) == 0 {
|
||||
t.Errorf("no providers for %s", goos)
|
||||
}
|
||||
for _, p := range providers {
|
||||
found := false
|
||||
for _, os := range p.OSes() {
|
||||
if os == goos {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("ForOS(%q) returned %q", goos, p.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
for _, p := range ForOS("windows") {
|
||||
if p.Name() == "apt" {
|
||||
t.Error("apt should not be offered on windows")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsRebootExit(t *testing.T) {
|
||||
for _, code := range []int{1641, 3010} {
|
||||
if !isRebootExit(code) {
|
||||
t.Errorf("%d should be a reboot exit", code)
|
||||
}
|
||||
}
|
||||
for _, code := range []int{0, 1, 1618} {
|
||||
if isRebootExit(code) {
|
||||
t.Errorf("%d should not be a reboot exit", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------- winget ---
|
||||
|
||||
type winget struct {
|
||||
once sync.Once
|
||||
path string
|
||||
}
|
||||
|
||||
func (w *winget) Name() string { return "winget" }
|
||||
func (w *winget) OSes() []string { return []string{"windows"} }
|
||||
func (w *winget) Label() string { return "Windows Package Manager (winget)" }
|
||||
|
||||
// resolve finds winget.exe. The PATH entry is an app-execution alias that only
|
||||
// exists inside a user session, so a run as SYSTEM (which is how an RMM invokes
|
||||
// us) has to reach into the WindowsApps payload directly.
|
||||
func (w *winget) resolve() string {
|
||||
w.once.Do(func() {
|
||||
if runtime.GOOS != "windows" {
|
||||
return
|
||||
}
|
||||
if p, ok := run.Which("winget"); ok {
|
||||
w.path = p
|
||||
return
|
||||
}
|
||||
pf := os.Getenv("ProgramFiles")
|
||||
if pf == "" {
|
||||
pf = "C:\\Program Files"
|
||||
}
|
||||
patterns := []string{
|
||||
filepath.Join(pf, "WindowsApps", "Microsoft.DesktopAppInstaller_*_x64__8wekyb3d8bbwe", "winget.exe"),
|
||||
filepath.Join(pf, "WindowsApps", "Microsoft.DesktopAppInstaller_*_arm64__8wekyb3d8bbwe", "winget.exe"),
|
||||
filepath.Join(pf, "WindowsApps", "Microsoft.DesktopAppInstaller_*", "winget.exe"),
|
||||
}
|
||||
var newest string
|
||||
var newestTime int64
|
||||
for _, pattern := range patterns {
|
||||
matches, _ := filepath.Glob(pattern)
|
||||
for _, m := range matches {
|
||||
info, err := os.Stat(m)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if ts := info.ModTime().Unix(); ts > newestTime {
|
||||
newest, newestTime = m, ts
|
||||
}
|
||||
}
|
||||
}
|
||||
w.path = newest
|
||||
})
|
||||
return w.path
|
||||
}
|
||||
|
||||
func (w *winget) Available(context.Context, Opts) bool { return w.resolve() != "" }
|
||||
|
||||
func (w *winget) base() []string {
|
||||
return []string{
|
||||
"--exact",
|
||||
"--silent",
|
||||
"--accept-package-agreements",
|
||||
"--accept-source-agreements",
|
||||
"--disable-interactivity",
|
||||
}
|
||||
}
|
||||
|
||||
func (w *winget) exec(ctx context.Context, o Opts, args []string) run.Result {
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: w.resolve(),
|
||||
Args: args,
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
func (w *winget) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
args := append([]string{"install", "--id", src.ID}, w.base()...)
|
||||
args = append(args, src.Args...)
|
||||
|
||||
// Prefer a machine-wide install so the software is there for every user --
|
||||
// and because a user-scope install performed as SYSTEM lands in a profile
|
||||
// nobody logs into. Not every package ships a machine-scope installer, so
|
||||
// fall back rather than fail.
|
||||
scoped := append(append([]string{}, args...), "--scope", "machine")
|
||||
res := w.exec(ctx, o, scoped)
|
||||
if res.Failed() && !w.benign(res) && wantsOtherScope(res) {
|
||||
if o.Log != nil {
|
||||
o.Log.Debugf("winget: %s has no machine-scope installer, retrying in default scope", src.ID)
|
||||
}
|
||||
res = w.exec(ctx, o, args)
|
||||
}
|
||||
return w.outcome(res, src, o, "install")
|
||||
}
|
||||
|
||||
func (w *winget) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
args := append([]string{"upgrade", "--id", src.ID}, w.base()...)
|
||||
args = append(args, src.Args...)
|
||||
res := w.exec(ctx, o, args)
|
||||
return w.outcome(res, src, o, "upgrade")
|
||||
}
|
||||
|
||||
func (w *winget) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
args := []string{"uninstall", "--id", src.ID, "--exact", "--silent",
|
||||
"--accept-source-agreements", "--disable-interactivity"}
|
||||
res := w.exec(ctx, o, args)
|
||||
return w.outcome(res, src, o, "uninstall")
|
||||
}
|
||||
|
||||
func (w *winget) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
res := run.Exec(ctx, run.Options{
|
||||
Name: w.resolve(),
|
||||
Args: []string{"list", "--id", src.ID, "--exact", "--accept-source-agreements", "--disable-interactivity"},
|
||||
Timeout: o.Timeout,
|
||||
Log: o.Log,
|
||||
})
|
||||
if res.Failed() {
|
||||
return "", false
|
||||
}
|
||||
return wingetListVersion(res.Stdout, src.ID), true
|
||||
}
|
||||
|
||||
// wingetListVersion pulls the version column out of `winget list` output. The
|
||||
// table is space-aligned and localised, so we anchor on the package id and take
|
||||
// the token after it rather than trusting column positions.
|
||||
func wingetListVersion(out, id string) string {
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if !strings.Contains(line, id) {
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(line)
|
||||
for i, f := range fields {
|
||||
if strings.EqualFold(f, id) && i+1 < len(fields) {
|
||||
return fields[i+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// benign recognises the outcomes winget reports as errors but which mean the
|
||||
// machine is already in the state we asked for.
|
||||
func (w *winget) benign(res run.Result) bool {
|
||||
for _, phrase := range []string{
|
||||
"already installed",
|
||||
"no applicable upgrade",
|
||||
"no newer package versions",
|
||||
"no available upgrade",
|
||||
"no installed package found matching",
|
||||
} {
|
||||
if res.Contains(phrase) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func wantsOtherScope(res run.Result) bool {
|
||||
return res.Contains("scope") || res.Contains("no applicable installer")
|
||||
}
|
||||
|
||||
func (w *winget) outcome(res run.Result, src catalog.Source, o Opts, verb string) (Outcome, error) {
|
||||
if o.DryRun {
|
||||
return Outcome{Message: "dry run"}, nil
|
||||
}
|
||||
switch {
|
||||
case !res.Failed():
|
||||
return Outcome{}, nil
|
||||
case isRebootExit(res.ExitCode):
|
||||
return Outcome{RebootRequired: true}, nil
|
||||
case w.benign(res):
|
||||
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("winget %s %s: %s", verb, src.ID, res.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ chocolatey ---
|
||||
|
||||
type choco struct{}
|
||||
|
||||
func (c *choco) Name() string { return "choco" }
|
||||
func (c *choco) OSes() []string { return []string{"windows"} }
|
||||
func (c *choco) Label() string { return "Chocolatey" }
|
||||
|
||||
func (c *choco) Available(context.Context, Opts) bool {
|
||||
return runtime.GOOS == "windows" && run.Available("choco")
|
||||
}
|
||||
|
||||
func (c *choco) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||
return run.Exec(ctx, run.Options{
|
||||
Name: "choco",
|
||||
Args: append(args, "-y", "--no-progress", "--limit-output"),
|
||||
Timeout: o.Timeout,
|
||||
DryRun: o.DryRun,
|
||||
Log: o.Log,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *choco) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := c.exec(ctx, o, append([]string{"install", src.ID}, src.Args...)...)
|
||||
return c.outcome(res, src, o, "install")
|
||||
}
|
||||
|
||||
func (c *choco) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := c.exec(ctx, o, append([]string{"upgrade", src.ID}, src.Args...)...)
|
||||
return c.outcome(res, src, o, "upgrade")
|
||||
}
|
||||
|
||||
func (c *choco) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||
res := c.exec(ctx, o, "uninstall", src.ID, "--remove-dependencies")
|
||||
return c.outcome(res, src, o, "uninstall")
|
||||
}
|
||||
|
||||
func (c *choco) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||
// Chocolatey 2.x dropped --local-only; 1.x needs it or `list` queries the
|
||||
// remote feed instead of the machine.
|
||||
for _, args := range [][]string{
|
||||
{"list", "--local-only", "--exact", src.ID, "-r"},
|
||||
{"list", "--exact", src.ID, "-r"},
|
||||
} {
|
||||
res := run.Exec(ctx, run.Options{Name: "choco", Args: args, Timeout: o.Timeout, Log: o.Log})
|
||||
if res.Failed() {
|
||||
continue
|
||||
}
|
||||
for _, line := range strings.Split(res.Stdout, "\n") {
|
||||
parts := strings.Split(strings.TrimSpace(line), "|")
|
||||
if len(parts) == 2 && strings.EqualFold(parts[0], src.ID) {
|
||||
return parts[1], true
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (c *choco) outcome(res run.Result, src catalog.Source, o Opts, verb string) (Outcome, error) {
|
||||
if o.DryRun {
|
||||
return Outcome{Message: "dry run"}, nil
|
||||
}
|
||||
switch {
|
||||
case !res.Failed():
|
||||
if res.Contains("already installed") || res.Contains("is not installed") {
|
||||
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||
}
|
||||
return Outcome{RebootRequired: res.Contains("pending reboot")}, nil
|
||||
case isRebootExit(res.ExitCode):
|
||||
return Outcome{RebootRequired: true}, nil
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("choco %s %s: %s", verb, src.ID, res.Error())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user