From 1eaf5e5b4b12251c8833731bbbc2ff5a08d09872 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 09:07:16 +0000 Subject: [PATCH 01/14] feat(update): tell system package installs about new releases, sooner CLIs installed from the apt, yum/dnf or apk repositories did not check for or announce new releases, on the assumption that the OS updates them. Third-party repositories are not covered by unattended upgrades by default, so these users only got a release when they happened to upgrade. - Check and notify for package installs. The package manager is the one whose database owns the executable (dpkg, rpm, apk), asked only before printing a notice; for RPM it is dnf if on PATH, or else yum. The install methods are now apt, dnf, yum and apk, with "package" for an unknown package manager (generic link). - Add the wrapper.package_name config key, and suggest a command that refreshes the index and upgrades the package, with sudo unless root. - Make the weekly throttle per version: a version newer than the one last announced (notified_version in the state) is announced at once. - Announce a release at the end of the run whose background check found it, if the check finished in time, rather than on the next run. The package repositories are updated by the release workflow within a minute of the GitHub release, so the GitHub check is used as is. Co-Authored-By: Claude Fable 5.2 --- .goreleaser.yaml | 8 +- CLAUDE.md | 10 +- README.md | 7 +- commands/root.go | 109 +++++++++++++----- commands/root_test.go | 19 ++- .../update-message-install-detection.md | 34 +++++- internal/config/platformsh-cli.yaml | 1 + internal/config/schema.go | 3 +- internal/config/upsun-cli.yaml | 1 + internal/install.go | 91 +++++++++------ internal/install_test.go | 57 ++++++--- internal/state/state.go | 1 + internal/update.go | 47 +++++--- internal/update_test.go | 23 +++- 14 files changed, 299 insertions(+), 112 deletions(-) diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 28fe0fb7..7ee161af 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -285,10 +285,10 @@ nfpms: - src: completion/zsh/_platform dst: /usr/local/share/zsh/site-functions/_platform # Marks the install as managed by a system package manager, so the CLI - # suppresses its update message. See internal/install.go. The dst must stay + # suggests its upgrade command. See internal/install.go. The dst must stay # at /share//install-source, where is the parent of # the binary's dir (default bindir /usr/bin -> prefix /usr); changing the - # nfpm bindir would silently break suppression. + # nfpm bindir would silently break detection. - src: packaging/install-source dst: /usr/share/platformsh-cli/install-source file_info: { mode: 0644 } @@ -320,10 +320,10 @@ nfpms: - src: completion/zsh/_upsun dst: /usr/local/share/zsh/site-functions/_upsun # Marks the install as managed by a system package manager, so the CLI - # suppresses its update message. See internal/install.go. The dst must stay + # suggests its upgrade command. See internal/install.go. The dst must stay # at /share//install-source, where is the parent of # the binary's dir (default bindir /usr/bin -> prefix /usr); changing the - # nfpm bindir would silently break suppression. + # nfpm bindir would silently break detection. - src: packaging/install-source dst: /usr/share/upsun/install-source file_info: { mode: 0644 } diff --git a/CLAUDE.md b/CLAUDE.md index 9ccd1674..0fd4baf1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -205,13 +205,13 @@ PHP version is still injected via ldflags: ### Update Checks -The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json`; the notice is shown before the command on a later run (see `internal/update.go`). When a check is running, the CLI waits up to 1 second for it before exiting. +The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. -Install-method detection (`internal/install.go`) tailors or suppresses the notice: -- System package managers (apt, yum/dnf, apk) are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`). Before printing a notice, older package installs without the marker are also detected by querying dpkg/rpm/apk. The notice is suppressed because the OS handles updates. -- Homebrew, Scoop, npm, winget, and the bash installer get a tailored upgrade command, built from config fields (`Wrapper.HomebrewTap`, `Wrapper.NpmPackage`, `Wrapper.WingetPackage`, `Wrapper.InstallerURL`, `Application.Executable`). +Install-method detection (`internal/install.go`) tailors the notice: +- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` unless running as root. The package repositories are updated by the release workflow straight after the GitHub release. +- Homebrew, Scoop, npm, winget, and the bash installer also get a tailored upgrade command, built from config fields (`Wrapper.HomebrewTap`, `Wrapper.NpmPackage`, `Wrapper.WingetPackage`, `Wrapper.InstallerURL`, `Application.Executable`). - winget installs are detected by their path (`\WinGet\Packages\`). A release reaches winget only after Microsoft merges its manifest PR in `microsoft/winget-pkgs`, so for winget installs the background check reads the newest version there (from the GitHub API) instead of the latest GitHub release. -- The notice is throttled to once a week (`LastNotified` in state) and only shown in an interactive terminal. +- The notice is only shown in an interactive terminal, and at most once a week for the same version (`LastNotified` and `NotifiedVersion` in state): a newer version is announced without waiting. - `INSTALL_METHOD` forces the method; `UPDATES_CHECK=0` disables checks entirely. - With `CLI_CONFIG_FILE` (e.g. a `config:install` shim), the `wrapper.*` keys and the application name, executable and slug come from the embedded config (`Config.Embedded()`), as the binary is the same. The notice is only shown if there is an upgrade command for the install method, as the binary may be a private copy. diff --git a/README.md b/README.md index fcf67d9d..5577be23 100644 --- a/README.md +++ b/README.md @@ -86,12 +86,13 @@ Upgrade with the tool you installed the CLI with: ### Update notifications When a newer release is available, the CLI prints the upgrade command for your -install method, at most once a week, in an interactive terminal. It prints -nothing for system packages, as the OS updates them. +install method, in an interactive terminal. A release is announced once, then +at most once a week. - `UPSUN_CLI_UPDATES_CHECK=0` disables update checks. - `UPSUN_CLI_INSTALL_METHOD=` overrides the detected install method: - `homebrew`, `scoop`, `npm`, `winget`, `package`, or `script`. + `homebrew`, `scoop`, `npm`, `winget`, `apt`, `dnf`, `yum`, `apk`, `package` + (a system package, with an unknown package manager), or `script`. ## Configuration diff --git a/commands/root.go b/commands/root.go index 80dedb3a..8583570e 100644 --- a/commands/root.go +++ b/commands/root.go @@ -1,6 +1,7 @@ package commands import ( + "bytes" "context" "errors" "fmt" @@ -38,13 +39,13 @@ func Execute(cnf *config.Config) error { err := cmd.ExecuteContext(ctx) var ee *exitError if errors.As(err, &ee) { - waitForUpdateCheck() + finishUpdateCheck() os.Exit(ee.code) } if err != nil && !isQuiet() { fmt.Fprintln(color.Error, "Error:", err) } - waitForUpdateCheck() + finishUpdateCheck() return err } @@ -56,12 +57,19 @@ func isQuiet() bool { // updateCheckWait is the maximum time to wait for a background update check before exiting. const updateCheckWait = time.Second -// updateCheck is the background update check started by the root command, if any. -var updateCheck *internal.UpdateCheck +var ( + // updateCheck is the background update check started by the root command, if any. + updateCheck *internal.UpdateCheck + // showUpdateMessage shows a pending update message, at most once. It is set by the root command. + showUpdateMessage func(atExit bool) +) -// waitForUpdateCheck gives a running update check a chance to save its result. -func waitForUpdateCheck() { - updateCheck.Wait(updateCheckWait) +// finishUpdateCheck gives a running update check a chance to save its result, +// and shows an update message if it found a new release. +func finishUpdateCheck() { + if updateCheck.Wait(updateCheckWait) && showUpdateMessage != nil { + showUpdateMessage(true) + } } func newRootCommand(cnf *config.Config) *cobra.Command { @@ -96,26 +104,38 @@ func newRootCommand(cnf *config.Config) *cobra.Command { if viper.GetBool("yes") { viper.Set("no-interaction", true) } - // The check runs in the background and caches its result for the - // next invocation. It is waited for briefly before exiting. + // The check runs in the background and caches its result. It is + // waited for briefly before exiting. updateCheck = internal.StartUpdateCheck(cnf) + shown := false + showUpdateMessage = func(atExit bool) { + // In quiet mode the message would be discarded, so it is left for a later run. + if shown || quiet { + return + } + rel := internal.PendingNotification(cnf, config.Version) + if rel == nil { + return + } + shown = true + var msg bytes.Buffer + if printUpdateMessage(&msg, rel, cnf, internal.DetectInstallMethod(cnf)) { + // A blank line separates the message from the command's output. + if atExit { + fmt.Fprintf(cmd.ErrOrStderr(), "\n%s", msg.String()) + } else { + fmt.Fprintf(cmd.ErrOrStderr(), "%s\n", msg.String()) + } + } + internal.MarkNotified(cnf, rel.Version) + } if viper.GetBool("version") { versionCommand.Run(cmd, []string{}) - waitForUpdateCheck() + finishUpdateCheck() os.Exit(0) } - if cnf.Embedded().Wrapper.GitHubRepo != "" { - // Show any update found by a previous run, before the command's - // output. In quiet mode the notice would be discarded, so it is - // left for a later run. - if rel := internal.PendingNotification(cnf, config.Version); rel != nil && !quiet { - // Full detection can find package installs that lack the marker. - if method := internal.DetectInstallMethod(cnf); !method.AutoUpdating() { - printUpdateMessage(cmd.ErrOrStderr(), rel, cnf, method) - } - internal.MarkNotified(cnf) - } - } + // Show any update found by a previous run, before the command's output. + showUpdateMessage(false) if alt.ShouldUpdate(cnf) { go func() { if err := alt.Update(cmd.Context(), cnf, debugLogf); err != nil { @@ -255,15 +275,18 @@ func checkShellConfigLeftovers(w io.Writer, cnf *config.Config) { // binary and its upgrade command are the same with or without CLI_CONFIG_FILE. // With CLI_CONFIG_FILE, it prints nothing if there is no upgrade command: the // binary may be a private copy, which the generic instructions do not update. -func printUpdateMessage(w io.Writer, rel *internal.ReleaseInfo, cnf *config.Config, method internal.InstallMethod) { +// It reports whether it printed a message. +func printUpdateMessage( + w io.Writer, rel *internal.ReleaseInfo, cnf *config.Config, method internal.InstallMethod, +) bool { if rel == nil { - return + return false } bin := cnf.Embedded() exe, _ := os.Executable() upgradeCmd := upgradeCommandFor(bin, method, exe) if upgradeCmd == "" && !cnf.IsEmbedded() { - return + return false } fmt.Fprintf(w, "%s %s → %s\n", @@ -282,7 +305,8 @@ func printUpdateMessage(w io.Writer, rel *internal.ReleaseInfo, cnf *config.Conf ) } - fmt.Fprintf(w, "%s\n\n", color.YellowString(rel.URL)) + fmt.Fprintln(w, color.YellowString(rel.URL)) + return true } // upgradeCommandFor returns the upgrade command for the install method, or an @@ -304,6 +328,10 @@ func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe st if cnf.Wrapper.WingetPackage != "" { return "winget upgrade " + cnf.Wrapper.WingetPackage } + case internal.InstallApt, internal.InstallDnf, internal.InstallYum, internal.InstallApk: + if pkg := cnf.Wrapper.PackageName; pkg != "" { + return packageUpgradeCommand(method, pkg, geteuid() == 0) + } case internal.InstallScript: // The raw method replaces the binary in INSTALL_DIR; without it, the // installer may choose a package manager instead (e.g. apt on Debian). @@ -315,6 +343,31 @@ func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe st return "" } +// geteuid can be replaced in tests. +var geteuid = os.Geteuid + +// packageUpgradeCommand returns the command to refresh a system package +// manager's index and upgrade a package, with sudo unless running as root. +func packageUpgradeCommand(method internal.InstallMethod, pkg string, root bool) string { + var cmds []string + switch method { + case internal.InstallApt: + cmds = []string{"apt update", "apt install --only-upgrade " + pkg} + case internal.InstallDnf: + cmds = []string{"dnf upgrade --refresh " + pkg} + case internal.InstallYum: + cmds = []string{"yum upgrade " + pkg} + case internal.InstallApk: + cmds = []string{"apk add --upgrade --update-cache " + pkg} + } + if !root { + for i := range cmds { + cmds[i] = "sudo " + cmds[i] + } + } + return strings.Join(cmds, " && ") +} + var shellSafe = regexp.MustCompile(`^[A-Za-z0-9_./-]+$`) // shellQuote quotes s for a POSIX shell, if needed. @@ -343,13 +396,13 @@ func exitWithError(err error) { exitCode = 128 + int(ws.Signal()) } debugLogf("%s", err) - waitForUpdateCheck() + finishUpdateCheck() os.Exit(exitCode) } if !isQuiet() { fmt.Fprintln(color.Error, color.RedString(err.Error())) } - waitForUpdateCheck() + finishUpdateCheck() os.Exit(1) } diff --git a/commands/root_test.go b/commands/root_test.go index 3e1ea058..79085174 100644 --- a/commands/root_test.go +++ b/commands/root_test.go @@ -17,8 +17,13 @@ func TestUpgradeCommandFor(t *testing.T) { cnf.Wrapper.NpmPackage = "upsun" cnf.Wrapper.WingetPackage = "Upsun.CLI" cnf.Wrapper.InstallerURL = "https://x.test/i.sh" + cnf.Wrapper.PackageName = "upsun-cli" cnf.Application.Executable = "upsun" + origGeteuid := geteuid + t.Cleanup(func() { geteuid = origGeteuid }) + geteuid = func() int { return 1000 } + cases := []struct { method internal.InstallMethod want string @@ -28,7 +33,11 @@ func TestUpgradeCommandFor(t *testing.T) { {internal.InstallNpm, "npm install -g upsun@latest"}, {internal.InstallWinget, "winget upgrade Upsun.CLI"}, {internal.InstallScript, "curl -fsSL https://x.test/i.sh | INSTALL_METHOD=raw INSTALL_DIR=/usr/local/bin sh"}, - {internal.InstallPackage, ""}, // suppressed; no tailored command + {internal.InstallApt, "sudo apt update && sudo apt install --only-upgrade upsun-cli"}, + {internal.InstallDnf, "sudo dnf upgrade --refresh upsun-cli"}, + {internal.InstallYum, "sudo yum upgrade upsun-cli"}, + {internal.InstallApk, "sudo apk add --upgrade --update-cache upsun-cli"}, + {internal.InstallPackage, ""}, // an unknown package manager falls back to the generic link {internal.InstallUnknown, ""}, // falls back to the generic link } for _, c := range cases { @@ -45,6 +54,14 @@ func TestUpgradeCommandForMissingConfigFallsBack(t *testing.T) { assert.Empty(t, upgradeCommandFor(cnf, internal.InstallNpm, "/usr/local/bin/upsun")) assert.Empty(t, upgradeCommandFor(cnf, internal.InstallWinget, "/usr/local/bin/upsun")) assert.Empty(t, upgradeCommandFor(cnf, internal.InstallScript, "/usr/local/bin/upsun")) + assert.Empty(t, upgradeCommandFor(cnf, internal.InstallApt, "/usr/bin/upsun")) +} + +func TestPackageUpgradeCommandAsRoot(t *testing.T) { + assert.Equal(t, "apt update && apt install --only-upgrade upsun-cli", + packageUpgradeCommand(internal.InstallApt, "upsun-cli", true)) + assert.Equal(t, "apk add --upgrade --update-cache upsun-cli", + packageUpgradeCommand(internal.InstallApk, "upsun-cli", true)) } func TestShellQuote(t *testing.T) { diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index 29f503c1..a64c3d56 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -4,6 +4,35 @@ Status: draft Author: Claude Code (for Patrick Dawkins) Date: 2026-06-14 +## Revision (2026-11-16): system packages are notified + +The sections below describe the original design, which stayed silent for system +packages (apt, yum/dnf, apk). That assumed the OS updates them, but third-party +repositories are not covered by unattended upgrades by default, so users only +got a new release when they happened to upgrade. This revision changes that: + +- Package installs check for updates and show the notice like other methods. + `AutoUpdating` and the `shouldCheckForUpdate` short-circuit are removed. +- The package repositories are updated by the release workflow straight after + the GitHub release (within a minute), so the GitHub check is used as is. If + that upload fails, the suggested command finds nothing to upgrade. +- The package manager is the one whose database owns the executable + (`dpkg-query -S`, `rpm -qf`, `apk info --who-owns`), asked only before + printing a notice. For RPM it is `dnf` if that is on `PATH`, or else `yum`. + The methods are `apt`, `dnf`, `yum` and `apk`; `package` remains for a + package with an unknown package manager, which gets the generic link. +- The package name is the new `wrapper.package_name` config key. +- Commands, with `sudo` unless running as root: + - `apt update && apt install --only-upgrade ` + - `dnf upgrade --refresh ` + - `yum upgrade ` + - `apk add --upgrade --update-cache ` +- The weekly throttle is per version: `notified_version` in the state records + the version last announced, and a newer one is announced without waiting. +- If the background check finishes before the command exits (it is waited for, + for up to 1 second), a release it found is announced at the end of that run, + unless a notice was already shown at the start. + ## Background The CLI checks GitHub for a newer release and, if one exists, prints a message @@ -206,7 +235,8 @@ hint. | Method | Notice shown? | Upgrade command | Auto-updatable? | |---|---|---|---| -| `package` | No (suppressed) | — | — (OS handles it) | +| `apt`, `dnf`, `yum`, `apk` | Yes | See the revision above | No (privileged) | +| `package` | Yes | generic link, as for `unknown` | No | | `homebrew` | Yes | `brew update && brew upgrade ` | Yes | | `scoop` | Yes | `scoop update ` | Yes | | `npm` | Yes | `npm install -g @latest` | Yes | @@ -424,7 +454,7 @@ upgrade line per method, including empty-config fallbacks. ## Resolved decisions -- `package` installs: total silence, no hint. The OS handles updates. +- `package` installs: originally silent; now notified (see the revision at the top). - Manual `dpkg -i`/`rpm -i`: treated as `package` (suppressed). Acceptable. - npm upgrade command: global `npm install -g @latest`. - Ambiguous / no marker: fall back to `script`/`unknown`, advise re-running the diff --git a/internal/config/platformsh-cli.yaml b/internal/config/platformsh-cli.yaml index edd4a664..4d74830f 100644 --- a/internal/config/platformsh-cli.yaml +++ b/internal/config/platformsh-cli.yaml @@ -6,6 +6,7 @@ wrapper: homebrew_tap: upsun/tap/platformsh-cli github_repo: upsun/cli + package_name: platformsh-cli application: name: "Upsun CLI (Platform.sh compatibility)" diff --git a/internal/config/schema.go b/internal/config/schema.go index 38cc1e07..294604d3 100644 --- a/internal/config/schema.go +++ b/internal/config/schema.go @@ -24,8 +24,9 @@ type Config struct { GitHubRepo string `yaml:"github_repo,omitempty"` // e.g. "upsun/cli" NpmPackage string `yaml:"npm_package,omitempty"` // e.g. "upsun" WingetPackage string `yaml:"winget_package,omitempty"` // e.g. "Upsun.CLI" + PackageName string `yaml:"package_name,omitempty"` // the apt, yum/dnf and apk package, e.g. "upsun-cli" InstallerURL string `yaml:"installer_url,omitempty"` // e.g. "https://raw.githubusercontent.com/upsun/cli/main/installer.sh" - InstallMethod string `yaml:"install_method,omitempty"` // forces the detected install method (homebrew, scoop, npm, winget, package, script) + InstallMethod string `yaml:"install_method,omitempty"` // forces the detected install method (homebrew, scoop, npm, winget, apt, dnf, yum, apk, package, script) } `yaml:"wrapper,omitempty"` Application struct { diff --git a/internal/config/upsun-cli.yaml b/internal/config/upsun-cli.yaml index 6b4896ce..a0cea151 100644 --- a/internal/config/upsun-cli.yaml +++ b/internal/config/upsun-cli.yaml @@ -4,6 +4,7 @@ wrapper: homebrew_tap: upsun/tap/upsun-cli github_repo: upsun/cli + package_name: upsun-cli npm_package: upsun winget_package: Upsun.CLI installer_url: https://raw.githubusercontent.com/upsun/cli/main/installer.sh diff --git a/internal/install.go b/internal/install.go index 19ce95bb..59310500 100644 --- a/internal/install.go +++ b/internal/install.go @@ -24,16 +24,14 @@ const ( InstallScoop InstallMethod = "scoop" InstallNpm InstallMethod = "npm" InstallWinget InstallMethod = "winget" - InstallPackage InstallMethod = "package" // a system package manager: apt, yum/dnf, apk + InstallApt InstallMethod = "apt" + InstallDnf InstallMethod = "dnf" + InstallYum InstallMethod = "yum" + InstallApk InstallMethod = "apk" + InstallPackage InstallMethod = "package" // a system package, with an unknown package manager InstallScript InstallMethod = "script" // the bash installer's raw method ) -// AutoUpdating reports whether the host system updates the CLI on its own, in -// which case the CLI should stay quiet about new releases. -func (m InstallMethod) AutoUpdating() bool { - return m == InstallPackage -} - // installProbe holds the (injectable) inputs to install-method detection. type installProbe struct { goos string @@ -45,7 +43,7 @@ type installProbe struct { getenv func(string) string fileExists func(string) bool brewPrefix func() (string, bool) - pkgOwned func(exe string) bool + pkgManager func(exe string) InstallMethod } var ( @@ -77,18 +75,8 @@ func newInstallProbe(cnf *config.Config) *installProbe { getenv: getenvFunc, fileExists: fileExists, brewPrefix: brewPrefix, - pkgOwned: ownedBySystemPackage, - } -} - -// IsAutoUpdating is a cheap check (no subprocess) suitable for the hot path. It -// only considers an explicit override and the package marker file. -func IsAutoUpdating(cnf *config.Config) bool { - bin := cnf.Embedded() - if m, ok := overrideMethod(cnf.Application.EnvPrefix, bin.Wrapper.InstallMethod, getenvFunc); ok { - return m.AutoUpdating() + pkgManager: owningPackageManager, } - return packageMarkerExists(resolvedExecutable(), bin.Application.Slug, fileExists) } // IsWinget is a cheap check (no subprocess) for a winget install. @@ -110,6 +98,9 @@ func detectInstallMethod(p *installProbe) InstallMethod { return m } if packageMarkerExists(p.exe, p.slug, p.fileExists) { + if m := p.pkgManager(p.exe); m != InstallUnknown { + return m + } return InstallPackage } n := normPath(p.exe) @@ -127,8 +118,10 @@ func detectInstallMethod(p *installProbe) InstallMethod { } if inStandardBinDir(p.exe) { // Packages installed before the marker file existed lack it. - if p.goos == "linux" && p.pkgOwned(p.exe) { - return InstallPackage + if p.goos == "linux" { + if m := p.pkgManager(p.exe); m != InstallUnknown { + return m + } } return InstallScript } @@ -158,7 +151,15 @@ func parseMethod(v string) (InstallMethod, bool) { return InstallWinget, true case string(InstallScript): return InstallScript, true - case string(InstallPackage), "apt", "yum", "dnf", "apk", "deb", "rpm": + case string(InstallApt): + return InstallApt, true + case string(InstallDnf): + return InstallDnf, true + case string(InstallYum): + return InstallYum, true + case string(InstallApk): + return InstallApk, true + case string(InstallPackage), "deb", "rpm": return InstallPackage, true } return InstallUnknown, false @@ -237,27 +238,49 @@ func fileExists(p string) bool { return err == nil } -// ownedBySystemPackage asks the system package database whether it owns exe. -// A time limit stops a slow database from delaying the command; a timeout -// counts as owned, to err on the side of silence. -func ownedBySystemPackage(exe string) bool { +// owningPackageManager asks the system package databases which one owns exe, +// and returns its install method, or InstallUnknown if none does. A time limit +// stops a slow database from delaying the command; a timeout counts as owned +// (InstallPackage), so that the installer script is not suggested. +func owningPackageManager(exe string) InstallMethod { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - queries := [][]string{ - {"dpkg-query", "-S", exe}, - {"rpm", "-qf", exe}, - {"apk", "info", "--who-owns", exe}, + queries := []struct { + method InstallMethod + args []string + }{ + {InstallApt, []string{"dpkg-query", "-S", exe}}, + {InstallDnf, []string{"rpm", "-qf", exe}}, + {InstallApk, []string{"apk", "info", "--who-owns", exe}}, } for _, q := range queries { - p, err := exec.LookPath(q[0]) + p, err := exec.LookPath(q.args[0]) if err != nil { continue } - if err := exec.CommandContext(ctx, p, q[1:]...).Run(); err == nil || ctx.Err() != nil { - return true + err = exec.CommandContext(ctx, p, q.args[1:]...).Run() + if ctx.Err() != nil { + return InstallPackage } + if err != nil { + continue + } + if q.method == InstallDnf { + return rpmFrontend(exec.LookPath) + } + return q.method } - return false + return InstallUnknown +} + +// rpmFrontend returns the install method for an RPM package: dnf, or else yum. +func rpmFrontend(lookPath func(string) (string, error)) InstallMethod { + for _, m := range []InstallMethod{InstallDnf, InstallYum} { + if _, err := lookPath(string(m)); err == nil { + return m + } + } + return InstallPackage } func brewPrefix() (string, bool) { diff --git a/internal/install_test.go b/internal/install_test.go index 25b5a69e..f83ac560 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -1,7 +1,9 @@ package internal import ( + "os/exec" "path" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -43,16 +45,26 @@ func TestDetectInstallMethod(t *testing.T) { want: InstallNpm, }, { - name: "override alias apt maps to package", + name: "override names a package manager", probe: installProbe{ goos: "linux", exe: "/somewhere/upsun", envPrefix: "UPSUN_CLI_", slug: "upsun", getenv: func(k string) string { return map[string]string{"UPSUN_CLI_INSTALL_METHOD": "apt"}[k] }, fileExists: noFile, brewPrefix: noBrew, }, - want: InstallPackage, + want: InstallApt, }, { - name: "package marker present", + name: "package marker present, owned by a package", + probe: installProbe{ + goos: "linux", exe: "/usr/bin/upsun", slug: "upsun", + getenv: func(string) string { return "" }, brewPrefix: noBrew, + fileExists: fileAt("/usr/share/upsun/install-source"), + pkgManager: func(string) InstallMethod { return InstallApk }, + }, + want: InstallApk, + }, + { + name: "package marker present, unknown package manager", probe: installProbe{ goos: "linux", exe: "/usr/bin/upsun", slug: "upsun", getenv: func(string) string { return "" }, brewPrefix: noBrew, @@ -148,9 +160,14 @@ func TestDetectInstallMethod(t *testing.T) { probe: installProbe{ goos: "linux", exe: "/usr/bin/upsun", slug: "upsun", getenv: func(string) string { return "" }, fileExists: noFile, brewPrefix: noBrew, - pkgOwned: func(exe string) bool { return exe == "/usr/bin/upsun" }, + pkgManager: func(exe string) InstallMethod { + if exe == "/usr/bin/upsun" { + return InstallDnf + } + return InstallUnknown + }, }, - want: InstallPackage, + want: InstallDnf, }, { name: "homebrew via brew prefix", @@ -172,19 +189,26 @@ func TestDetectInstallMethod(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - if c.probe.pkgOwned == nil { - c.probe.pkgOwned = func(string) bool { return false } + if c.probe.pkgManager == nil { + c.probe.pkgManager = func(string) InstallMethod { return InstallUnknown } } assert.Equal(t, c.want, detectInstallMethod(&c.probe)) }) } } -func TestInstallMethodAutoUpdating(t *testing.T) { - assert.True(t, InstallPackage.AutoUpdating()) - assert.False(t, InstallHomebrew.AutoUpdating()) - assert.False(t, InstallScript.AutoUpdating()) - assert.False(t, InstallUnknown.AutoUpdating()) +func TestRPMFrontend(t *testing.T) { + has := func(names ...string) func(string) (string, error) { + return func(name string) (string, error) { + if slices.Contains(names, name) { + return "/usr/bin/" + name, nil + } + return "", exec.ErrNotFound + } + } + assert.Equal(t, InstallDnf, rpmFrontend(has("dnf", "yum"))) + assert.Equal(t, InstallYum, rpmFrontend(has("yum"))) + assert.Equal(t, InstallPackage, rpmFrontend(has("zypper"))) } func TestParseMethod(t *testing.T) { @@ -195,9 +219,12 @@ func TestParseMethod(t *testing.T) { }{ {"homebrew", InstallHomebrew, true}, {"brew", InstallHomebrew, true}, - {"APT", InstallPackage, true}, - {"dnf", InstallPackage, true}, - {"apk", InstallPackage, true}, + {"APT", InstallApt, true}, + {"dnf", InstallDnf, true}, + {"yum", InstallYum, true}, + {"apk", InstallApk, true}, + {"package", InstallPackage, true}, + {"rpm", InstallPackage, true}, {"npm", InstallNpm, true}, {" scoop ", InstallScoop, true}, {"winget", InstallWinget, true}, diff --git a/internal/state/state.go b/internal/state/state.go index 92e1b4b0..101dd896 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -13,6 +13,7 @@ type State struct { Updates struct { LastChecked int64 `json:"last_checked"` LastNotified int64 `json:"last_notified,omitempty"` + NotifiedVersion string `json:"notified_version,omitempty"` KnownLatestVersion string `json:"known_latest_version,omitempty"` } `json:"updates,omitempty"` diff --git a/internal/update.go b/internal/update.go index 69061c35..60b3e0cf 100644 --- a/internal/update.go +++ b/internal/update.go @@ -65,25 +65,27 @@ func StartUpdateCheck(cnf *config.Config) *UpdateCheck { return c } -// Wait waits for the check to finish, up to the given timeout. -func (c *UpdateCheck) Wait(timeout time.Duration) { +// Wait waits for the check to finish, up to the given timeout, and reports whether it did. +func (c *UpdateCheck) Wait(timeout time.Duration) bool { if c == nil { - return + return false } select { case <-c.done: + return true case <-time.After(timeout): + return false } } -// notifyInterval is the minimum time between showing update messages. +// notifyInterval is the minimum time between update messages about the same version. const notifyInterval = 7 * 24 * 60 * 60 // one week, in seconds // PendingNotification returns a release to tell the user about, based on the -// version cached by a previous background check. It returns nil when there is -// nothing to show, when the weekly throttle has not elapsed, or when the -// environment is not eligible. The caller should print the result and then call -// MarkNotified. +// version cached by a background check. It returns nil when there is nothing +// to show, when the user was told about this version (or a newer one) in the +// past week, or when the environment is not eligible. The caller should print +// the result and then call MarkNotified. func PendingNotification(cnf *config.Config, currentVersion string) *ReleaseInfo { if !shouldCheckForUpdate(cnf) { return nil @@ -101,26 +103,39 @@ func notificationFromState(s state.State, repo, currentVersion string, now int64 if s.Updates.KnownLatestVersion == "" { return nil } - // A LastNotified in the future (clock skew) is treated as stale. - if s.Updates.LastNotified != 0 && s.Updates.LastNotified <= now && now-s.Updates.LastNotified < notifyInterval { - return nil - } cmp, err := version.Compare(s.Updates.KnownLatestVersion, currentVersion) if err != nil || cmp <= 0 { return nil } + // A LastNotified in the future (clock skew) is treated as stale. + recent := s.Updates.LastNotified != 0 && s.Updates.LastNotified <= now && now-s.Updates.LastNotified < notifyInterval + if recent && !newerThanNotified(s) { + return nil + } return &ReleaseInfo{ Version: s.Updates.KnownLatestVersion, URL: fmt.Sprintf("https://github.com/%s/releases/tag/%s", repo, s.Updates.KnownLatestVersion), } } -// MarkNotified records that an update message was just shown, so it is not -// repeated until the next notify interval. -func MarkNotified(cnf *config.Config) { +// newerThanNotified reports whether the cached latest version is newer than +// the one the user was last told about. A state without that version (saved +// by an older CLI) counts as not newer. +func newerThanNotified(s state.State) bool { + if s.Updates.NotifiedVersion == "" { + return false + } + cmp, err := version.Compare(s.Updates.KnownLatestVersion, s.Updates.NotifiedVersion) + return err == nil && cmp > 0 +} + +// MarkNotified records that an update message about a version was just shown, +// so it is not repeated until the next notify interval. +func MarkNotified(cnf *config.Config, notifiedVersion string) { //nolint:errcheck // failing to save state should not affect the rest of the program state.Update(cnf, func(s *state.State) { s.Updates.LastNotified = time.Now().Unix() + s.Updates.NotifiedVersion = notifiedVersion }) } @@ -131,7 +146,7 @@ func shouldCheckForUpdate(cnf *config.Config) bool { cnf.Embedded().Wrapper.GitHubRepo != "" && cnf.Updates.Check && os.Getenv(cnf.Application.EnvPrefix+"UPDATES_CHECK") != "0" && - !isCI() && !IsAutoUpdating(cnf) && + !isCI() && terminal.IsTerminal(os.Stdout) && terminal.IsTerminal(os.Stderr) } diff --git a/internal/update_test.go b/internal/update_test.go index c81a5c9c..28494a1c 100644 --- a/internal/update_test.go +++ b/internal/update_test.go @@ -56,6 +56,23 @@ func TestNotificationFromState(t *testing.T) { assert.NotNil(t, notificationFromState(newState("v2.0.0", lastNotified), "upsun/cli", "v1.0.0", now)) }) + t.Run("a version newer than the one notified is not throttled", func(t *testing.T) { + s := newState("v2.1.0", now-3*24*60*60) + s.Updates.NotifiedVersion = "v2.0.0" + rel := notificationFromState(s, "upsun/cli", "v1.0.0", now) + if assert.NotNil(t, rel) { + assert.Equal(t, "v2.1.0", rel.Version) + } + }) + + t.Run("the version notified is throttled, then shown again", func(t *testing.T) { + s := newState("v2.0.0", now-3*24*60*60) + s.Updates.NotifiedVersion = "v2.0.0" + assert.Nil(t, notificationFromState(s, "upsun/cli", "v1.0.0", now)) + s.Updates.LastNotified = now - 8*24*60*60 + assert.NotNil(t, notificationFromState(s, "upsun/cli", "v1.0.0", now)) + }) + t.Run("notifies when last notified is in the future", func(t *testing.T) { lastNotified := int64(now + 30*24*60*60) // clock skew assert.NotNil(t, notificationFromState(newState("v2.0.0", lastNotified), "upsun/cli", "v1.0.0", now)) @@ -66,7 +83,7 @@ func TestUpdateCheckWait(t *testing.T) { t.Run("nil check returns immediately", func(t *testing.T) { var c *UpdateCheck start := time.Now() - c.Wait(time.Second) + assert.False(t, c.Wait(time.Second)) assert.Less(t, time.Since(start), 100*time.Millisecond) }) @@ -77,14 +94,14 @@ func TestUpdateCheckWait(t *testing.T) { close(c.done) }() start := time.Now() - c.Wait(5 * time.Second) + assert.True(t, c.Wait(5*time.Second)) assert.Less(t, time.Since(start), time.Second) }) t.Run("gives up after the timeout", func(t *testing.T) { c := &UpdateCheck{done: make(chan struct{})} start := time.Now() - c.Wait(50 * time.Millisecond) + assert.False(t, c.Wait(50*time.Millisecond)) assert.GreaterOrEqual(t, time.Since(start), 50*time.Millisecond) }) } From ce19caad8f4e4e9e8fa9400efe7753e20bd6e968 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 09:19:34 +0000 Subject: [PATCH 02/14] fix(update): only suggest a package manager that uses the repository Address review findings on the package install notice: - A downloaded package (installed with dpkg -i, rpm -i or apk add --allow-untrusted) is owned by the package database, but cannot be upgraded with the package manager. The method is now only apt, dnf, yum or apk if the package manager's configuration mentions the host of the repository (the new wrapper.package_repository config key). Otherwise it is "package", which gets the generic link. - The yum command now runs "yum clean expire-cache" first, as yum otherwise uses its cached metadata for hours. - Suggest doas instead of sudo if doas is installed and sudo is not, as is usual on Alpine. - Correct the design document on manual package installs. Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 2 +- commands/root.go | 28 ++++++++--- commands/root_test.go | 27 ++++++++-- .../update-message-install-detection.md | 21 +++++--- internal/config/platformsh-cli.yaml | 1 + internal/config/schema.go | 6 ++- internal/config/upsun-cli.yaml | 1 + internal/install.go | 50 ++++++++++++++++++- internal/install_test.go | 43 ++++++++++++++++ 9 files changed, 156 insertions(+), 23 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0fd4baf1..f614f049 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -208,7 +208,7 @@ PHP version is still injected via ldflags: The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. Install-method detection (`internal/install.go`) tailors the notice: -- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` unless running as root. The package repositories are updated by the release workflow straight after the GitHub release. +- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager's configuration does not mention `Wrapper.PackageRepository` (e.g. a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. - Homebrew, Scoop, npm, winget, and the bash installer also get a tailored upgrade command, built from config fields (`Wrapper.HomebrewTap`, `Wrapper.NpmPackage`, `Wrapper.WingetPackage`, `Wrapper.InstallerURL`, `Application.Executable`). - winget installs are detected by their path (`\WinGet\Packages\`). A release reaches winget only after Microsoft merges its manifest PR in `microsoft/winget-pkgs`, so for winget installs the background check reads the newest version there (from the GitHub API) instead of the latest GitHub release. - The notice is only shown in an interactive terminal, and at most once a week for the same version (`LastNotified` and `NotifiedVersion` in state): a newer version is announced without waiting. diff --git a/commands/root.go b/commands/root.go index 8583570e..6b03637b 100644 --- a/commands/root.go +++ b/commands/root.go @@ -330,7 +330,7 @@ func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe st } case internal.InstallApt, internal.InstallDnf, internal.InstallYum, internal.InstallApk: if pkg := cnf.Wrapper.PackageName; pkg != "" { - return packageUpgradeCommand(method, pkg, geteuid() == 0) + return packageUpgradeCommand(method, pkg, privilegeCommand(geteuid() == 0, exec.LookPath)) } case internal.InstallScript: // The raw method replaces the binary in INSTALL_DIR; without it, the @@ -346,9 +346,24 @@ func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe st // geteuid can be replaced in tests. var geteuid = os.Geteuid +// privilegeCommand returns the command to run another as root: none for root, +// doas if it is installed and sudo is not (e.g. on Alpine), or else sudo. +func privilegeCommand(root bool, lookPath func(string) (string, error)) string { + if root { + return "" + } + if _, err := lookPath("sudo"); err != nil { + if _, err := lookPath("doas"); err == nil { + return "doas" + } + } + return "sudo" +} + // packageUpgradeCommand returns the command to refresh a system package -// manager's index and upgrade a package, with sudo unless running as root. -func packageUpgradeCommand(method internal.InstallMethod, pkg string, root bool) string { +// manager's index and upgrade a package, running each part with the privilege +// command, if any. +func packageUpgradeCommand(method internal.InstallMethod, pkg, privilege string) string { var cmds []string switch method { case internal.InstallApt: @@ -356,13 +371,14 @@ func packageUpgradeCommand(method internal.InstallMethod, pkg string, root bool) case internal.InstallDnf: cmds = []string{"dnf upgrade --refresh " + pkg} case internal.InstallYum: - cmds = []string{"yum upgrade " + pkg} + // Without this, yum uses its cached metadata for hours. + cmds = []string{"yum clean expire-cache", "yum upgrade " + pkg} case internal.InstallApk: cmds = []string{"apk add --upgrade --update-cache " + pkg} } - if !root { + if privilege != "" { for i := range cmds { - cmds[i] = "sudo " + cmds[i] + cmds[i] = privilege + " " + cmds[i] } } return strings.Join(cmds, " && ") diff --git a/commands/root_test.go b/commands/root_test.go index 79085174..39559fa5 100644 --- a/commands/root_test.go +++ b/commands/root_test.go @@ -2,6 +2,8 @@ package commands import ( "bytes" + "os/exec" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -35,7 +37,7 @@ func TestUpgradeCommandFor(t *testing.T) { {internal.InstallScript, "curl -fsSL https://x.test/i.sh | INSTALL_METHOD=raw INSTALL_DIR=/usr/local/bin sh"}, {internal.InstallApt, "sudo apt update && sudo apt install --only-upgrade upsun-cli"}, {internal.InstallDnf, "sudo dnf upgrade --refresh upsun-cli"}, - {internal.InstallYum, "sudo yum upgrade upsun-cli"}, + {internal.InstallYum, "sudo yum clean expire-cache && sudo yum upgrade upsun-cli"}, {internal.InstallApk, "sudo apk add --upgrade --update-cache upsun-cli"}, {internal.InstallPackage, ""}, // an unknown package manager falls back to the generic link {internal.InstallUnknown, ""}, // falls back to the generic link @@ -57,11 +59,26 @@ func TestUpgradeCommandForMissingConfigFallsBack(t *testing.T) { assert.Empty(t, upgradeCommandFor(cnf, internal.InstallApt, "/usr/bin/upsun")) } -func TestPackageUpgradeCommandAsRoot(t *testing.T) { +func TestPackageUpgradeCommandPrivilege(t *testing.T) { assert.Equal(t, "apt update && apt install --only-upgrade upsun-cli", - packageUpgradeCommand(internal.InstallApt, "upsun-cli", true)) - assert.Equal(t, "apk add --upgrade --update-cache upsun-cli", - packageUpgradeCommand(internal.InstallApk, "upsun-cli", true)) + packageUpgradeCommand(internal.InstallApt, "upsun-cli", "")) + assert.Equal(t, "doas apk add --upgrade --update-cache upsun-cli", + packageUpgradeCommand(internal.InstallApk, "upsun-cli", "doas")) +} + +func TestPrivilegeCommand(t *testing.T) { + has := func(names ...string) func(string) (string, error) { + return func(name string) (string, error) { + if slices.Contains(names, name) { + return "/usr/bin/" + name, nil + } + return "", exec.ErrNotFound + } + } + assert.Empty(t, privilegeCommand(true, has("sudo"))) + assert.Equal(t, "sudo", privilegeCommand(false, has("sudo", "doas"))) + assert.Equal(t, "doas", privilegeCommand(false, has("doas"))) + assert.Equal(t, "sudo", privilegeCommand(false, has())) } func TestShellQuote(t *testing.T) { diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index a64c3d56..d23374d9 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -21,11 +21,18 @@ got a new release when they happened to upgrade. This revision changes that: printing a notice. For RPM it is `dnf` if that is on `PATH`, or else `yum`. The methods are `apt`, `dnf`, `yum` and `apk`; `package` remains for a package with an unknown package manager, which gets the generic link. +- A downloaded package (installed with `dpkg -i`, `rpm -i` or + `apk add --allow-untrusted`) cannot be upgraded with the package manager. So + the method is only `apt`, `dnf`, `yum` or `apk` if the package manager's + configuration (`/etc/apt/sources.list*`, `/etc/yum.repos.d/*.repo`, + `/etc/apk/repositories*`) mentions the repository's host, the new + `wrapper.package_repository` config key. Otherwise it is `package`. - The package name is the new `wrapper.package_name` config key. -- Commands, with `sudo` unless running as root: +- Commands, with `sudo` unless running as root (or `doas`, if it is installed + and `sudo` is not, as is usual on Alpine): - `apt update && apt install --only-upgrade ` - `dnf upgrade --refresh ` - - `yum upgrade ` + - `yum clean expire-cache && yum upgrade ` - `apk add --upgrade --update-cache ` - The weekly throttle is per version: `notified_version` in the state records the version last announced, and a newer one is announced without waiting. @@ -90,7 +97,8 @@ is shown even when the user cannot act on it usefully: those channels we print the command rather than executing it (see Phase 2). - Changing the network-check throttle, the CI gate, or the TTY gate. - Detecting manual `dpkg -i` / `rpm -i` installs that bypass a repo. These are - treated as "package" (auto-updating); see Edge cases. + treated as "package"; see Edge cases (and the revision above, which does + detect them). ## Phasing @@ -400,9 +408,8 @@ Phase 2: ## Edge cases - **Manual `dpkg -i` / `rpm -i` of a downloaded package** still carries the - marker, so it is treated as `package` and suppressed even though it will not - auto-update from a repo. Acceptable: the user chose a package format and can - re-run the same install, and the GitHub releases page is still discoverable. + marker, so it is treated as `package`. Originally that was silent; since the + revision at the top, it gets the notice with the generic link. - **`brew --prefix` unavailable / slow.** The `/Cellar/` pre-check avoids the subprocess in the common non-Homebrew case; if `brew` is missing we fall through to `script`/`unknown`, matching today's behavior. @@ -455,7 +462,7 @@ upgrade line per method, including empty-config fallbacks. ## Resolved decisions - `package` installs: originally silent; now notified (see the revision at the top). -- Manual `dpkg -i`/`rpm -i`: treated as `package` (suppressed). Acceptable. +- Manual `dpkg -i`/`rpm -i`: treated as `package`, originally silent; now notified with the generic link. - npm upgrade command: global `npm install -g @latest`. - Ambiguous / no marker: fall back to `script`/`unknown`, advise re-running the installer (or the GitHub link). diff --git a/internal/config/platformsh-cli.yaml b/internal/config/platformsh-cli.yaml index 4d74830f..c6cb1b10 100644 --- a/internal/config/platformsh-cli.yaml +++ b/internal/config/platformsh-cli.yaml @@ -7,6 +7,7 @@ wrapper: homebrew_tap: upsun/tap/platformsh-cli github_repo: upsun/cli package_name: platformsh-cli + package_repository: repositories.upsun.com application: name: "Upsun CLI (Platform.sh compatibility)" diff --git a/internal/config/schema.go b/internal/config/schema.go index 294604d3..0b7d4b37 100644 --- a/internal/config/schema.go +++ b/internal/config/schema.go @@ -25,8 +25,10 @@ type Config struct { NpmPackage string `yaml:"npm_package,omitempty"` // e.g. "upsun" WingetPackage string `yaml:"winget_package,omitempty"` // e.g. "Upsun.CLI" PackageName string `yaml:"package_name,omitempty"` // the apt, yum/dnf and apk package, e.g. "upsun-cli" - InstallerURL string `yaml:"installer_url,omitempty"` // e.g. "https://raw.githubusercontent.com/upsun/cli/main/installer.sh" - InstallMethod string `yaml:"install_method,omitempty"` // forces the detected install method (homebrew, scoop, npm, winget, apt, dnf, yum, apk, package, script) + // The host of the apt, yum/dnf and apk repository, e.g. "repositories.upsun.com". + PackageRepository string `yaml:"package_repository,omitempty"` + InstallerURL string `yaml:"installer_url,omitempty"` // e.g. "https://raw.githubusercontent.com/upsun/cli/main/installer.sh" + InstallMethod string `yaml:"install_method,omitempty"` // forces the detected install method (homebrew, scoop, npm, winget, apt, dnf, yum, apk, package, script) } `yaml:"wrapper,omitempty"` Application struct { diff --git a/internal/config/upsun-cli.yaml b/internal/config/upsun-cli.yaml index a0cea151..f6fc3330 100644 --- a/internal/config/upsun-cli.yaml +++ b/internal/config/upsun-cli.yaml @@ -5,6 +5,7 @@ wrapper: homebrew_tap: upsun/tap/upsun-cli github_repo: upsun/cli package_name: upsun-cli + package_repository: repositories.upsun.com npm_package: upsun winget_package: Upsun.CLI installer_url: https://raw.githubusercontent.com/upsun/cli/main/installer.sh diff --git a/internal/install.go b/internal/install.go index 59310500..6884e2de 100644 --- a/internal/install.go +++ b/internal/install.go @@ -1,6 +1,7 @@ package internal import ( + "bytes" "context" "os" "os/exec" @@ -43,7 +44,9 @@ type installProbe struct { getenv func(string) string fileExists func(string) bool brewPrefix func() (string, bool) + pkgRepo string // the host of the package repository, e.g. "repositories.upsun.com" pkgManager func(exe string) InstallMethod + repoInUse func(m InstallMethod, repo string) bool } var ( @@ -75,7 +78,9 @@ func newInstallProbe(cnf *config.Config) *installProbe { getenv: getenvFunc, fileExists: fileExists, brewPrefix: brewPrefix, + pkgRepo: bin.Wrapper.PackageRepository, pkgManager: owningPackageManager, + repoInUse: packageRepositoryInUse, } } @@ -98,7 +103,7 @@ func detectInstallMethod(p *installProbe) InstallMethod { return m } if packageMarkerExists(p.exe, p.slug, p.fileExists) { - if m := p.pkgManager(p.exe); m != InstallUnknown { + if m := p.packageMethod(); m != InstallUnknown { return m } return InstallPackage @@ -119,7 +124,7 @@ func detectInstallMethod(p *installProbe) InstallMethod { if inStandardBinDir(p.exe) { // Packages installed before the marker file existed lack it. if p.goos == "linux" { - if m := p.pkgManager(p.exe); m != InstallUnknown { + if m := p.packageMethod(); m != InstallUnknown { return m } } @@ -128,6 +133,47 @@ func detectInstallMethod(p *installProbe) InstallMethod { return InstallUnknown } +// packageMethod returns the install method of the package manager that owns +// the executable, or InstallUnknown if none does. It is InstallPackage unless +// the package manager uses the package repository: a downloaded package (e.g. +// installed with "dpkg -i") cannot be upgraded with the package manager. +func (p *installProbe) packageMethod() InstallMethod { + m := p.pkgManager(p.exe) + if m == InstallUnknown || m == InstallPackage { + return m + } + if p.pkgRepo == "" || !p.repoInUse(m, p.pkgRepo) { + return InstallPackage + } + return m +} + +// packageRepoFiles lists the files (as glob patterns) that configure each package manager's repositories. +var packageRepoFiles = map[InstallMethod][]string{ + InstallApt: {"/etc/apt/sources.list", "/etc/apt/sources.list.d/*"}, + InstallDnf: {"/etc/yum.repos.d/*.repo"}, + InstallYum: {"/etc/yum.repos.d/*.repo"}, + InstallApk: {"/etc/apk/repositories", "/etc/apk/repositories.d/*"}, +} + +// packageRepositoryInUse reports whether a package manager's configuration mentions the repository. +func packageRepositoryInUse(m InstallMethod, repo string) bool { + return anyFileContains(packageRepoFiles[m], repo) +} + +// anyFileContains reports whether a file matching one of the glob patterns contains s. +func anyFileContains(patterns []string, s string) bool { + for _, pattern := range patterns { + paths, _ := filepath.Glob(pattern) + for _, path := range paths { + if b, err := os.ReadFile(path); err == nil && bytes.Contains(b, []byte(s)) { + return true + } + } + } + return false +} + // overrideMethod reads a forced install method from the environment or config. func overrideMethod(envPrefix, configMethod string, getenv func(string) string) (InstallMethod, bool) { if v := getenv(envPrefix + "INSTALL_METHOD"); v != "" { diff --git a/internal/install_test.go b/internal/install_test.go index f83ac560..ff42ada0 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -1,8 +1,10 @@ package internal import ( + "os" "os/exec" "path" + "path/filepath" "slices" "testing" @@ -60,9 +62,33 @@ func TestDetectInstallMethod(t *testing.T) { getenv: func(string) string { return "" }, brewPrefix: noBrew, fileExists: fileAt("/usr/share/upsun/install-source"), pkgManager: func(string) InstallMethod { return InstallApk }, + pkgRepo: "repo.example.com", + repoInUse: func(m InstallMethod, repo string) bool { return m == InstallApk && repo == "repo.example.com" }, }, want: InstallApk, }, + { + name: "package marker present, repository not in use (e.g. dpkg -i)", + probe: installProbe{ + goos: "linux", exe: "/usr/bin/upsun", slug: "upsun", + getenv: func(string) string { return "" }, brewPrefix: noBrew, + fileExists: fileAt("/usr/share/upsun/install-source"), + pkgManager: func(string) InstallMethod { return InstallApt }, + pkgRepo: "repo.example.com", + repoInUse: func(InstallMethod, string) bool { return false }, + }, + want: InstallPackage, + }, + { + name: "package marker present, no repository in config", + probe: installProbe{ + goos: "linux", exe: "/usr/bin/upsun", slug: "upsun", + getenv: func(string) string { return "" }, brewPrefix: noBrew, + fileExists: fileAt("/usr/share/upsun/install-source"), + pkgManager: func(string) InstallMethod { return InstallApt }, + }, + want: InstallPackage, + }, { name: "package marker present, unknown package manager", probe: installProbe{ @@ -166,6 +192,8 @@ func TestDetectInstallMethod(t *testing.T) { } return InstallUnknown }, + pkgRepo: "repo.example.com", + repoInUse: func(InstallMethod, string) bool { return true }, }, want: InstallDnf, }, @@ -197,6 +225,21 @@ func TestDetectInstallMethod(t *testing.T) { } } +func TestAnyFileContains(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.Mkdir(filepath.Join(dir, "sources.list.d"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "sources.list"), + []byte("deb http://deb.example.org stable main\n"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "sources.list.d", "example.list"), + []byte("deb https://repo.example.com/debian stable main\n"), 0o600)) + patterns := []string{filepath.Join(dir, "sources.list"), filepath.Join(dir, "sources.list.d", "*")} + + assert.True(t, anyFileContains(patterns, "repo.example.com")) + assert.False(t, anyFileContains(patterns, "other.example.com")) + assert.False(t, anyFileContains(patterns[:1], "repo.example.com")) + assert.False(t, anyFileContains(nil, "repo.example.com")) +} + func TestRPMFrontend(t *testing.T) { has := func(names ...string) func(string) (string, error) { return func(name string) (string, error) { From 2bb9bb8d9b58cae7e6512f79a3c7365068681a79 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 09:23:57 +0000 Subject: [PATCH 03/14] fix(update): ignore disabled package repository entries The repository counted as in use if its host appeared anywhere in the package manager's configuration, including in entries that a release upgrade commented out, in backup files, and in disabled repositories. - Skip comment lines. - Only read the files that apt and apk read (*.list, *.sources). - Skip a file that disables a repository (enabled=0, Enabled: no). The file is not parsed to find out which one, so this errs towards the generic link. Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 2 +- .../update-message-install-detection.md | 4 +- internal/install.go | 37 ++++++++++---- internal/install_test.go | 48 ++++++++++++++----- 4 files changed, 70 insertions(+), 21 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f614f049..79455ea1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -208,7 +208,7 @@ PHP version is still injected via ldflags: The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. Install-method detection (`internal/install.go`) tailors the notice: -- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager's configuration does not mention `Wrapper.PackageRepository` (e.g. a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. +- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager's configuration does not enable `Wrapper.PackageRepository` (e.g. a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. - Homebrew, Scoop, npm, winget, and the bash installer also get a tailored upgrade command, built from config fields (`Wrapper.HomebrewTap`, `Wrapper.NpmPackage`, `Wrapper.WingetPackage`, `Wrapper.InstallerURL`, `Application.Executable`). - winget installs are detected by their path (`\WinGet\Packages\`). A release reaches winget only after Microsoft merges its manifest PR in `microsoft/winget-pkgs`, so for winget installs the background check reads the newest version there (from the GitHub API) instead of the latest GitHub release. - The notice is only shown in an interactive terminal, and at most once a week for the same version (`LastNotified` and `NotifiedVersion` in state): a newer version is announced without waiting. diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index d23374d9..e4269bbe 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -26,7 +26,9 @@ got a new release when they happened to upgrade. This revision changes that: the method is only `apt`, `dnf`, `yum` or `apk` if the package manager's configuration (`/etc/apt/sources.list*`, `/etc/yum.repos.d/*.repo`, `/etc/apk/repositories*`) mentions the repository's host, the new - `wrapper.package_repository` config key. Otherwise it is `package`. + `wrapper.package_repository` config key. Otherwise it is `package`. Comments + do not count, nor does a file that disables a repository (`enabled=0`, + `Enabled: no`). - The package name is the new `wrapper.package_name` config key. - Commands, with `sudo` unless running as root (or `doas`, if it is installed and `sudo` is not, as is usual on Alpine): diff --git a/internal/install.go b/internal/install.go index 6884e2de..ae08d79e 100644 --- a/internal/install.go +++ b/internal/install.go @@ -1,12 +1,12 @@ package internal import ( - "bytes" "context" "os" "os/exec" "path" "path/filepath" + "regexp" "runtime" "strings" "sync" @@ -150,23 +150,23 @@ func (p *installProbe) packageMethod() InstallMethod { // packageRepoFiles lists the files (as glob patterns) that configure each package manager's repositories. var packageRepoFiles = map[InstallMethod][]string{ - InstallApt: {"/etc/apt/sources.list", "/etc/apt/sources.list.d/*"}, + InstallApt: {"/etc/apt/sources.list", "/etc/apt/sources.list.d/*.list", "/etc/apt/sources.list.d/*.sources"}, InstallDnf: {"/etc/yum.repos.d/*.repo"}, InstallYum: {"/etc/yum.repos.d/*.repo"}, - InstallApk: {"/etc/apk/repositories", "/etc/apk/repositories.d/*"}, + InstallApk: {"/etc/apk/repositories", "/etc/apk/repositories.d/*.list"}, } -// packageRepositoryInUse reports whether a package manager's configuration mentions the repository. +// packageRepositoryInUse reports whether a package manager's configuration enables the repository. func packageRepositoryInUse(m InstallMethod, repo string) bool { - return anyFileContains(packageRepoFiles[m], repo) + return anyFileEnablesRepo(packageRepoFiles[m], repo) } -// anyFileContains reports whether a file matching one of the glob patterns contains s. -func anyFileContains(patterns []string, s string) bool { +// anyFileEnablesRepo reports whether a file matching one of the glob patterns enables the repository. +func anyFileEnablesRepo(patterns []string, repo string) bool { for _, pattern := range patterns { paths, _ := filepath.Glob(pattern) for _, path := range paths { - if b, err := os.ReadFile(path); err == nil && bytes.Contains(b, []byte(s)) { + if b, err := os.ReadFile(path); err == nil && enablesRepo(b, repo) { return true } } @@ -174,6 +174,27 @@ func anyFileContains(patterns []string, s string) bool { return false } +// repoDisabled matches a line that disables a repository, in a yum repo file or a deb822 sources file. +var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false)$`) + +// enablesRepo reports whether a repository configuration file mentions the +// repository outside comments. A file that disables any repository does not +// count, as it is not parsed to find out which one. +func enablesRepo(content []byte, repo string) bool { + found := false + for line := range strings.Lines(string(content)) { + line = strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "#"): + case repoDisabled.MatchString(line): + return false + case strings.Contains(line, repo): + found = true + } + } + return found +} + // overrideMethod reads a forced install method from the environment or config. func overrideMethod(envPrefix, configMethod string, getenv func(string) string) (InstallMethod, bool) { if v := getenv(envPrefix + "INSTALL_METHOD"); v != "" { diff --git a/internal/install_test.go b/internal/install_test.go index ff42ada0..630db037 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -225,19 +225,45 @@ func TestDetectInstallMethod(t *testing.T) { } } -func TestAnyFileContains(t *testing.T) { +func TestAnyFileEnablesRepo(t *testing.T) { dir := t.TempDir() - require.NoError(t, os.Mkdir(filepath.Join(dir, "sources.list.d"), 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(dir, "sources.list"), - []byte("deb http://deb.example.org stable main\n"), 0o600)) - require.NoError(t, os.WriteFile(filepath.Join(dir, "sources.list.d", "example.list"), - []byte("deb https://repo.example.com/debian stable main\n"), 0o600)) - patterns := []string{filepath.Join(dir, "sources.list"), filepath.Join(dir, "sources.list.d", "*")} + write := func(name, content string) { + require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) + } + write("other.list", "deb http://deb.example.org stable main\n") + write("example.list", "deb https://repo.example.com/debian stable main\n") + write("example.list.distUpgrade", "deb https://backup.example.com/debian stable main\n") + + patterns := []string{filepath.Join(dir, "other.list"), filepath.Join(dir, "*.list")} + assert.True(t, anyFileEnablesRepo(patterns, "repo.example.com")) + assert.False(t, anyFileEnablesRepo(patterns, "other.example.com")) + assert.False(t, anyFileEnablesRepo(patterns, "backup.example.com")) + assert.False(t, anyFileEnablesRepo(patterns[:1], "repo.example.com")) + assert.False(t, anyFileEnablesRepo(nil, "repo.example.com")) +} - assert.True(t, anyFileContains(patterns, "repo.example.com")) - assert.False(t, anyFileContains(patterns, "other.example.com")) - assert.False(t, anyFileContains(patterns[:1], "repo.example.com")) - assert.False(t, anyFileContains(nil, "repo.example.com")) +func TestEnablesRepo(t *testing.T) { + cases := []struct { + name string + content string + want bool + }{ + {"apt list", "deb [signed-by=/k.asc] https://repo.example.com/debian stable main\n", true}, + {"apt list disabled by a release upgrade", "# deb https://repo.example.com/debian stable main # disabled\n", false}, + {"deb822", "Types: deb\nURIs: https://repo.example.com/debian\nSuites: stable\n", true}, + {"deb822 disabled", "Types: deb\nURIs: https://repo.example.com/debian\nEnabled: no\n", false}, + {"yum", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\ngpgcheck=1\n", true}, + {"yum disabled", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled = 0\n", false}, + {"apk", "https://dl-cdn.example.org/alpine/main\nhttps://repo.example.com/alpine\n", true}, + {"apk commented out", "https://dl-cdn.example.org/alpine/main\n #https://repo.example.com/alpine\n", false}, + {"another repository", "deb http://deb.example.org stable main\n", false}, + {"empty", "", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + assert.Equal(t, c.want, enablesRepo([]byte(c.content), "repo.example.com")) + }) + } } func TestRPMFrontend(t *testing.T) { From 9442688288487a806042a6ecabca1f2db3ba1cda Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 09:27:27 +0000 Subject: [PATCH 04/14] fix(update): recognize more ways to disable a package repository dnf also accepts "off" for enabled=, and apt's deb822 Enabled: field also accepts "off" and "disable". Co-Authored-By: Claude Fable 5.2 --- internal/install.go | 2 +- internal/install_test.go | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/install.go b/internal/install.go index ae08d79e..b16b6b2a 100644 --- a/internal/install.go +++ b/internal/install.go @@ -175,7 +175,7 @@ func anyFileEnablesRepo(patterns []string, repo string) bool { } // repoDisabled matches a line that disables a repository, in a yum repo file or a deb822 sources file. -var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false)$`) +var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false|off|disable)$`) // enablesRepo reports whether a repository configuration file mentions the // repository outside comments. A file that disables any repository does not diff --git a/internal/install_test.go b/internal/install_test.go index 630db037..ac29af2d 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -254,6 +254,8 @@ func TestEnablesRepo(t *testing.T) { {"deb822 disabled", "Types: deb\nURIs: https://repo.example.com/debian\nEnabled: no\n", false}, {"yum", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\ngpgcheck=1\n", true}, {"yum disabled", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled = 0\n", false}, + {"yum disabled with off", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=off\n", false}, + {"deb822 disabled with disable", "URIs: https://repo.example.com/debian\nEnabled: disable\n", false}, {"apk", "https://dl-cdn.example.org/alpine/main\nhttps://repo.example.com/alpine\n", true}, {"apk commented out", "https://dl-cdn.example.org/alpine/main\n #https://repo.example.com/alpine\n", false}, {"another repository", "deb http://deb.example.org stable main\n", false}, From 2c61a0aa6d699671b0e8c5cd3bf0bb339e3a81f7 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 09:32:29 +0000 Subject: [PATCH 05/14] fix(update): recognize apt's "without" as disabling a repository Co-Authored-By: Claude Fable 5.2 --- internal/install.go | 2 +- internal/install_test.go | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/install.go b/internal/install.go index b16b6b2a..8ff95f7d 100644 --- a/internal/install.go +++ b/internal/install.go @@ -175,7 +175,7 @@ func anyFileEnablesRepo(patterns []string, repo string) bool { } // repoDisabled matches a line that disables a repository, in a yum repo file or a deb822 sources file. -var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false|off|disable)$`) +var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false|off|disable|without)$`) // enablesRepo reports whether a repository configuration file mentions the // repository outside comments. A file that disables any repository does not diff --git a/internal/install_test.go b/internal/install_test.go index ac29af2d..f87be8ff 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -256,6 +256,7 @@ func TestEnablesRepo(t *testing.T) { {"yum disabled", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled = 0\n", false}, {"yum disabled with off", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=off\n", false}, {"deb822 disabled with disable", "URIs: https://repo.example.com/debian\nEnabled: disable\n", false}, + {"deb822 disabled with without", "URIs: https://repo.example.com/debian\nEnabled: without\n", false}, {"apk", "https://dl-cdn.example.org/alpine/main\nhttps://repo.example.com/alpine\n", true}, {"apk commented out", "https://dl-cdn.example.org/alpine/main\n #https://repo.example.com/alpine\n", false}, {"another repository", "deb http://deb.example.org stable main\n", false}, From 5e61f93f5130d889b05c72642bbba6838c58b6bb Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 11:59:57 +0000 Subject: [PATCH 06/14] fix(update): honor DNF 5 repository overrides With DNF 5, "dnf config-manager" disables a repository in /etc/dnf/repos.override.d rather than in its file in /etc/yum.repos.d, so a disabled repository still got the dnf upgrade command. For dnf, the override files (also in /usr/share/dnf5/repos.override.d) are now read as DNF applies them: by file name, section names as glob patterns, and the last "enabled" setting wins. Also make TestUpgradeCommandFor independent of whether the host has sudo or doas, and update two comments on install-method detection. Co-Authored-By: Claude Fable 5.2 --- commands/root.go | 9 +- commands/root_test.go | 5 +- .../update-message-install-detection.md | 3 +- internal/install.go | 99 +++++++++++++++++-- internal/install_test.go | 51 +++++++++- 5 files changed, 148 insertions(+), 19 deletions(-) diff --git a/commands/root.go b/commands/root.go index 6b03637b..c7d59cf5 100644 --- a/commands/root.go +++ b/commands/root.go @@ -330,7 +330,7 @@ func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe st } case internal.InstallApt, internal.InstallDnf, internal.InstallYum, internal.InstallApk: if pkg := cnf.Wrapper.PackageName; pkg != "" { - return packageUpgradeCommand(method, pkg, privilegeCommand(geteuid() == 0, exec.LookPath)) + return packageUpgradeCommand(method, pkg, privilegeCommand(geteuid() == 0, lookPath)) } case internal.InstallScript: // The raw method replaces the binary in INSTALL_DIR; without it, the @@ -343,8 +343,11 @@ func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe st return "" } -// geteuid can be replaced in tests. -var geteuid = os.Geteuid +// geteuid and lookPath can be replaced in tests. +var ( + geteuid = os.Geteuid + lookPath = exec.LookPath +) // privilegeCommand returns the command to run another as root: none for root, // doas if it is installed and sudo is not (e.g. on Alpine), or else sudo. diff --git a/commands/root_test.go b/commands/root_test.go index 39559fa5..da117648 100644 --- a/commands/root_test.go +++ b/commands/root_test.go @@ -22,9 +22,10 @@ func TestUpgradeCommandFor(t *testing.T) { cnf.Wrapper.PackageName = "upsun-cli" cnf.Application.Executable = "upsun" - origGeteuid := geteuid - t.Cleanup(func() { geteuid = origGeteuid }) + origGeteuid, origLookPath := geteuid, lookPath + t.Cleanup(func() { geteuid, lookPath = origGeteuid, origLookPath }) geteuid = func() int { return 1000 } + lookPath = func(string) (string, error) { return "", exec.ErrNotFound } cases := []struct { method internal.InstallMethod diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index e4269bbe..2ad80b3a 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -28,7 +28,8 @@ got a new release when they happened to upgrade. This revision changes that: `/etc/apk/repositories*`) mentions the repository's host, the new `wrapper.package_repository` config key. Otherwise it is `package`. Comments do not count, nor does a file that disables a repository (`enabled=0`, - `Enabled: no`). + `Enabled: no`). For dnf, a repository disabled in DNF 5's override files + (`repos.override.d`, written by `dnf config-manager`) does not count either. - The package name is the new `wrapper.package_name` config key. - Commands, with `sudo` unless running as root (or `doas`, if it is installed and `sudo` is not, as is usual on Alpine): diff --git a/internal/install.go b/internal/install.go index 8ff95f7d..8748d94e 100644 --- a/internal/install.go +++ b/internal/install.go @@ -8,6 +8,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strings" "sync" "time" @@ -16,7 +17,7 @@ import ( ) // InstallMethod identifies how the CLI binary was installed, so update messages -// can be tailored or suppressed. +// can be tailored. type InstallMethod string const ( @@ -54,9 +55,9 @@ var ( detectedMethod InstallMethod ) -// DetectInstallMethod resolves the install method once per process. It may shell -// out to "brew", so it is only called when about to print an update message, -// never on the hot path of every command. +// DetectInstallMethod resolves the install method once per process. It may run +// "brew" or a package manager's query, and read package repository files, so it +// is only called when about to print an update message, not for every command. func DetectInstallMethod(cnf *config.Config) InstallMethod { detectOnce.Do(func() { detectedMethod = detectInstallMethod(newInstallProbe(cnf)) @@ -156,24 +157,106 @@ var packageRepoFiles = map[InstallMethod][]string{ InstallApk: {"/etc/apk/repositories", "/etc/apk/repositories.d/*.list"}, } +// dnfOverrideFiles lists the files (as glob patterns) that override repository settings in DNF 5. +var dnfOverrideFiles = []string{"/usr/share/dnf5/repos.override.d/*.repo", "/etc/dnf/repos.override.d/*.repo"} + // packageRepositoryInUse reports whether a package manager's configuration enables the repository. func packageRepositoryInUse(m InstallMethod, repo string) bool { - return anyFileEnablesRepo(packageRepoFiles[m], repo) + var overrides []string + if m == InstallDnf { + overrides = dnfOverrideFiles + } + return anyFileEnablesRepo(packageRepoFiles[m], overrides, repo) } -// anyFileEnablesRepo reports whether a file matching one of the glob patterns enables the repository. -func anyFileEnablesRepo(patterns []string, repo string) bool { +// anyFileEnablesRepo reports whether a file matching one of the glob patterns +// enables the repository, and no file matching the override patterns disables it. +func anyFileEnablesRepo(patterns, overridePatterns []string, repo string) bool { + overrides := readOverrides(overridePatterns) for _, pattern := range patterns { paths, _ := filepath.Glob(pattern) for _, path := range paths { - if b, err := os.ReadFile(path); err == nil && enablesRepo(b, repo) { + b, err := os.ReadFile(path) + if err != nil || !enablesRepo(b, repo) { + continue + } + if len(overrides) == 0 { return true } + for _, id := range repoSections(b, repo) { + if !disabledByOverride(id, overrides) { + return true + } + } } } return false } +// readOverrides reads the files matching the glob patterns, ordered by file name as DNF applies them. +func readOverrides(patterns []string) [][]byte { + var paths []string + for _, pattern := range patterns { + matches, _ := filepath.Glob(pattern) + paths = append(paths, matches...) + } + slices.SortStableFunc(paths, func(a, b string) int { + return strings.Compare(filepath.Base(a), filepath.Base(b)) + }) + var contents [][]byte + for _, path := range paths { + if b, err := os.ReadFile(path); err == nil { + contents = append(contents, b) + } + } + return contents +} + +// sectionName returns the name of an INI section header line, e.g. "[name]". +func sectionName(line string) (string, bool) { + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + return strings.TrimSpace(line[1 : len(line)-1]), true + } + return "", false +} + +// repoSections returns the names of the sections of a yum repo file that mention the repository. +func repoSections(content []byte, repo string) []string { + var ids []string + section := "" + for line := range strings.Lines(string(content)) { + line = strings.TrimSpace(line) + if name, ok := sectionName(line); ok { + section = name + } else if section != "" && !strings.HasPrefix(line, "#") && strings.Contains(line, repo) { + ids = append(ids, section) + section = "" + } + } + return ids +} + +// enabledSetting matches a line that enables or disables a repository. +var enabledSetting = regexp.MustCompile(`(?i)^enabled\s*[=:]`) + +// disabledByOverride reports whether the override files disable a repository. +// Their section names may be glob patterns, and the last setting applies. +func disabledByOverride(id string, overrides [][]byte) bool { + disabled := false + for _, content := range overrides { + applies := false + for line := range strings.Lines(string(content)) { + line = strings.TrimSpace(line) + if name, ok := sectionName(line); ok { + applies, _ = path.Match(name, id) + } else if applies && enabledSetting.MatchString(line) { + disabled = repoDisabled.MatchString(line) + } + } + } + return disabled +} + // repoDisabled matches a line that disables a repository, in a yum repo file or a deb822 sources file. var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false|off|disable|without)$`) diff --git a/internal/install_test.go b/internal/install_test.go index f87be8ff..d15617c7 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -235,11 +235,52 @@ func TestAnyFileEnablesRepo(t *testing.T) { write("example.list.distUpgrade", "deb https://backup.example.com/debian stable main\n") patterns := []string{filepath.Join(dir, "other.list"), filepath.Join(dir, "*.list")} - assert.True(t, anyFileEnablesRepo(patterns, "repo.example.com")) - assert.False(t, anyFileEnablesRepo(patterns, "other.example.com")) - assert.False(t, anyFileEnablesRepo(patterns, "backup.example.com")) - assert.False(t, anyFileEnablesRepo(patterns[:1], "repo.example.com")) - assert.False(t, anyFileEnablesRepo(nil, "repo.example.com")) + assert.True(t, anyFileEnablesRepo(patterns, nil, "repo.example.com")) + assert.False(t, anyFileEnablesRepo(patterns, nil, "other.example.com")) + assert.False(t, anyFileEnablesRepo(patterns, nil, "backup.example.com")) + assert.False(t, anyFileEnablesRepo(patterns[:1], nil, "repo.example.com")) + assert.False(t, anyFileEnablesRepo(nil, nil, "repo.example.com")) +} + +func TestAnyFileEnablesRepoWithOverrides(t *testing.T) { + const repoFile = "[other]\nbaseurl=https://rpm.example.org/\n\n" + + "[example]\nname=Example\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\n" + cases := []struct { + name string + // Override files by path, relative to a temporary directory. + overrides map[string]string + want bool + }{ + {"no overrides", nil, true}, + {"disabled", map[string]string{"etc/99-config_manager.repo": "# Generated.\n[example]\nenabled=0\n"}, false}, + {"another repository disabled", map[string]string{"etc/99-config_manager.repo": "[other]\nenabled=0\n"}, true}, + {"disabled by a glob pattern", map[string]string{"etc/50-all.repo": "[exam*]\nenabled = false\n"}, false}, + {"another option set", map[string]string{"etc/50-x.repo": "[example]\npriority=10\n"}, true}, + {"enabled again by a later file", map[string]string{ + "etc/50-x.repo": "[example]\nenabled=0\n", + "etc/60-x.repo": "[example]\nenabled=1\n", + }, true}, + {"later file name in another directory", map[string]string{ + "etc/40-x.repo": "[example]\nenabled=1\n", + "usr/50-x.repo": "[example]\nenabled=0\n", + }, false}, + {"not a repo file", map[string]string{"etc/50-x.conf": "[example]\nenabled=0\n"}, true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + for _, d := range []string{"repos", "usr", "etc"} { + require.NoError(t, os.Mkdir(filepath.Join(dir, d), 0o700)) + } + require.NoError(t, os.WriteFile(filepath.Join(dir, "repos", "example.repo"), []byte(repoFile), 0o600)) + for name, content := range c.overrides { + require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) + } + patterns := []string{filepath.Join(dir, "repos", "*.repo")} + overrides := []string{filepath.Join(dir, "usr", "*.repo"), filepath.Join(dir, "etc", "*.repo")} + assert.Equal(t, c.want, anyFileEnablesRepo(patterns, overrides, "repo.example.com")) + }) + } } func TestEnablesRepo(t *testing.T) { From 7580239e49e8106013360256a95a6981cb5ad617 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 12:02:04 +0000 Subject: [PATCH 07/14] fix(update): mask DNF 5 override files of the same name DNF 5 reads only the /etc/dnf/repos.override.d file when a file of the same name exists in /usr/share/dnf5/repos.override.d. Both were read, so a repository disabled in a masked file counted as disabled. Co-Authored-By: Claude Fable 5.2 --- internal/install.go | 15 ++++++++------- internal/install_test.go | 4 ++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/internal/install.go b/internal/install.go index 8748d94e..0fb9cb54 100644 --- a/internal/install.go +++ b/internal/install.go @@ -2,6 +2,7 @@ package internal import ( "context" + "maps" "os" "os/exec" "path" @@ -194,18 +195,18 @@ func anyFileEnablesRepo(patterns, overridePatterns []string, repo string) bool { } // readOverrides reads the files matching the glob patterns, ordered by file name as DNF applies them. +// A file masks those of the same name that match an earlier pattern. func readOverrides(patterns []string) [][]byte { - var paths []string + paths := map[string]string{} for _, pattern := range patterns { matches, _ := filepath.Glob(pattern) - paths = append(paths, matches...) + for _, path := range matches { + paths[filepath.Base(path)] = path + } } - slices.SortStableFunc(paths, func(a, b string) int { - return strings.Compare(filepath.Base(a), filepath.Base(b)) - }) var contents [][]byte - for _, path := range paths { - if b, err := os.ReadFile(path); err == nil { + for _, name := range slices.Sorted(maps.Keys(paths)) { + if b, err := os.ReadFile(paths[name]); err == nil { contents = append(contents, b) } } diff --git a/internal/install_test.go b/internal/install_test.go index d15617c7..09fbf044 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -264,6 +264,10 @@ func TestAnyFileEnablesRepoWithOverrides(t *testing.T) { "etc/40-x.repo": "[example]\nenabled=1\n", "usr/50-x.repo": "[example]\nenabled=0\n", }, false}, + {"masked by a file of the same name", map[string]string{ + "usr/50-x.repo": "[example]\nenabled=0\n", + "etc/50-x.repo": "[example]\npriority=10\n", + }, true}, {"not a repo file", map[string]string{"etc/50-x.conf": "[example]\nenabled=0\n"}, true}, } for _, c := range cases { From 71010e43d5e2c0df7f2a0120ff9bbc4643fedb17 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Mon, 16 Nov 2026 12:35:35 +0000 Subject: [PATCH 08/14] refactor(update): move update message and repository code to their own files The update message code moves from commands/root.go to commands/update_message.go. The closure that showed the message becomes a type, updateNotifier, with tests for: the message before or after the command's output, showing it once, quiet mode, and recording a version whose message was not printed. The parsing of package repository configuration moves from internal/install.go to internal/package_repo.go, with its tests. No change in behavior. Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 4 +- commands/root.go | 171 +------------- commands/update_message.go | 210 ++++++++++++++++++ .../{root_test.go => update_message_test.go} | 66 ++++++ internal/install.go | 132 ----------- internal/install_test.go | 91 -------- internal/package_repo.go | 140 ++++++++++++ internal/package_repo_test.go | 99 +++++++++ 8 files changed, 519 insertions(+), 394 deletions(-) create mode 100644 commands/update_message.go rename commands/{root_test.go => update_message_test.go} (66%) create mode 100644 internal/package_repo.go create mode 100644 internal/package_repo_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 79455ea1..7a918869 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -205,9 +205,9 @@ PHP version is still injected via ldflags: ### Update Checks -The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. +The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). The notice is printed by `commands/update_message.go`. When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. -Install-method detection (`internal/install.go`) tailors the notice: +Install-method detection (`internal/install.go`, and `internal/package_repo.go` for package repositories) tailors the notice: - System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager's configuration does not enable `Wrapper.PackageRepository` (e.g. a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. - Homebrew, Scoop, npm, winget, and the bash installer also get a tailored upgrade command, built from config fields (`Wrapper.HomebrewTap`, `Wrapper.NpmPackage`, `Wrapper.WingetPackage`, `Wrapper.InstallerURL`, `Application.Executable`). - winget installs are detected by their path (`\WinGet\Packages\`). A release reaches winget only after Microsoft merges its manifest PR in `microsoft/winget-pkgs`, so for winget installs the background check reads the newest version there (from the GitHub API) instead of the latest GitHub release. diff --git a/commands/root.go b/commands/root.go index c7d59cf5..2d594b54 100644 --- a/commands/root.go +++ b/commands/root.go @@ -1,7 +1,6 @@ package commands import ( - "bytes" "context" "errors" "fmt" @@ -13,7 +12,6 @@ import ( "slices" "strings" "syscall" - "time" "github.com/fatih/color" "github.com/spf13/cobra" @@ -54,24 +52,6 @@ func isQuiet() bool { return viper.GetBool("quiet") && !viper.GetBool("debug") && !viper.GetBool("verbose") } -// updateCheckWait is the maximum time to wait for a background update check before exiting. -const updateCheckWait = time.Second - -var ( - // updateCheck is the background update check started by the root command, if any. - updateCheck *internal.UpdateCheck - // showUpdateMessage shows a pending update message, at most once. It is set by the root command. - showUpdateMessage func(atExit bool) -) - -// finishUpdateCheck gives a running update check a chance to save its result, -// and shows an update message if it found a new release. -func finishUpdateCheck() { - if updateCheck.Wait(updateCheckWait) && showUpdateMessage != nil { - showUpdateMessage(true) - } -} - func newRootCommand(cnf *config.Config) *cobra.Command { versionCommand := newVersionCommand(cnf) cmd := &cobra.Command{ @@ -107,35 +87,14 @@ func newRootCommand(cnf *config.Config) *cobra.Command { // The check runs in the background and caches its result. It is // waited for briefly before exiting. updateCheck = internal.StartUpdateCheck(cnf) - shown := false - showUpdateMessage = func(atExit bool) { - // In quiet mode the message would be discarded, so it is left for a later run. - if shown || quiet { - return - } - rel := internal.PendingNotification(cnf, config.Version) - if rel == nil { - return - } - shown = true - var msg bytes.Buffer - if printUpdateMessage(&msg, rel, cnf, internal.DetectInstallMethod(cnf)) { - // A blank line separates the message from the command's output. - if atExit { - fmt.Fprintf(cmd.ErrOrStderr(), "\n%s", msg.String()) - } else { - fmt.Fprintf(cmd.ErrOrStderr(), "%s\n", msg.String()) - } - } - internal.MarkNotified(cnf, rel.Version) - } + updateMessage = newUpdateNotifier(cnf, cmd.ErrOrStderr(), quiet) if viper.GetBool("version") { versionCommand.Run(cmd, []string{}) finishUpdateCheck() os.Exit(0) } // Show any update found by a previous run, before the command's output. - showUpdateMessage(false) + updateMessage.show(false) if alt.ShouldUpdate(cnf) { go func() { if err := alt.Update(cmd.Context(), cnf, debugLogf); err != nil { @@ -271,132 +230,6 @@ func checkShellConfigLeftovers(w io.Writer, cnf *config.Config) { } } -// printUpdateMessage describes the binary from its embedded config, as the -// binary and its upgrade command are the same with or without CLI_CONFIG_FILE. -// With CLI_CONFIG_FILE, it prints nothing if there is no upgrade command: the -// binary may be a private copy, which the generic instructions do not update. -// It reports whether it printed a message. -func printUpdateMessage( - w io.Writer, rel *internal.ReleaseInfo, cnf *config.Config, method internal.InstallMethod, -) bool { - if rel == nil { - return false - } - bin := cnf.Embedded() - exe, _ := os.Executable() - upgradeCmd := upgradeCommandFor(bin, method, exe) - if upgradeCmd == "" && !cnf.IsEmbedded() { - return false - } - - fmt.Fprintf(w, "%s %s → %s\n", - color.YellowString(fmt.Sprintf("A new release of the %s is available:", bin.Application.Name)), - color.CyanString(config.Version), - color.CyanString(rel.Version), - ) - - if upgradeCmd != "" { - fmt.Fprintf(w, "To upgrade, run: %s\n", color.YellowString(upgradeCmd)) - } else if bin.Wrapper.GitHubRepo != "" { - fmt.Fprintf( - w, - "To upgrade, follow the instructions at: https://github.com/%s#upgrade\n", - bin.Wrapper.GitHubRepo, - ) - } - - fmt.Fprintln(w, color.YellowString(rel.URL)) - return true -} - -// upgradeCommandFor returns the upgrade command for the install method, or an -// empty string when there is no tailored command (the caller then falls back to -// a generic link). -func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe string) string { - switch method { - case internal.InstallHomebrew: - if cnf.Wrapper.HomebrewTap != "" { - return "brew update && brew upgrade " + cnf.Wrapper.HomebrewTap - } - case internal.InstallScoop: - return "scoop update " + cnf.Application.Executable - case internal.InstallNpm: - if cnf.Wrapper.NpmPackage != "" { - return "npm install -g " + cnf.Wrapper.NpmPackage + "@latest" - } - case internal.InstallWinget: - if cnf.Wrapper.WingetPackage != "" { - return "winget upgrade " + cnf.Wrapper.WingetPackage - } - case internal.InstallApt, internal.InstallDnf, internal.InstallYum, internal.InstallApk: - if pkg := cnf.Wrapper.PackageName; pkg != "" { - return packageUpgradeCommand(method, pkg, privilegeCommand(geteuid() == 0, lookPath)) - } - case internal.InstallScript: - // The raw method replaces the binary in INSTALL_DIR; without it, the - // installer may choose a package manager instead (e.g. apt on Debian). - if cnf.Wrapper.InstallerURL != "" && exe != "" { - return "curl -fsSL " + cnf.Wrapper.InstallerURL + - " | INSTALL_METHOD=raw INSTALL_DIR=" + shellQuote(filepath.Dir(exe)) + " sh" - } - } - return "" -} - -// geteuid and lookPath can be replaced in tests. -var ( - geteuid = os.Geteuid - lookPath = exec.LookPath -) - -// privilegeCommand returns the command to run another as root: none for root, -// doas if it is installed and sudo is not (e.g. on Alpine), or else sudo. -func privilegeCommand(root bool, lookPath func(string) (string, error)) string { - if root { - return "" - } - if _, err := lookPath("sudo"); err != nil { - if _, err := lookPath("doas"); err == nil { - return "doas" - } - } - return "sudo" -} - -// packageUpgradeCommand returns the command to refresh a system package -// manager's index and upgrade a package, running each part with the privilege -// command, if any. -func packageUpgradeCommand(method internal.InstallMethod, pkg, privilege string) string { - var cmds []string - switch method { - case internal.InstallApt: - cmds = []string{"apt update", "apt install --only-upgrade " + pkg} - case internal.InstallDnf: - cmds = []string{"dnf upgrade --refresh " + pkg} - case internal.InstallYum: - // Without this, yum uses its cached metadata for hours. - cmds = []string{"yum clean expire-cache", "yum upgrade " + pkg} - case internal.InstallApk: - cmds = []string{"apk add --upgrade --update-cache " + pkg} - } - if privilege != "" { - for i := range cmds { - cmds[i] = privilege + " " + cmds[i] - } - } - return strings.Join(cmds, " && ") -} - -var shellSafe = regexp.MustCompile(`^[A-Za-z0-9_./-]+$`) - -// shellQuote quotes s for a POSIX shell, if needed. -func shellQuote(s string) string { - if shellSafe.MatchString(s) { - return s - } - return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" -} - func debugLogf(format string, v ...any) { if !viper.GetBool("debug") { return diff --git a/commands/update_message.go b/commands/update_message.go new file mode 100644 index 00000000..0a618949 --- /dev/null +++ b/commands/update_message.go @@ -0,0 +1,210 @@ +package commands + +import ( + "bytes" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/fatih/color" + + "github.com/upsun/cli/internal" + "github.com/upsun/cli/internal/config" +) + +// updateCheckWait is the maximum time to wait for a background update check before exiting. +const updateCheckWait = time.Second + +var ( + // updateCheck is the background update check started by the root command, if any. + updateCheck *internal.UpdateCheck + // updateMessage shows a pending update message. It is set by the root command. + updateMessage *updateNotifier +) + +// finishUpdateCheck gives a running update check a chance to save its result, +// and shows an update message if it found a new release. +func finishUpdateCheck() { + if updateCheck.Wait(updateCheckWait) { + updateMessage.show(true) + } +} + +// updateNotifier shows a pending update message, at most once. +type updateNotifier struct { + cnf *config.Config + w io.Writer + quiet bool + shown bool + + // These can be replaced in tests. + pending func() *internal.ReleaseInfo + method func() internal.InstallMethod + mark func(version string) +} + +func newUpdateNotifier(cnf *config.Config, w io.Writer, quiet bool) *updateNotifier { + return &updateNotifier{ + cnf: cnf, + w: w, + quiet: quiet, + pending: func() *internal.ReleaseInfo { return internal.PendingNotification(cnf, config.Version) }, + method: func() internal.InstallMethod { return internal.DetectInstallMethod(cnf) }, + mark: func(version string) { internal.MarkNotified(cnf, version) }, + } +} + +// show prints the update message, if one is pending, before the command's +// output or (atExit) after it. +func (n *updateNotifier) show(atExit bool) { + // In quiet mode the message would be discarded, so it is left for a later run. + if n == nil || n.shown || n.quiet { + return + } + rel := n.pending() + if rel == nil { + return + } + n.shown = true + var msg bytes.Buffer + if printUpdateMessage(&msg, rel, n.cnf, n.method()) { + // A blank line separates the message from the command's output. + if atExit { + fmt.Fprintf(n.w, "\n%s", msg.String()) + } else { + fmt.Fprintf(n.w, "%s\n", msg.String()) + } + } + n.mark(rel.Version) +} + +// printUpdateMessage describes the binary from its embedded config, as the +// binary and its upgrade command are the same with or without CLI_CONFIG_FILE. +// With CLI_CONFIG_FILE, it prints nothing if there is no upgrade command: the +// binary may be a private copy, which the generic instructions do not update. +// It reports whether it printed a message. +func printUpdateMessage( + w io.Writer, rel *internal.ReleaseInfo, cnf *config.Config, method internal.InstallMethod, +) bool { + if rel == nil { + return false + } + bin := cnf.Embedded() + exe, _ := os.Executable() + upgradeCmd := upgradeCommandFor(bin, method, exe) + if upgradeCmd == "" && !cnf.IsEmbedded() { + return false + } + + fmt.Fprintf(w, "%s %s → %s\n", + color.YellowString(fmt.Sprintf("A new release of the %s is available:", bin.Application.Name)), + color.CyanString(config.Version), + color.CyanString(rel.Version), + ) + + if upgradeCmd != "" { + fmt.Fprintf(w, "To upgrade, run: %s\n", color.YellowString(upgradeCmd)) + } else if bin.Wrapper.GitHubRepo != "" { + fmt.Fprintf( + w, + "To upgrade, follow the instructions at: https://github.com/%s#upgrade\n", + bin.Wrapper.GitHubRepo, + ) + } + + fmt.Fprintln(w, color.YellowString(rel.URL)) + return true +} + +// upgradeCommandFor returns the upgrade command for the install method, or an +// empty string when there is no tailored command (the caller then falls back to +// a generic link). +func upgradeCommandFor(cnf *config.Config, method internal.InstallMethod, exe string) string { + switch method { + case internal.InstallHomebrew: + if cnf.Wrapper.HomebrewTap != "" { + return "brew update && brew upgrade " + cnf.Wrapper.HomebrewTap + } + case internal.InstallScoop: + return "scoop update " + cnf.Application.Executable + case internal.InstallNpm: + if cnf.Wrapper.NpmPackage != "" { + return "npm install -g " + cnf.Wrapper.NpmPackage + "@latest" + } + case internal.InstallWinget: + if cnf.Wrapper.WingetPackage != "" { + return "winget upgrade " + cnf.Wrapper.WingetPackage + } + case internal.InstallApt, internal.InstallDnf, internal.InstallYum, internal.InstallApk: + if pkg := cnf.Wrapper.PackageName; pkg != "" { + return packageUpgradeCommand(method, pkg, privilegeCommand(geteuid() == 0, lookPath)) + } + case internal.InstallScript: + // The raw method replaces the binary in INSTALL_DIR; without it, the + // installer may choose a package manager instead (e.g. apt on Debian). + if cnf.Wrapper.InstallerURL != "" && exe != "" { + return "curl -fsSL " + cnf.Wrapper.InstallerURL + + " | INSTALL_METHOD=raw INSTALL_DIR=" + shellQuote(filepath.Dir(exe)) + " sh" + } + } + return "" +} + +// geteuid and lookPath can be replaced in tests. +var ( + geteuid = os.Geteuid + lookPath = exec.LookPath +) + +// privilegeCommand returns the command to run another as root: none for root, +// doas if it is installed and sudo is not (e.g. on Alpine), or else sudo. +func privilegeCommand(root bool, lookPath func(string) (string, error)) string { + if root { + return "" + } + if _, err := lookPath("sudo"); err != nil { + if _, err := lookPath("doas"); err == nil { + return "doas" + } + } + return "sudo" +} + +// packageUpgradeCommand returns the command to refresh a system package +// manager's index and upgrade a package, running each part with the privilege +// command, if any. +func packageUpgradeCommand(method internal.InstallMethod, pkg, privilege string) string { + var cmds []string + switch method { + case internal.InstallApt: + cmds = []string{"apt update", "apt install --only-upgrade " + pkg} + case internal.InstallDnf: + cmds = []string{"dnf upgrade --refresh " + pkg} + case internal.InstallYum: + // Without this, yum uses its cached metadata for hours. + cmds = []string{"yum clean expire-cache", "yum upgrade " + pkg} + case internal.InstallApk: + cmds = []string{"apk add --upgrade --update-cache " + pkg} + } + if privilege != "" { + for i := range cmds { + cmds[i] = privilege + " " + cmds[i] + } + } + return strings.Join(cmds, " && ") +} + +var shellSafe = regexp.MustCompile(`^[A-Za-z0-9_./-]+$`) + +// shellQuote quotes s for a POSIX shell, if needed. +func shellQuote(s string) string { + if shellSafe.MatchString(s) { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} diff --git a/commands/root_test.go b/commands/update_message_test.go similarity index 66% rename from commands/root_test.go rename to commands/update_message_test.go index da117648..4a903ad6 100644 --- a/commands/root_test.go +++ b/commands/update_message_test.go @@ -4,6 +4,7 @@ import ( "bytes" "os/exec" "slices" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -130,3 +131,68 @@ func TestPrintUpdateMessageUnknownMethod(t *testing.T) { internal.InstallUnknown) assert.Contains(t, buf.String(), "https://github.com/"+cnf.Wrapper.GitHubRepo+"#upgrade") } + +func TestUpdateNotifier(t *testing.T) { + t.Setenv("CLI_CONFIG_FILE", "") + b, err := config.LoadYAML() + require.NoError(t, err) + embedded, err := config.FromYAML(b) + require.NoError(t, err) + // An alt CLI shows no message when there is no upgrade command. + altCnf := testConfig() + + rel := &internal.ReleaseInfo{Version: "v9.9.9", URL: "https://example.com/release"} + const firstLine = "A new release of the " + + cases := []struct { + name string + cnf *config.Config + quiet bool + pending []*internal.ReleaseInfo // the result for each call to show + atExit bool + wantPrefix string + wantSuffix string + wantMarked []string + }{ + {name: "at start", cnf: embedded, pending: []*internal.ReleaseInfo{rel}, + wantPrefix: firstLine, wantSuffix: rel.URL + "\n\n", wantMarked: []string{"v9.9.9"}}, + {name: "at exit", cnf: embedded, pending: []*internal.ReleaseInfo{rel}, atExit: true, + wantPrefix: "\n" + firstLine, wantSuffix: rel.URL + "\n", wantMarked: []string{"v9.9.9"}}, + {name: "shown once", cnf: embedded, pending: []*internal.ReleaseInfo{rel, rel}, + wantPrefix: firstLine, wantSuffix: rel.URL + "\n\n", wantMarked: []string{"v9.9.9"}}, + {name: "found by a later call", cnf: embedded, pending: []*internal.ReleaseInfo{nil, rel}, atExit: true, + wantPrefix: "\n" + firstLine, wantSuffix: rel.URL + "\n", wantMarked: []string{"v9.9.9"}}, + {name: "nothing pending", cnf: embedded, pending: []*internal.ReleaseInfo{nil}}, + {name: "quiet", cnf: embedded, quiet: true, pending: []*internal.ReleaseInfo{rel}}, + {name: "no message to print", cnf: altCnf, pending: []*internal.ReleaseInfo{rel}, + wantMarked: []string{"v9.9.9"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var ( + out bytes.Buffer + marked []string + calls int + ) + n := newUpdateNotifier(c.cnf, &out, c.quiet) + n.pending = func() *internal.ReleaseInfo { calls++; return c.pending[calls-1] } + n.method = func() internal.InstallMethod { return internal.InstallUnknown } + n.mark = func(v string) { marked = append(marked, v) } + for range c.pending { + n.show(c.atExit) + } + assert.Equal(t, c.wantMarked, marked) + if c.wantPrefix == "" { + assert.Empty(t, out.String()) + return + } + assert.True(t, strings.HasPrefix(out.String(), c.wantPrefix), out.String()) + assert.True(t, strings.HasSuffix(out.String(), c.wantSuffix), out.String()) + assert.Equal(t, 1, strings.Count(out.String(), firstLine)) + }) + } + + // A nil notifier (no root command run) does nothing. + var none *updateNotifier + none.show(true) +} diff --git a/internal/install.go b/internal/install.go index 0fb9cb54..5623738b 100644 --- a/internal/install.go +++ b/internal/install.go @@ -2,14 +2,11 @@ package internal import ( "context" - "maps" "os" "os/exec" "path" "path/filepath" - "regexp" "runtime" - "slices" "strings" "sync" "time" @@ -150,135 +147,6 @@ func (p *installProbe) packageMethod() InstallMethod { return m } -// packageRepoFiles lists the files (as glob patterns) that configure each package manager's repositories. -var packageRepoFiles = map[InstallMethod][]string{ - InstallApt: {"/etc/apt/sources.list", "/etc/apt/sources.list.d/*.list", "/etc/apt/sources.list.d/*.sources"}, - InstallDnf: {"/etc/yum.repos.d/*.repo"}, - InstallYum: {"/etc/yum.repos.d/*.repo"}, - InstallApk: {"/etc/apk/repositories", "/etc/apk/repositories.d/*.list"}, -} - -// dnfOverrideFiles lists the files (as glob patterns) that override repository settings in DNF 5. -var dnfOverrideFiles = []string{"/usr/share/dnf5/repos.override.d/*.repo", "/etc/dnf/repos.override.d/*.repo"} - -// packageRepositoryInUse reports whether a package manager's configuration enables the repository. -func packageRepositoryInUse(m InstallMethod, repo string) bool { - var overrides []string - if m == InstallDnf { - overrides = dnfOverrideFiles - } - return anyFileEnablesRepo(packageRepoFiles[m], overrides, repo) -} - -// anyFileEnablesRepo reports whether a file matching one of the glob patterns -// enables the repository, and no file matching the override patterns disables it. -func anyFileEnablesRepo(patterns, overridePatterns []string, repo string) bool { - overrides := readOverrides(overridePatterns) - for _, pattern := range patterns { - paths, _ := filepath.Glob(pattern) - for _, path := range paths { - b, err := os.ReadFile(path) - if err != nil || !enablesRepo(b, repo) { - continue - } - if len(overrides) == 0 { - return true - } - for _, id := range repoSections(b, repo) { - if !disabledByOverride(id, overrides) { - return true - } - } - } - } - return false -} - -// readOverrides reads the files matching the glob patterns, ordered by file name as DNF applies them. -// A file masks those of the same name that match an earlier pattern. -func readOverrides(patterns []string) [][]byte { - paths := map[string]string{} - for _, pattern := range patterns { - matches, _ := filepath.Glob(pattern) - for _, path := range matches { - paths[filepath.Base(path)] = path - } - } - var contents [][]byte - for _, name := range slices.Sorted(maps.Keys(paths)) { - if b, err := os.ReadFile(paths[name]); err == nil { - contents = append(contents, b) - } - } - return contents -} - -// sectionName returns the name of an INI section header line, e.g. "[name]". -func sectionName(line string) (string, bool) { - if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { - return strings.TrimSpace(line[1 : len(line)-1]), true - } - return "", false -} - -// repoSections returns the names of the sections of a yum repo file that mention the repository. -func repoSections(content []byte, repo string) []string { - var ids []string - section := "" - for line := range strings.Lines(string(content)) { - line = strings.TrimSpace(line) - if name, ok := sectionName(line); ok { - section = name - } else if section != "" && !strings.HasPrefix(line, "#") && strings.Contains(line, repo) { - ids = append(ids, section) - section = "" - } - } - return ids -} - -// enabledSetting matches a line that enables or disables a repository. -var enabledSetting = regexp.MustCompile(`(?i)^enabled\s*[=:]`) - -// disabledByOverride reports whether the override files disable a repository. -// Their section names may be glob patterns, and the last setting applies. -func disabledByOverride(id string, overrides [][]byte) bool { - disabled := false - for _, content := range overrides { - applies := false - for line := range strings.Lines(string(content)) { - line = strings.TrimSpace(line) - if name, ok := sectionName(line); ok { - applies, _ = path.Match(name, id) - } else if applies && enabledSetting.MatchString(line) { - disabled = repoDisabled.MatchString(line) - } - } - } - return disabled -} - -// repoDisabled matches a line that disables a repository, in a yum repo file or a deb822 sources file. -var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false|off|disable|without)$`) - -// enablesRepo reports whether a repository configuration file mentions the -// repository outside comments. A file that disables any repository does not -// count, as it is not parsed to find out which one. -func enablesRepo(content []byte, repo string) bool { - found := false - for line := range strings.Lines(string(content)) { - line = strings.TrimSpace(line) - switch { - case strings.HasPrefix(line, "#"): - case repoDisabled.MatchString(line): - return false - case strings.Contains(line, repo): - found = true - } - } - return found -} - // overrideMethod reads a forced install method from the environment or config. func overrideMethod(envPrefix, configMethod string, getenv func(string) string) (InstallMethod, bool) { if v := getenv(envPrefix + "INSTALL_METHOD"); v != "" { diff --git a/internal/install_test.go b/internal/install_test.go index 09fbf044..1fb86566 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -1,10 +1,8 @@ package internal import ( - "os" "os/exec" "path" - "path/filepath" "slices" "testing" @@ -225,95 +223,6 @@ func TestDetectInstallMethod(t *testing.T) { } } -func TestAnyFileEnablesRepo(t *testing.T) { - dir := t.TempDir() - write := func(name, content string) { - require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) - } - write("other.list", "deb http://deb.example.org stable main\n") - write("example.list", "deb https://repo.example.com/debian stable main\n") - write("example.list.distUpgrade", "deb https://backup.example.com/debian stable main\n") - - patterns := []string{filepath.Join(dir, "other.list"), filepath.Join(dir, "*.list")} - assert.True(t, anyFileEnablesRepo(patterns, nil, "repo.example.com")) - assert.False(t, anyFileEnablesRepo(patterns, nil, "other.example.com")) - assert.False(t, anyFileEnablesRepo(patterns, nil, "backup.example.com")) - assert.False(t, anyFileEnablesRepo(patterns[:1], nil, "repo.example.com")) - assert.False(t, anyFileEnablesRepo(nil, nil, "repo.example.com")) -} - -func TestAnyFileEnablesRepoWithOverrides(t *testing.T) { - const repoFile = "[other]\nbaseurl=https://rpm.example.org/\n\n" + - "[example]\nname=Example\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\n" - cases := []struct { - name string - // Override files by path, relative to a temporary directory. - overrides map[string]string - want bool - }{ - {"no overrides", nil, true}, - {"disabled", map[string]string{"etc/99-config_manager.repo": "# Generated.\n[example]\nenabled=0\n"}, false}, - {"another repository disabled", map[string]string{"etc/99-config_manager.repo": "[other]\nenabled=0\n"}, true}, - {"disabled by a glob pattern", map[string]string{"etc/50-all.repo": "[exam*]\nenabled = false\n"}, false}, - {"another option set", map[string]string{"etc/50-x.repo": "[example]\npriority=10\n"}, true}, - {"enabled again by a later file", map[string]string{ - "etc/50-x.repo": "[example]\nenabled=0\n", - "etc/60-x.repo": "[example]\nenabled=1\n", - }, true}, - {"later file name in another directory", map[string]string{ - "etc/40-x.repo": "[example]\nenabled=1\n", - "usr/50-x.repo": "[example]\nenabled=0\n", - }, false}, - {"masked by a file of the same name", map[string]string{ - "usr/50-x.repo": "[example]\nenabled=0\n", - "etc/50-x.repo": "[example]\npriority=10\n", - }, true}, - {"not a repo file", map[string]string{"etc/50-x.conf": "[example]\nenabled=0\n"}, true}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - dir := t.TempDir() - for _, d := range []string{"repos", "usr", "etc"} { - require.NoError(t, os.Mkdir(filepath.Join(dir, d), 0o700)) - } - require.NoError(t, os.WriteFile(filepath.Join(dir, "repos", "example.repo"), []byte(repoFile), 0o600)) - for name, content := range c.overrides { - require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) - } - patterns := []string{filepath.Join(dir, "repos", "*.repo")} - overrides := []string{filepath.Join(dir, "usr", "*.repo"), filepath.Join(dir, "etc", "*.repo")} - assert.Equal(t, c.want, anyFileEnablesRepo(patterns, overrides, "repo.example.com")) - }) - } -} - -func TestEnablesRepo(t *testing.T) { - cases := []struct { - name string - content string - want bool - }{ - {"apt list", "deb [signed-by=/k.asc] https://repo.example.com/debian stable main\n", true}, - {"apt list disabled by a release upgrade", "# deb https://repo.example.com/debian stable main # disabled\n", false}, - {"deb822", "Types: deb\nURIs: https://repo.example.com/debian\nSuites: stable\n", true}, - {"deb822 disabled", "Types: deb\nURIs: https://repo.example.com/debian\nEnabled: no\n", false}, - {"yum", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\ngpgcheck=1\n", true}, - {"yum disabled", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled = 0\n", false}, - {"yum disabled with off", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=off\n", false}, - {"deb822 disabled with disable", "URIs: https://repo.example.com/debian\nEnabled: disable\n", false}, - {"deb822 disabled with without", "URIs: https://repo.example.com/debian\nEnabled: without\n", false}, - {"apk", "https://dl-cdn.example.org/alpine/main\nhttps://repo.example.com/alpine\n", true}, - {"apk commented out", "https://dl-cdn.example.org/alpine/main\n #https://repo.example.com/alpine\n", false}, - {"another repository", "deb http://deb.example.org stable main\n", false}, - {"empty", "", false}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - assert.Equal(t, c.want, enablesRepo([]byte(c.content), "repo.example.com")) - }) - } -} - func TestRPMFrontend(t *testing.T) { has := func(names ...string) func(string) (string, error) { return func(name string) (string, error) { diff --git a/internal/package_repo.go b/internal/package_repo.go new file mode 100644 index 00000000..971e8f1d --- /dev/null +++ b/internal/package_repo.go @@ -0,0 +1,140 @@ +package internal + +import ( + "maps" + "os" + "path" + "path/filepath" + "regexp" + "slices" + "strings" +) + +// packageRepoFiles lists the files (as glob patterns) that configure each package manager's repositories. +var packageRepoFiles = map[InstallMethod][]string{ + InstallApt: {"/etc/apt/sources.list", "/etc/apt/sources.list.d/*.list", "/etc/apt/sources.list.d/*.sources"}, + InstallDnf: {"/etc/yum.repos.d/*.repo"}, + InstallYum: {"/etc/yum.repos.d/*.repo"}, + InstallApk: {"/etc/apk/repositories", "/etc/apk/repositories.d/*.list"}, +} + +// dnfOverrideFiles lists the files (as glob patterns) that override repository settings in DNF 5. +var dnfOverrideFiles = []string{"/usr/share/dnf5/repos.override.d/*.repo", "/etc/dnf/repos.override.d/*.repo"} + +// packageRepositoryInUse reports whether a package manager's configuration enables the repository. +func packageRepositoryInUse(m InstallMethod, repo string) bool { + var overrides []string + if m == InstallDnf { + overrides = dnfOverrideFiles + } + return anyFileEnablesRepo(packageRepoFiles[m], overrides, repo) +} + +// anyFileEnablesRepo reports whether a file matching one of the glob patterns +// enables the repository, and no file matching the override patterns disables it. +func anyFileEnablesRepo(patterns, overridePatterns []string, repo string) bool { + overrides := readOverrides(overridePatterns) + for _, pattern := range patterns { + paths, _ := filepath.Glob(pattern) + for _, path := range paths { + b, err := os.ReadFile(path) + if err != nil || !enablesRepo(b, repo) { + continue + } + if len(overrides) == 0 { + return true + } + for _, id := range repoSections(b, repo) { + if !disabledByOverride(id, overrides) { + return true + } + } + } + } + return false +} + +// readOverrides reads the files matching the glob patterns, ordered by file name as DNF applies them. +// A file masks those of the same name that match an earlier pattern. +func readOverrides(patterns []string) [][]byte { + paths := map[string]string{} + for _, pattern := range patterns { + matches, _ := filepath.Glob(pattern) + for _, path := range matches { + paths[filepath.Base(path)] = path + } + } + var contents [][]byte + for _, name := range slices.Sorted(maps.Keys(paths)) { + if b, err := os.ReadFile(paths[name]); err == nil { + contents = append(contents, b) + } + } + return contents +} + +// sectionName returns the name of an INI section header line, e.g. "[name]". +func sectionName(line string) (string, bool) { + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + return strings.TrimSpace(line[1 : len(line)-1]), true + } + return "", false +} + +// repoSections returns the names of the sections of a yum repo file that mention the repository. +func repoSections(content []byte, repo string) []string { + var ids []string + section := "" + for line := range strings.Lines(string(content)) { + line = strings.TrimSpace(line) + if name, ok := sectionName(line); ok { + section = name + } else if section != "" && !strings.HasPrefix(line, "#") && strings.Contains(line, repo) { + ids = append(ids, section) + section = "" + } + } + return ids +} + +// enabledSetting matches a line that enables or disables a repository. +var enabledSetting = regexp.MustCompile(`(?i)^enabled\s*[=:]`) + +// disabledByOverride reports whether the override files disable a repository. +// Their section names may be glob patterns, and the last setting applies. +func disabledByOverride(id string, overrides [][]byte) bool { + disabled := false + for _, content := range overrides { + applies := false + for line := range strings.Lines(string(content)) { + line = strings.TrimSpace(line) + if name, ok := sectionName(line); ok { + applies, _ = path.Match(name, id) + } else if applies && enabledSetting.MatchString(line) { + disabled = repoDisabled.MatchString(line) + } + } + } + return disabled +} + +// repoDisabled matches a line that disables a repository, in a yum repo file or a deb822 sources file. +var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false|off|disable|without)$`) + +// enablesRepo reports whether a repository configuration file mentions the +// repository outside comments. A file that disables any repository does not +// count, as it is not parsed to find out which one. +func enablesRepo(content []byte, repo string) bool { + found := false + for line := range strings.Lines(string(content)) { + line = strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "#"): + case repoDisabled.MatchString(line): + return false + case strings.Contains(line, repo): + found = true + } + } + return found +} diff --git a/internal/package_repo_test.go b/internal/package_repo_test.go new file mode 100644 index 00000000..717d9704 --- /dev/null +++ b/internal/package_repo_test.go @@ -0,0 +1,99 @@ +package internal + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAnyFileEnablesRepo(t *testing.T) { + dir := t.TempDir() + write := func(name, content string) { + require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) + } + write("other.list", "deb http://deb.example.org stable main\n") + write("example.list", "deb https://repo.example.com/debian stable main\n") + write("example.list.distUpgrade", "deb https://backup.example.com/debian stable main\n") + + patterns := []string{filepath.Join(dir, "other.list"), filepath.Join(dir, "*.list")} + assert.True(t, anyFileEnablesRepo(patterns, nil, "repo.example.com")) + assert.False(t, anyFileEnablesRepo(patterns, nil, "other.example.com")) + assert.False(t, anyFileEnablesRepo(patterns, nil, "backup.example.com")) + assert.False(t, anyFileEnablesRepo(patterns[:1], nil, "repo.example.com")) + assert.False(t, anyFileEnablesRepo(nil, nil, "repo.example.com")) +} + +func TestAnyFileEnablesRepoWithOverrides(t *testing.T) { + const repoFile = "[other]\nbaseurl=https://rpm.example.org/\n\n" + + "[example]\nname=Example\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\n" + cases := []struct { + name string + // Override files by path, relative to a temporary directory. + overrides map[string]string + want bool + }{ + {"no overrides", nil, true}, + {"disabled", map[string]string{"etc/99-config_manager.repo": "# Generated.\n[example]\nenabled=0\n"}, false}, + {"another repository disabled", map[string]string{"etc/99-config_manager.repo": "[other]\nenabled=0\n"}, true}, + {"disabled by a glob pattern", map[string]string{"etc/50-all.repo": "[exam*]\nenabled = false\n"}, false}, + {"another option set", map[string]string{"etc/50-x.repo": "[example]\npriority=10\n"}, true}, + {"enabled again by a later file", map[string]string{ + "etc/50-x.repo": "[example]\nenabled=0\n", + "etc/60-x.repo": "[example]\nenabled=1\n", + }, true}, + {"later file name in another directory", map[string]string{ + "etc/40-x.repo": "[example]\nenabled=1\n", + "usr/50-x.repo": "[example]\nenabled=0\n", + }, false}, + {"masked by a file of the same name", map[string]string{ + "usr/50-x.repo": "[example]\nenabled=0\n", + "etc/50-x.repo": "[example]\npriority=10\n", + }, true}, + {"not a repo file", map[string]string{"etc/50-x.conf": "[example]\nenabled=0\n"}, true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + for _, d := range []string{"repos", "usr", "etc"} { + require.NoError(t, os.Mkdir(filepath.Join(dir, d), 0o700)) + } + require.NoError(t, os.WriteFile(filepath.Join(dir, "repos", "example.repo"), []byte(repoFile), 0o600)) + for name, content := range c.overrides { + require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) + } + patterns := []string{filepath.Join(dir, "repos", "*.repo")} + overrides := []string{filepath.Join(dir, "usr", "*.repo"), filepath.Join(dir, "etc", "*.repo")} + assert.Equal(t, c.want, anyFileEnablesRepo(patterns, overrides, "repo.example.com")) + }) + } +} + +func TestEnablesRepo(t *testing.T) { + cases := []struct { + name string + content string + want bool + }{ + {"apt list", "deb [signed-by=/k.asc] https://repo.example.com/debian stable main\n", true}, + {"apt list disabled by a release upgrade", "# deb https://repo.example.com/debian stable main # disabled\n", false}, + {"deb822", "Types: deb\nURIs: https://repo.example.com/debian\nSuites: stable\n", true}, + {"deb822 disabled", "Types: deb\nURIs: https://repo.example.com/debian\nEnabled: no\n", false}, + {"yum", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\ngpgcheck=1\n", true}, + {"yum disabled", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled = 0\n", false}, + {"yum disabled with off", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=off\n", false}, + {"deb822 disabled with disable", "URIs: https://repo.example.com/debian\nEnabled: disable\n", false}, + {"deb822 disabled with without", "URIs: https://repo.example.com/debian\nEnabled: without\n", false}, + {"apk", "https://dl-cdn.example.org/alpine/main\nhttps://repo.example.com/alpine\n", true}, + {"apk commented out", "https://dl-cdn.example.org/alpine/main\n #https://repo.example.com/alpine\n", false}, + {"another repository", "deb http://deb.example.org stable main\n", false}, + {"empty", "", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + assert.Equal(t, c.want, enablesRepo([]byte(c.content), "repo.example.com")) + }) + } +} From 48c064fd3191532e8c2af1d18dbd19a4f56b2d69 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Tue, 17 Nov 2026 10:10:59 +0000 Subject: [PATCH 09/14] test(update): cover the package ownership query Split owningPackageManager into packageOwner, which takes the command lookup and runner as arguments, and test its query order, the choice of dnf or yum for an RPM, and a timeout counting as owned. Co-Authored-By: Claude Fable 5.2 --- internal/install.go | 22 +++++++++++---- internal/install_test.go | 59 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 5 deletions(-) diff --git a/internal/install.go b/internal/install.go index 5623738b..3fb256f1 100644 --- a/internal/install.go +++ b/internal/install.go @@ -259,11 +259,23 @@ func fileExists(p string) bool { // owningPackageManager asks the system package databases which one owns exe, // and returns its install method, or InstallUnknown if none does. A time limit -// stops a slow database from delaying the command; a timeout counts as owned -// (InstallPackage), so that the installer script is not suggested. +// stops a slow database from delaying the command. func owningPackageManager(exe string) InstallMethod { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() + return packageOwner(ctx, exe, exec.LookPath, func(ctx context.Context, name string, args ...string) error { + return exec.CommandContext(ctx, name, args...).Run() + }) +} + +// packageOwner runs each installed package manager's ownership query for exe, +// until one succeeds. If ctx ends first, exe counts as owned (InstallPackage), +// so that the installer script is not suggested. +func packageOwner( + ctx context.Context, exe string, + lookPath func(string) (string, error), + run func(ctx context.Context, name string, args ...string) error, +) InstallMethod { queries := []struct { method InstallMethod args []string @@ -273,11 +285,11 @@ func owningPackageManager(exe string) InstallMethod { {InstallApk, []string{"apk", "info", "--who-owns", exe}}, } for _, q := range queries { - p, err := exec.LookPath(q.args[0]) + p, err := lookPath(q.args[0]) if err != nil { continue } - err = exec.CommandContext(ctx, p, q.args[1:]...).Run() + err = run(ctx, p, q.args[1:]...) if ctx.Err() != nil { return InstallPackage } @@ -285,7 +297,7 @@ func owningPackageManager(exe string) InstallMethod { continue } if q.method == InstallDnf { - return rpmFrontend(exec.LookPath) + return rpmFrontend(lookPath) } return q.method } diff --git a/internal/install_test.go b/internal/install_test.go index 1fb86566..5b577396 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -1,9 +1,12 @@ package internal import ( + "context" + "errors" "os/exec" "path" "slices" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -223,6 +226,62 @@ func TestDetectInstallMethod(t *testing.T) { } } +func TestPackageOwner(t *testing.T) { + const exe = "/usr/bin/example" + cases := []struct { + name string + installed []string + owner string // the query command that reports exe as owned + timeout string // the query command that outlasts the time limit + want InstallMethod + wantRun []string + }{ + {name: "no package managers", want: InstallUnknown}, + {name: "dpkg", installed: []string{"dpkg-query", "rpm"}, owner: "dpkg-query", want: InstallApt, + wantRun: []string{"/bin/dpkg-query -S " + exe}}, + {name: "rpm with dnf", installed: []string{"dpkg-query", "rpm", "dnf", "yum"}, owner: "rpm", want: InstallDnf, + wantRun: []string{"/bin/dpkg-query -S " + exe, "/bin/rpm -qf " + exe}}, + {name: "rpm with yum", installed: []string{"rpm", "yum"}, owner: "rpm", want: InstallYum, + wantRun: []string{"/bin/rpm -qf " + exe}}, + {name: "rpm without a frontend", installed: []string{"rpm"}, owner: "rpm", want: InstallPackage, + wantRun: []string{"/bin/rpm -qf " + exe}}, + {name: "apk", installed: []string{"apk"}, owner: "apk", want: InstallApk, + wantRun: []string{"/bin/apk info --who-owns " + exe}}, + {name: "not owned", installed: []string{"dpkg-query", "rpm", "apk"}, want: InstallUnknown, + wantRun: []string{"/bin/dpkg-query -S " + exe, "/bin/rpm -qf " + exe, "/bin/apk info --who-owns " + exe}}, + {name: "owner not installed", installed: []string{"apk"}, owner: "rpm", want: InstallUnknown, + wantRun: []string{"/bin/apk info --who-owns " + exe}}, + {name: "timeout", installed: []string{"dpkg-query", "rpm"}, owner: "rpm", timeout: "dpkg-query", + want: InstallPackage, wantRun: []string{"/bin/dpkg-query -S " + exe}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + lookPath := func(name string) (string, error) { + if slices.Contains(c.installed, name) { + return "/bin/" + name, nil + } + return "", exec.ErrNotFound + } + var ran []string + run := func(_ context.Context, name string, args ...string) error { + ran = append(ran, name+" "+strings.Join(args, " ")) + switch path.Base(name) { + case c.timeout: + cancel() + return context.Canceled + case c.owner: + return nil + } + return errors.New("exit status 1") + } + assert.Equal(t, c.want, packageOwner(ctx, exe, lookPath, run)) + assert.Equal(t, c.wantRun, ran) + }) + } +} + func TestRPMFrontend(t *testing.T) { has := func(names ...string) func(string) (string, error) { return func(name string) (string, error) { From c7042c0236843e041beb7a883007e65a7d3f6d02 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Wed, 18 Nov 2026 23:48:58 +0000 Subject: [PATCH 10/14] docs(update): correct the StartUpdateCheck comment The cached result is now also read in the same run, once the check has finished, not only in a later invocation. Co-Authored-By: Claude Fable 5.2 --- internal/update.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/update.go b/internal/update.go index 60b3e0cf..765cb1b7 100644 --- a/internal/update.go +++ b/internal/update.go @@ -33,7 +33,8 @@ type UpdateCheck struct { // StartUpdateCheck starts a background check for a newer release on GitHub, // if one is due. The result is cached in the state, for PendingNotification -// to read in a later invocation. It returns nil if no check was started. +// to read once the check has finished, or in a later invocation. It returns +// nil if no check was started. func StartUpdateCheck(cnf *config.Config) *UpdateCheck { if !shouldCheckForUpdate(cnf) { return nil From a942592daeb028b3efd3b08a35b0dde497713994 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Thu, 19 Nov 2026 18:28:09 +0000 Subject: [PATCH 11/14] feat(update): ask the package manager whether a repository provides the package Replace the scan of repository configuration files for the repository's host with the package manager's own queries, run without network access: - apt: `apt-cache policy` lists a source other than the dpkg status file - apk: `apk --no-network policy` lists a source other than the installed database - dnf: the installed package's `from_repo` is an enabled repository - yum: `yum info installed` has a `From repo` that is an enabled repository These use the package manager's parsing of its configuration, and dnf and yum record where the package came from. Any enabled repository that provides the package counts, so the `wrapper.package_repository` config key is removed. Without an index (apt lists, apk's cache), apt and apk do not list the repository, so the notice gets the generic link. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../update-message-install-detection.md | 20 +- internal/config/platformsh-cli.yaml | 1 - internal/config/schema.go | 6 +- internal/config/upsun-cli.yaml | 1 - internal/install.go | 16 +- internal/install_test.go | 16 +- internal/package_repo.go | 198 ++++++++---------- internal/package_repo_test.go | 190 ++++++++++------- 9 files changed, 238 insertions(+), 212 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index bc0e904b..7ef11cc1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -208,7 +208,7 @@ PHP version is still injected via ldflags: The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). The notice is printed by `commands/update_message.go`. When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. Install-method detection (`internal/install.go`, and `internal/package_repo.go` for package repositories) tailors the notice: -- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager's configuration does not enable `Wrapper.PackageRepository` (e.g. a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. +- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager does not report that an enabled repository provides the package (`apt-cache policy`, `apk --no-network policy`, dnf's `from_repo`, `yum info installed`; e.g. not for a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. - Homebrew, Scoop, npm, winget, and the bash installer also get a tailored upgrade command, built from config fields (`Wrapper.HomebrewTap`, `Wrapper.NpmPackage`, `Wrapper.WingetPackage`, `Wrapper.InstallerURL`, `Application.Executable`). - winget installs are detected by their path (`\WinGet\Packages\`). A release reaches winget only after Microsoft merges its manifest PR in `microsoft/winget-pkgs`, so for winget installs the background check reads the newest version there (from the GitHub API) instead of the latest GitHub release. - The notice is only shown in an interactive terminal, and at most once a week for the same version (`LastNotified` and `NotifiedVersion` in state): a newer version is announced without waiting. diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index 2ad80b3a..43e131b0 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -23,13 +23,19 @@ got a new release when they happened to upgrade. This revision changes that: package with an unknown package manager, which gets the generic link. - A downloaded package (installed with `dpkg -i`, `rpm -i` or `apk add --allow-untrusted`) cannot be upgraded with the package manager. So - the method is only `apt`, `dnf`, `yum` or `apk` if the package manager's - configuration (`/etc/apt/sources.list*`, `/etc/yum.repos.d/*.repo`, - `/etc/apk/repositories*`) mentions the repository's host, the new - `wrapper.package_repository` config key. Otherwise it is `package`. Comments - do not count, nor does a file that disables a repository (`enabled=0`, - `Enabled: no`). For dnf, a repository disabled in DNF 5's override files - (`repos.override.d`, written by `dnf config-manager`) does not count either. + the method is only `apt`, `dnf`, `yum` or `apk` if the package manager says + that an enabled repository provides the package. Otherwise it is `package`. + The queries run without network access, under a 2-second limit: + - apt: `apt-cache policy ` lists a source other than + `/var/lib/dpkg/status`. Without package lists (e.g. removed in a container + image), it does not. + - apk: `apk --no-network policy ` lists a source other than + `lib/apk/db/installed`. Without its index cache, it does not. + - dnf: `dnf -C repoquery --installed --qf '%{from_repo}'` names a repository + that `dnf -C repolist --enabled` lists. It is `` (dnf 5) or empty + (dnf 4) for `rpm -i`, and `@commandline` for `dnf install ./file.rpm`. + - yum: `yum -C info installed` has a `From repo` line, naming a repository + that `yum -C repolist enabled` lists. - The package name is the new `wrapper.package_name` config key. - Commands, with `sudo` unless running as root (or `doas`, if it is installed and `sudo` is not, as is usual on Alpine): diff --git a/internal/config/platformsh-cli.yaml b/internal/config/platformsh-cli.yaml index c6cb1b10..4d74830f 100644 --- a/internal/config/platformsh-cli.yaml +++ b/internal/config/platformsh-cli.yaml @@ -7,7 +7,6 @@ wrapper: homebrew_tap: upsun/tap/platformsh-cli github_repo: upsun/cli package_name: platformsh-cli - package_repository: repositories.upsun.com application: name: "Upsun CLI (Platform.sh compatibility)" diff --git a/internal/config/schema.go b/internal/config/schema.go index 0b7d4b37..294604d3 100644 --- a/internal/config/schema.go +++ b/internal/config/schema.go @@ -25,10 +25,8 @@ type Config struct { NpmPackage string `yaml:"npm_package,omitempty"` // e.g. "upsun" WingetPackage string `yaml:"winget_package,omitempty"` // e.g. "Upsun.CLI" PackageName string `yaml:"package_name,omitempty"` // the apt, yum/dnf and apk package, e.g. "upsun-cli" - // The host of the apt, yum/dnf and apk repository, e.g. "repositories.upsun.com". - PackageRepository string `yaml:"package_repository,omitempty"` - InstallerURL string `yaml:"installer_url,omitempty"` // e.g. "https://raw.githubusercontent.com/upsun/cli/main/installer.sh" - InstallMethod string `yaml:"install_method,omitempty"` // forces the detected install method (homebrew, scoop, npm, winget, apt, dnf, yum, apk, package, script) + InstallerURL string `yaml:"installer_url,omitempty"` // e.g. "https://raw.githubusercontent.com/upsun/cli/main/installer.sh" + InstallMethod string `yaml:"install_method,omitempty"` // forces the detected install method (homebrew, scoop, npm, winget, apt, dnf, yum, apk, package, script) } `yaml:"wrapper,omitempty"` Application struct { diff --git a/internal/config/upsun-cli.yaml b/internal/config/upsun-cli.yaml index f6fc3330..a0cea151 100644 --- a/internal/config/upsun-cli.yaml +++ b/internal/config/upsun-cli.yaml @@ -5,7 +5,6 @@ wrapper: homebrew_tap: upsun/tap/upsun-cli github_repo: upsun/cli package_name: upsun-cli - package_repository: repositories.upsun.com npm_package: upsun winget_package: Upsun.CLI installer_url: https://raw.githubusercontent.com/upsun/cli/main/installer.sh diff --git a/internal/install.go b/internal/install.go index 3fb256f1..0c5308d2 100644 --- a/internal/install.go +++ b/internal/install.go @@ -43,9 +43,9 @@ type installProbe struct { getenv func(string) string fileExists func(string) bool brewPrefix func() (string, bool) - pkgRepo string // the host of the package repository, e.g. "repositories.upsun.com" + pkgName string // the apt, dnf/yum and apk package, e.g. "upsun-cli" pkgManager func(exe string) InstallMethod - repoInUse func(m InstallMethod, repo string) bool + inRepo func(m InstallMethod, pkg string) bool } var ( @@ -54,8 +54,8 @@ var ( ) // DetectInstallMethod resolves the install method once per process. It may run -// "brew" or a package manager's query, and read package repository files, so it -// is only called when about to print an update message, not for every command. +// "brew" or package manager queries, so it is only called when about to print +// an update message, not for every command. func DetectInstallMethod(cnf *config.Config) InstallMethod { detectOnce.Do(func() { detectedMethod = detectInstallMethod(newInstallProbe(cnf)) @@ -77,9 +77,9 @@ func newInstallProbe(cnf *config.Config) *installProbe { getenv: getenvFunc, fileExists: fileExists, brewPrefix: brewPrefix, - pkgRepo: bin.Wrapper.PackageRepository, + pkgName: bin.Wrapper.PackageName, pkgManager: owningPackageManager, - repoInUse: packageRepositoryInUse, + inRepo: packageInRepository, } } @@ -134,14 +134,14 @@ func detectInstallMethod(p *installProbe) InstallMethod { // packageMethod returns the install method of the package manager that owns // the executable, or InstallUnknown if none does. It is InstallPackage unless -// the package manager uses the package repository: a downloaded package (e.g. +// an enabled repository provides the package: a downloaded package (e.g. // installed with "dpkg -i") cannot be upgraded with the package manager. func (p *installProbe) packageMethod() InstallMethod { m := p.pkgManager(p.exe) if m == InstallUnknown || m == InstallPackage { return m } - if p.pkgRepo == "" || !p.repoInUse(m, p.pkgRepo) { + if p.pkgName == "" || !p.inRepo(m, p.pkgName) { return InstallPackage } return m diff --git a/internal/install_test.go b/internal/install_test.go index 5b577396..9bfcae3c 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -63,25 +63,25 @@ func TestDetectInstallMethod(t *testing.T) { getenv: func(string) string { return "" }, brewPrefix: noBrew, fileExists: fileAt("/usr/share/upsun/install-source"), pkgManager: func(string) InstallMethod { return InstallApk }, - pkgRepo: "repo.example.com", - repoInUse: func(m InstallMethod, repo string) bool { return m == InstallApk && repo == "repo.example.com" }, + pkgName: "example-cli", + inRepo: func(m InstallMethod, pkg string) bool { return m == InstallApk && pkg == "example-cli" }, }, want: InstallApk, }, { - name: "package marker present, repository not in use (e.g. dpkg -i)", + name: "package marker present, not in a repository (e.g. dpkg -i)", probe: installProbe{ goos: "linux", exe: "/usr/bin/upsun", slug: "upsun", getenv: func(string) string { return "" }, brewPrefix: noBrew, fileExists: fileAt("/usr/share/upsun/install-source"), pkgManager: func(string) InstallMethod { return InstallApt }, - pkgRepo: "repo.example.com", - repoInUse: func(InstallMethod, string) bool { return false }, + pkgName: "example-cli", + inRepo: func(InstallMethod, string) bool { return false }, }, want: InstallPackage, }, { - name: "package marker present, no repository in config", + name: "package marker present, no package name in config", probe: installProbe{ goos: "linux", exe: "/usr/bin/upsun", slug: "upsun", getenv: func(string) string { return "" }, brewPrefix: noBrew, @@ -193,8 +193,8 @@ func TestDetectInstallMethod(t *testing.T) { } return InstallUnknown }, - pkgRepo: "repo.example.com", - repoInUse: func(InstallMethod, string) bool { return true }, + pkgName: "example-cli", + inRepo: func(InstallMethod, string) bool { return true }, }, want: InstallDnf, }, diff --git a/internal/package_repo.go b/internal/package_repo.go index 971e8f1d..0fae3561 100644 --- a/internal/package_repo.go +++ b/internal/package_repo.go @@ -1,140 +1,126 @@ package internal import ( - "maps" + "context" "os" - "path" - "path/filepath" + "os/exec" "regexp" - "slices" "strings" + "time" ) -// packageRepoFiles lists the files (as glob patterns) that configure each package manager's repositories. -var packageRepoFiles = map[InstallMethod][]string{ - InstallApt: {"/etc/apt/sources.list", "/etc/apt/sources.list.d/*.list", "/etc/apt/sources.list.d/*.sources"}, - InstallDnf: {"/etc/yum.repos.d/*.repo"}, - InstallYum: {"/etc/yum.repos.d/*.repo"}, - InstallApk: {"/etc/apk/repositories", "/etc/apk/repositories.d/*.list"}, +// packageInRepository asks the package manager whether an enabled repository +// provides the installed package, so that the package manager can upgrade it. +func packageInRepository(m InstallMethod, pkg string) bool { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + return inRepository(m, pkg, func(name string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Env = append(os.Environ(), "LC_ALL=C") + out, err := cmd.Output() + return string(out), err + }) } -// dnfOverrideFiles lists the files (as glob patterns) that override repository settings in DNF 5. -var dnfOverrideFiles = []string{"/usr/share/dnf5/repos.override.d/*.repo", "/etc/dnf/repos.override.d/*.repo"} - -// packageRepositoryInUse reports whether a package manager's configuration enables the repository. -func packageRepositoryInUse(m InstallMethod, repo string) bool { - var overrides []string - if m == InstallDnf { - overrides = dnfOverrideFiles - } - return anyFileEnablesRepo(packageRepoFiles[m], overrides, repo) -} - -// anyFileEnablesRepo reports whether a file matching one of the glob patterns -// enables the repository, and no file matching the override patterns disables it. -func anyFileEnablesRepo(patterns, overridePatterns []string, repo string) bool { - overrides := readOverrides(overridePatterns) - for _, pattern := range patterns { - paths, _ := filepath.Glob(pattern) - for _, path := range paths { - b, err := os.ReadFile(path) - if err != nil || !enablesRepo(b, repo) { - continue - } - if len(overrides) == 0 { - return true - } - for _, id := range repoSections(b, repo) { - if !disabledByOverride(id, overrides) { - return true - } - } +// inRepository runs the package manager's queries with output, which returns a command's standard output. +func inRepository(m InstallMethod, pkg string, output func(name string, args ...string) (string, error)) bool { + switch m { + case InstallApt: + out, err := output("apt-cache", "policy", pkg) + return err == nil && aptPolicyHasRepository(out) + case InstallApk: + out, err := output("apk", "--no-network", "policy", pkg) + return err == nil && apkPolicyHasRepository(out) + case InstallDnf: + repo, err := output("dnf", "-C", "-q", "repoquery", "--installed", "--qf", "%{from_repo}\n", pkg) + if err != nil { + return false } + repos, err := output("dnf", "-C", "-q", "repolist", "--enabled") + return err == nil && repoEnabled(strings.TrimSpace(repo), repos) + case InstallYum: + info, err := output("yum", "-C", "-q", "info", "installed", pkg) + if err != nil { + return false + } + repos, err := output("yum", "-C", "-q", "repolist", "enabled") + return err == nil && repoEnabled(yumFromRepo(info), repos) } return false } -// readOverrides reads the files matching the glob patterns, ordered by file name as DNF applies them. -// A file masks those of the same name that match an earlier pattern. -func readOverrides(patterns []string) [][]byte { - paths := map[string]string{} - for _, pattern := range patterns { - matches, _ := filepath.Glob(pattern) - for _, path := range matches { - paths[filepath.Base(path)] = path +// aptSource matches a line of the version table of "apt-cache policy" that +// names a source of the version, after its priority. +var aptSource = regexp.MustCompile(`^\s+-?\d+\s+(\S+)`) + +// aptPolicyHasRepository reports whether "apt-cache policy" lists a source +// other than the dpkg status file, i.e. a repository. +func aptPolicyHasRepository(out string) bool { + table := false + for line := range strings.Lines(out) { + if strings.TrimSpace(line) == "Version table:" { + table = true + continue } - } - var contents [][]byte - for _, name := range slices.Sorted(maps.Keys(paths)) { - if b, err := os.ReadFile(paths[name]); err == nil { - contents = append(contents, b) + if !table { + continue + } + m := aptSource.FindStringSubmatch(line) + if len(m) == 2 && m[1] != "/var/lib/dpkg/status" && !isNumber(m[1]) { + return true } } - return contents + return false } -// sectionName returns the name of an INI section header line, e.g. "[name]". -func sectionName(line string) (string, bool) { - if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { - return strings.TrimSpace(line[1 : len(line)-1]), true - } - return "", false +func isNumber(s string) bool { + return strings.Trim(s, "0123456789") == "" } -// repoSections returns the names of the sections of a yum repo file that mention the repository. -func repoSections(content []byte, repo string) []string { - var ids []string - section := "" - for line := range strings.Lines(string(content)) { +// apkPolicyHasRepository reports whether "apk policy" lists a source other +// than the installed database, i.e. a repository. +func apkPolicyHasRepository(out string) bool { + for line := range strings.Lines(out) { line = strings.TrimSpace(line) - if name, ok := sectionName(line); ok { - section = name - } else if section != "" && !strings.HasPrefix(line, "#") && strings.Contains(line, repo) { - ids = append(ids, section) - section = "" + if line == "" || strings.HasSuffix(line, ":") || line == "lib/apk/db/installed" { + continue } + return true } - return ids + return false } -// enabledSetting matches a line that enables or disables a repository. -var enabledSetting = regexp.MustCompile(`(?i)^enabled\s*[=:]`) - -// disabledByOverride reports whether the override files disable a repository. -// Their section names may be glob patterns, and the last setting applies. -func disabledByOverride(id string, overrides [][]byte) bool { - disabled := false - for _, content := range overrides { - applies := false - for line := range strings.Lines(string(content)) { - line = strings.TrimSpace(line) - if name, ok := sectionName(line); ok { - applies, _ = path.Match(name, id) - } else if applies && enabledSetting.MatchString(line) { - disabled = repoDisabled.MatchString(line) - } +// yumFromRepo returns the "From repo" field of "yum info installed". +func yumFromRepo(info string) string { + for line := range strings.Lines(info) { + k, v, ok := strings.Cut(line, ":") + if ok && strings.TrimSpace(k) == "From repo" { + return strings.TrimSpace(v) } } - return disabled + return "" } -// repoDisabled matches a line that disables a repository, in a yum repo file or a deb822 sources file. -var repoDisabled = regexp.MustCompile(`(?i)^enabled\s*[=:]\s*(0|no|false|off|disable|without)$`) - -// enablesRepo reports whether a repository configuration file mentions the -// repository outside comments. A file that disables any repository does not -// count, as it is not parsed to find out which one. -func enablesRepo(content []byte, repo string) bool { - found := false - for line := range strings.Lines(string(content)) { - line = strings.TrimSpace(line) - switch { - case strings.HasPrefix(line, "#"): - case repoDisabled.MatchString(line): - return false - case strings.Contains(line, repo): - found = true +// repoEnabled reports whether the repository ID is in the output of "dnf +// repolist" or "yum repolist". yum may prefix an ID with "!" or "*" and +// suffix it with the release and architecture, e.g. "upsun/x86_64". +func repoEnabled(id, repolist string) bool { + if id == "" { + return false + } + for line := range strings.Lines(repolist) { + // The header ("repo id repo name") has no ID. + if strings.HasPrefix(line, "repo id") { + continue + } + fields := strings.Fields(line) + if len(fields) == 0 { + continue + } + name, _, _ := strings.Cut(strings.TrimLeft(fields[0], "!*"), "/") + if name == id { + return true } } - return found + return false } diff --git a/internal/package_repo_test.go b/internal/package_repo_test.go index 717d9704..856b29c4 100644 --- a/internal/package_repo_test.go +++ b/internal/package_repo_test.go @@ -1,99 +1,137 @@ package internal import ( - "os" - "path/filepath" + "errors" + "strings" "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) -func TestAnyFileEnablesRepo(t *testing.T) { - dir := t.TempDir() - write := func(name, content string) { - require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) - } - write("other.list", "deb http://deb.example.org stable main\n") - write("example.list", "deb https://repo.example.com/debian stable main\n") - write("example.list.distUpgrade", "deb https://backup.example.com/debian stable main\n") - - patterns := []string{filepath.Join(dir, "other.list"), filepath.Join(dir, "*.list")} - assert.True(t, anyFileEnablesRepo(patterns, nil, "repo.example.com")) - assert.False(t, anyFileEnablesRepo(patterns, nil, "other.example.com")) - assert.False(t, anyFileEnablesRepo(patterns, nil, "backup.example.com")) - assert.False(t, anyFileEnablesRepo(patterns[:1], nil, "repo.example.com")) - assert.False(t, anyFileEnablesRepo(nil, nil, "repo.example.com")) -} +// Outputs captured from the package managers, for a package installed from a +// repository, and from a downloaded file. +const ( + aptPolicyRepo = `upsun-cli: + Installed: 5.17.0 + Candidate: 5.17.0 + Version table: + *** 5.17.0 500 + 500 https://repositories.upsun.com/debian stable/main amd64 Packages + 100 /var/lib/dpkg/status + 5.16.0 500 + 500 https://repositories.upsun.com/debian stable/main amd64 Packages +` + aptPolicyFile = `upsun-cli: + Installed: 5.17.0 + Candidate: 5.17.0 + Version table: + *** 5.17.0 100 + 100 /var/lib/dpkg/status +` + apkPolicyRepo = `upsun-cli policy: + 5.17.0: + lib/apk/db/installed + https://repositories.upsun.com/alpine +` + apkPolicyFile = `upsun-cli policy: + 5.17.0: + lib/apk/db/installed +` + dnfRepolist = `repo id repo name +fedora Fedora 45 - x86_64 +updates Fedora 45 - x86_64 - Updates +upsun Upsun CLI +` + yumInfoRepo = `Installed Packages +Name : upsun-cli +Version : 5.17.0 +Repo : installed +From repo : upsun +` + yumInfoFile = `Installed Packages +Name : upsun-cli +Version : 5.17.0 +Repo : installed +` + yumRepolist = `repo id repo name status +amzn2-core/2/x86_64 Amazon Linux 2 core repository 44236 +upsun/x86_64 Upsun CLI 26 +` +) -func TestAnyFileEnablesRepoWithOverrides(t *testing.T) { - const repoFile = "[other]\nbaseurl=https://rpm.example.org/\n\n" + - "[example]\nname=Example\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\n" +func TestInRepository(t *testing.T) { cases := []struct { - name string - // Override files by path, relative to a temporary directory. - overrides map[string]string - want bool + name string + method InstallMethod + outputs map[string]string // command line -> output; other commands fail + want bool }{ - {"no overrides", nil, true}, - {"disabled", map[string]string{"etc/99-config_manager.repo": "# Generated.\n[example]\nenabled=0\n"}, false}, - {"another repository disabled", map[string]string{"etc/99-config_manager.repo": "[other]\nenabled=0\n"}, true}, - {"disabled by a glob pattern", map[string]string{"etc/50-all.repo": "[exam*]\nenabled = false\n"}, false}, - {"another option set", map[string]string{"etc/50-x.repo": "[example]\npriority=10\n"}, true}, - {"enabled again by a later file", map[string]string{ - "etc/50-x.repo": "[example]\nenabled=0\n", - "etc/60-x.repo": "[example]\nenabled=1\n", + {"apt repository", InstallApt, map[string]string{"apt-cache policy upsun-cli": aptPolicyRepo}, true}, + {"apt file", InstallApt, map[string]string{"apt-cache policy upsun-cli": aptPolicyFile}, false}, + {"apt query fails", InstallApt, nil, false}, + {"apk repository", InstallApk, map[string]string{"apk --no-network policy upsun-cli": apkPolicyRepo}, true}, + {"apk file", InstallApk, map[string]string{"apk --no-network policy upsun-cli": apkPolicyFile}, false}, + {"dnf repository", InstallDnf, map[string]string{ + "dnf -C -q repoquery --installed --qf %{from_repo}\n upsun-cli": "upsun\n\n", + "dnf -C -q repolist --enabled": dnfRepolist, }, true}, - {"later file name in another directory", map[string]string{ - "etc/40-x.repo": "[example]\nenabled=1\n", - "usr/50-x.repo": "[example]\nenabled=0\n", + {"dnf repository disabled", InstallDnf, map[string]string{ + "dnf -C -q repoquery --installed --qf %{from_repo}\n upsun-cli": "upsun\n", + "dnf -C -q repolist --enabled": strings.ReplaceAll(dnfRepolist, "upsun ", "other "), }, false}, - {"masked by a file of the same name", map[string]string{ - "usr/50-x.repo": "[example]\nenabled=0\n", - "etc/50-x.repo": "[example]\npriority=10\n", + {"dnf command line", InstallDnf, map[string]string{ + "dnf -C -q repoquery --installed --qf %{from_repo}\n upsun-cli": "@commandline\n", + "dnf -C -q repolist --enabled": dnfRepolist, + }, false}, + {"dnf unknown", InstallDnf, map[string]string{ + "dnf -C -q repoquery --installed --qf %{from_repo}\n upsun-cli": "\n", + "dnf -C -q repolist --enabled": dnfRepolist, + }, false}, + {"dnf4 rpm -i", InstallDnf, map[string]string{ + "dnf -C -q repoquery --installed --qf %{from_repo}\n upsun-cli": "\n\n", + "dnf -C -q repolist --enabled": "repo id repo name\n", + }, false}, + {"yum repository", InstallYum, map[string]string{ + "yum -C -q info installed upsun-cli": yumInfoRepo, + "yum -C -q repolist enabled": yumRepolist, }, true}, - {"not a repo file", map[string]string{"etc/50-x.conf": "[example]\nenabled=0\n"}, true}, + {"yum file", InstallYum, map[string]string{ + "yum -C -q info installed upsun-cli": yumInfoFile, + "yum -C -q repolist enabled": yumRepolist, + }, false}, + {"yum repolist fails", InstallYum, map[string]string{ + "yum -C -q info installed upsun-cli": yumInfoRepo, + }, false}, + {"unknown method", InstallPackage, nil, false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - dir := t.TempDir() - for _, d := range []string{"repos", "usr", "etc"} { - require.NoError(t, os.Mkdir(filepath.Join(dir, d), 0o700)) - } - require.NoError(t, os.WriteFile(filepath.Join(dir, "repos", "example.repo"), []byte(repoFile), 0o600)) - for name, content := range c.overrides { - require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600)) + output := func(name string, args ...string) (string, error) { + if out, ok := c.outputs[name+" "+strings.Join(args, " ")]; ok { + return out, nil + } + return "", errors.New("exit status 1") } - patterns := []string{filepath.Join(dir, "repos", "*.repo")} - overrides := []string{filepath.Join(dir, "usr", "*.repo"), filepath.Join(dir, "etc", "*.repo")} - assert.Equal(t, c.want, anyFileEnablesRepo(patterns, overrides, "repo.example.com")) + assert.Equal(t, c.want, inRepository(c.method, "upsun-cli", output)) }) } } -func TestEnablesRepo(t *testing.T) { - cases := []struct { - name string - content string - want bool - }{ - {"apt list", "deb [signed-by=/k.asc] https://repo.example.com/debian stable main\n", true}, - {"apt list disabled by a release upgrade", "# deb https://repo.example.com/debian stable main # disabled\n", false}, - {"deb822", "Types: deb\nURIs: https://repo.example.com/debian\nSuites: stable\n", true}, - {"deb822 disabled", "Types: deb\nURIs: https://repo.example.com/debian\nEnabled: no\n", false}, - {"yum", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=1\ngpgcheck=1\n", true}, - {"yum disabled", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled = 0\n", false}, - {"yum disabled with off", "[example]\nbaseurl=https://repo.example.com/rpm/$basearch\nenabled=off\n", false}, - {"deb822 disabled with disable", "URIs: https://repo.example.com/debian\nEnabled: disable\n", false}, - {"deb822 disabled with without", "URIs: https://repo.example.com/debian\nEnabled: without\n", false}, - {"apk", "https://dl-cdn.example.org/alpine/main\nhttps://repo.example.com/alpine\n", true}, - {"apk commented out", "https://dl-cdn.example.org/alpine/main\n #https://repo.example.com/alpine\n", false}, - {"another repository", "deb http://deb.example.org stable main\n", false}, - {"empty", "", false}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - assert.Equal(t, c.want, enablesRepo([]byte(c.content), "repo.example.com")) - }) - } +func TestRepoEnabled(t *testing.T) { + assert.True(t, repoEnabled("upsun", dnfRepolist)) + assert.True(t, repoEnabled("upsun", yumRepolist)) + assert.True(t, repoEnabled("amzn2-core", yumRepolist)) + assert.True(t, repoEnabled("upsun", "!upsun/x86_64 Upsun CLI 26\n")) + assert.False(t, repoEnabled("repo", dnfRepolist)) + assert.False(t, repoEnabled("", dnfRepolist)) + assert.False(t, repoEnabled("other", dnfRepolist)) +} + +func TestAptPolicyHasRepository(t *testing.T) { + assert.True(t, aptPolicyHasRepository(aptPolicyRepo)) + assert.False(t, aptPolicyHasRepository(aptPolicyFile)) + assert.False(t, aptPolicyHasRepository("")) + // A version that is a number, without a repository. + assert.False(t, aptPolicyHasRepository( + "x:\n Version table:\n *** 1 100\n 100 /var/lib/dpkg/status\n 2 500\n")) } From 5064660021fbd6f51e6bcdd2bfbecd4fe98019c9 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Thu, 19 Nov 2026 19:18:13 +0000 Subject: [PATCH 12/14] fix(update): require the package to be installed for apt and apk The ownership query only finds that some package owns the executable. If it was another package, and the configured package was available in a repository, `apt-cache policy` and `apk policy` listed the repository, and the notice suggested an upgrade command that does nothing. Also require the dpkg status file (apt) or the installed database (apk) as a source, as dnf and yum already query the installed package. Co-Authored-By: Claude Opus 5.5 --- .../update-message-install-detection.md | 11 +++--- internal/package_repo.go | 34 ++++++++++++------- internal/package_repo_test.go | 17 +++++++++- 3 files changed, 44 insertions(+), 18 deletions(-) diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index 43e131b0..0331cc0b 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -26,11 +26,12 @@ got a new release when they happened to upgrade. This revision changes that: the method is only `apt`, `dnf`, `yum` or `apk` if the package manager says that an enabled repository provides the package. Otherwise it is `package`. The queries run without network access, under a 2-second limit: - - apt: `apt-cache policy ` lists a source other than - `/var/lib/dpkg/status`. Without package lists (e.g. removed in a container - image), it does not. - - apk: `apk --no-network policy ` lists a source other than - `lib/apk/db/installed`. Without its index cache, it does not. + - apt: `apt-cache policy ` lists `/var/lib/dpkg/status` (the + package is installed) and another source. Without package lists (e.g. + removed in a container image), it lists no other source. + - apk: `apk --no-network policy ` lists `lib/apk/db/installed` + (the package is installed) and another source. Without its index cache, + it lists no other source. - dnf: `dnf -C repoquery --installed --qf '%{from_repo}'` names a repository that `dnf -C repolist --enabled` lists. It is `` (dnf 5) or empty (dnf 4) for `rpm -i`, and `@commandline` for `dnf install ./file.rpm`. diff --git a/internal/package_repo.go b/internal/package_repo.go index 0fae3561..35f3492f 100644 --- a/internal/package_repo.go +++ b/internal/package_repo.go @@ -53,10 +53,11 @@ func inRepository(m InstallMethod, pkg string, output func(name string, args ... // names a source of the version, after its priority. var aptSource = regexp.MustCompile(`^\s+-?\d+\s+(\S+)`) -// aptPolicyHasRepository reports whether "apt-cache policy" lists a source -// other than the dpkg status file, i.e. a repository. +// aptPolicyHasRepository reports whether "apt-cache policy" shows the package +// as installed (from the dpkg status file), and lists another source, i.e. a +// repository. func aptPolicyHasRepository(out string) bool { - table := false + table, installed, repo := false, false, false for line := range strings.Lines(out) { if strings.TrimSpace(line) == "Version table:" { table = true @@ -66,28 +67,37 @@ func aptPolicyHasRepository(out string) bool { continue } m := aptSource.FindStringSubmatch(line) - if len(m) == 2 && m[1] != "/var/lib/dpkg/status" && !isNumber(m[1]) { - return true + switch { + case len(m) != 2 || isNumber(m[1]): + case m[1] == "/var/lib/dpkg/status": + installed = true + default: + repo = true } } - return false + return installed && repo } func isNumber(s string) bool { return strings.Trim(s, "0123456789") == "" } -// apkPolicyHasRepository reports whether "apk policy" lists a source other -// than the installed database, i.e. a repository. +// apkPolicyHasRepository reports whether "apk policy" shows the package as +// installed (from the installed database), and lists another source, i.e. a +// repository. func apkPolicyHasRepository(out string) bool { + installed, repo := false, false for line := range strings.Lines(out) { line = strings.TrimSpace(line) - if line == "" || strings.HasSuffix(line, ":") || line == "lib/apk/db/installed" { - continue + switch { + case line == "" || strings.HasSuffix(line, ":"): + case line == "lib/apk/db/installed": + installed = true + default: + repo = true } - return true } - return false + return installed && repo } // yumFromRepo returns the "From repo" field of "yum info installed". diff --git a/internal/package_repo_test.go b/internal/package_repo_test.go index 856b29c4..952d427b 100644 --- a/internal/package_repo_test.go +++ b/internal/package_repo_test.go @@ -9,7 +9,7 @@ import ( ) // Outputs captured from the package managers, for a package installed from a -// repository, and from a downloaded file. +// repository, installed from a downloaded file, and not installed. const ( aptPolicyRepo = `upsun-cli: Installed: 5.17.0 @@ -27,6 +27,13 @@ const ( Version table: *** 5.17.0 100 100 /var/lib/dpkg/status +` + aptPolicyNotInstalled = `upsun-cli: + Installed: (none) + Candidate: 5.17.0 + Version table: + 5.17.0 500 + 500 https://repositories.upsun.com/debian stable/main amd64 Packages ` apkPolicyRepo = `upsun-cli policy: 5.17.0: @@ -36,6 +43,10 @@ const ( apkPolicyFile = `upsun-cli policy: 5.17.0: lib/apk/db/installed +` + apkPolicyNotInstalled = `upsun-cli policy: + 5.17.0: + https://repositories.upsun.com/alpine ` dnfRepolist = `repo id repo name fedora Fedora 45 - x86_64 @@ -68,9 +79,13 @@ func TestInRepository(t *testing.T) { }{ {"apt repository", InstallApt, map[string]string{"apt-cache policy upsun-cli": aptPolicyRepo}, true}, {"apt file", InstallApt, map[string]string{"apt-cache policy upsun-cli": aptPolicyFile}, false}, + {"apt not installed", InstallApt, map[string]string{"apt-cache policy upsun-cli": aptPolicyNotInstalled}, false}, {"apt query fails", InstallApt, nil, false}, {"apk repository", InstallApk, map[string]string{"apk --no-network policy upsun-cli": apkPolicyRepo}, true}, {"apk file", InstallApk, map[string]string{"apk --no-network policy upsun-cli": apkPolicyFile}, false}, + {"apk not installed", InstallApk, map[string]string{ + "apk --no-network policy upsun-cli": apkPolicyNotInstalled, + }, false}, {"dnf repository", InstallDnf, map[string]string{ "dnf -C -q repoquery --installed --qf %{from_repo}\n upsun-cli": "upsun\n\n", "dnf -C -q repolist --enabled": dnfRepolist, From cc06b6d8d8113dd78a5dff29c1f104006c2b7aa9 Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Thu, 19 Nov 2026 19:23:18 +0000 Subject: [PATCH 13/14] docs(update): describe the dnf and yum repository check accurately dnf and yum check that the package was installed from a repository that is still enabled, not that an enabled repository provides it: a package installed with `rpm -i`, from a repository added later, gets the generic link. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/design/update-message-install-detection.md | 10 +++++++--- internal/install.go | 2 +- internal/package_repo.go | 6 ++++-- 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7ef11cc1..6ba4e7bf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -208,7 +208,7 @@ PHP version is still injected via ldflags: The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). The notice is printed by `commands/update_message.go`. When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. Install-method detection (`internal/install.go`, and `internal/package_repo.go` for package repositories) tailors the notice: -- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager does not report that an enabled repository provides the package (`apt-cache policy`, `apk --no-network policy`, dnf's `from_repo`, `yum info installed`; e.g. not for a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. +- System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager does not report that the package is installed and comes from an enabled repository (for apt and apk, `apt-cache policy` or `apk --no-network policy` lists a repository; for dnf and yum, dnf's `from_repo` or yum's `From repo` is still enabled; e.g. not for a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. - Homebrew, Scoop, npm, winget, and the bash installer also get a tailored upgrade command, built from config fields (`Wrapper.HomebrewTap`, `Wrapper.NpmPackage`, `Wrapper.WingetPackage`, `Wrapper.InstallerURL`, `Application.Executable`). - winget installs are detected by their path (`\WinGet\Packages\`). A release reaches winget only after Microsoft merges its manifest PR in `microsoft/winget-pkgs`, so for winget installs the background check reads the newest version there (from the GitHub API) instead of the latest GitHub release. - The notice is only shown in an interactive terminal, and at most once a week for the same version (`LastNotified` and `NotifiedVersion` in state): a newer version is announced without waiting. diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index 0331cc0b..ad5eee28 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -23,9 +23,13 @@ got a new release when they happened to upgrade. This revision changes that: package with an unknown package manager, which gets the generic link. - A downloaded package (installed with `dpkg -i`, `rpm -i` or `apk add --allow-untrusted`) cannot be upgraded with the package manager. So - the method is only `apt`, `dnf`, `yum` or `apk` if the package manager says - that an enabled repository provides the package. Otherwise it is `package`. - The queries run without network access, under a 2-second limit: + the method is only `apt`, `dnf`, `yum` or `apk` if the package manager + reports that the package is installed and comes from an enabled repository: + for apt and apk, a repository provides it; for dnf and yum, it was installed + from a repository that is still enabled. Otherwise it is `package`. So a + package installed with `rpm -i`, from a repository added later, gets the + generic link. The queries run without network access, under a 2-second + limit: - apt: `apt-cache policy ` lists `/var/lib/dpkg/status` (the package is installed) and another source. Without package lists (e.g. removed in a container image), it lists no other source. diff --git a/internal/install.go b/internal/install.go index 0c5308d2..ecb70ca7 100644 --- a/internal/install.go +++ b/internal/install.go @@ -134,7 +134,7 @@ func detectInstallMethod(p *installProbe) InstallMethod { // packageMethod returns the install method of the package manager that owns // the executable, or InstallUnknown if none does. It is InstallPackage unless -// an enabled repository provides the package: a downloaded package (e.g. +// the package comes from an enabled repository: a downloaded package (e.g. // installed with "dpkg -i") cannot be upgraded with the package manager. func (p *installProbe) packageMethod() InstallMethod { m := p.pkgManager(p.exe) diff --git a/internal/package_repo.go b/internal/package_repo.go index 35f3492f..3a12e24b 100644 --- a/internal/package_repo.go +++ b/internal/package_repo.go @@ -9,8 +9,10 @@ import ( "time" ) -// packageInRepository asks the package manager whether an enabled repository -// provides the installed package, so that the package manager can upgrade it. +// packageInRepository asks the package manager whether the installed package +// comes from an enabled repository, so that the package manager can upgrade +// it: for apt and apk, a repository provides it; for dnf and yum, it was +// installed from a repository that is still enabled. func packageInRepository(m InstallMethod, pkg string) bool { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() From 3b2876fc90372689cafd0961970b61d19d5918dc Mon Sep 17 00:00:00 2001 From: Patrick Dawkins Date: Thu, 19 Nov 2026 19:33:26 +0000 Subject: [PATCH 14/14] fix(update): detect the install method during the background check A notice shown at exit ran the install method detection (package manager queries of up to 3 seconds in total) after the command had finished, on top of the 1 second wait for the check. The background check now runs the detection itself when it finds a release to announce, while the command runs. The wait for the check is then the only delay at exit: if detection has not finished within it, the notice is left for a later run. Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 2 +- docs/design/update-message-install-detection.md | 4 +++- internal/install.go | 4 ++-- internal/update.go | 4 ++++ 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6ba4e7bf..1f66eb71 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -205,7 +205,7 @@ PHP version is still injected via ldflags: ### Update Checks -The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). The notice is printed by `commands/update_message.go`. When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then. Otherwise the notice is shown before the command on a later run. +The CLI checks for updates from GitHub releases (when Wrapper.GitHubRepo is set in config). The network check runs in a background goroutine and caches the latest known version in `state.json` (see `internal/update.go`). The notice is printed by `commands/update_message.go`. When a check is running, the CLI waits up to 1 second for it before exiting: if it found a new release, the notice is shown then (the check also detects the install method, so that this wait is the only delay). Otherwise the notice is shown before the command on a later run. Install-method detection (`internal/install.go`, and `internal/package_repo.go` for package repositories) tailors the notice: - System packages are detected via a marker file installed by the nfpm packages (`packaging/install-source` → `/usr/share//install-source`), or in a standard bin directory without one. Before printing a notice, the package manager (apt, dnf or yum, apk) is found by asking dpkg, rpm and apk which owns the executable. The upgrade command uses `Wrapper.PackageName`, with `sudo` (or `doas`) unless running as root. If the package manager does not report that the package is installed and comes from an enabled repository (for apt and apk, `apt-cache policy` or `apk --no-network policy` lists a repository; for dnf and yum, dnf's `from_repo` or yum's `From repo` is still enabled; e.g. not for a downloaded package installed with `dpkg -i`), the method is `package`, which gets the generic link. The package repositories are updated by the release workflow straight after the GitHub release. diff --git a/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index ad5eee28..052ef438 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -52,7 +52,9 @@ got a new release when they happened to upgrade. This revision changes that: the version last announced, and a newer one is announced without waiting. - If the background check finishes before the command exits (it is waited for, for up to 1 second), a release it found is announced at the end of that run, - unless a notice was already shown at the start. + unless a notice was already shown at the start. The check also detects the + install method, so that wait is the only delay at exit: if detection takes + longer, the notice is left for a later run. ## Background diff --git a/internal/install.go b/internal/install.go index ecb70ca7..87a25475 100644 --- a/internal/install.go +++ b/internal/install.go @@ -54,8 +54,8 @@ var ( ) // DetectInstallMethod resolves the install method once per process. It may run -// "brew" or package manager queries, so it is only called when about to print -// an update message, not for every command. +// "brew" or package manager queries, so it is only called when there is an +// update message to print, not for every command. func DetectInstallMethod(cnf *config.Config) InstallMethod { detectOnce.Do(func() { detectedMethod = detectInstallMethod(newInstallProbe(cnf)) diff --git a/internal/update.go b/internal/update.go index 765cb1b7..132db657 100644 --- a/internal/update.go +++ b/internal/update.go @@ -62,6 +62,10 @@ func StartUpdateCheck(cnf *config.Config) *UpdateCheck { state.Update(cnf, func(s *state.State) { s.Updates.KnownLatestVersion = latest }) + // Detect the install method while the command runs, so that a message at exit does not wait for it. + if PendingNotification(cnf, config.Version) != nil { + DetectInstallMethod(cnf) + } }() return c }