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 a2e75cb1..1f66eb71 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`). 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`) 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`, 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. +- 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 daaa930e..ecdadbd7 100644 --- a/README.md +++ b/README.md @@ -88,12 +88,13 @@ Regular system package updates (e.g. `sudo apt update && sudo apt upgrade`) also ### 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..2d594b54 100644 --- a/commands/root.go +++ b/commands/root.go @@ -12,7 +12,6 @@ import ( "slices" "strings" "syscall" - "time" "github.com/fatih/color" "github.com/spf13/cobra" @@ -38,13 +37,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 } @@ -53,17 +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 - -// updateCheck is the background update check started by the root command, if any. -var updateCheck *internal.UpdateCheck - -// waitForUpdateCheck gives a running update check a chance to save its result. -func waitForUpdateCheck() { - updateCheck.Wait(updateCheckWait) -} - func newRootCommand(cnf *config.Config) *cobra.Command { versionCommand := newVersionCommand(cnf) cmd := &cobra.Command{ @@ -96,26 +84,17 @@ 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) + updateMessage = newUpdateNotifier(cnf, cmd.ErrOrStderr(), quiet) 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. + updateMessage.show(false) if alt.ShouldUpdate(cnf) { go func() { if err := alt.Update(cmd.Context(), cnf, debugLogf); err != nil { @@ -251,80 +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. -func printUpdateMessage(w io.Writer, rel *internal.ReleaseInfo, cnf *config.Config, method internal.InstallMethod) { - if rel == nil { - return - } - bin := cnf.Embedded() - exe, _ := os.Executable() - upgradeCmd := upgradeCommandFor(bin, method, exe) - if upgradeCmd == "" && !cnf.IsEmbedded() { - return - } - - 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.Fprintf(w, "%s\n\n", color.YellowString(rel.URL)) -} - -// 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.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 "" -} - -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 @@ -343,13 +248,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 deleted file mode 100644 index 3e1ea058..00000000 --- a/commands/root_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package commands - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/upsun/cli/internal" - "github.com/upsun/cli/internal/config" -) - -func TestUpgradeCommandFor(t *testing.T) { - cnf := testConfig() - cnf.Wrapper.HomebrewTap = "upsun/tap/upsun-cli" - cnf.Wrapper.NpmPackage = "upsun" - cnf.Wrapper.WingetPackage = "Upsun.CLI" - cnf.Wrapper.InstallerURL = "https://x.test/i.sh" - cnf.Application.Executable = "upsun" - - cases := []struct { - method internal.InstallMethod - want string - }{ - {internal.InstallHomebrew, "brew update && brew upgrade upsun/tap/upsun-cli"}, - {internal.InstallScoop, "scoop update upsun"}, - {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.InstallUnknown, ""}, // falls back to the generic link - } - for _, c := range cases { - t.Run(string(c.method), func(t *testing.T) { - assert.Equal(t, c.want, upgradeCommandFor(cnf, c.method, "/usr/local/bin/upsun")) - }) - } -} - -func TestUpgradeCommandForMissingConfigFallsBack(t *testing.T) { - cnf := testConfig() // no Wrapper.* fields set - // Homebrew/npm/winget/script require their config field; without it, fall back (empty). - assert.Empty(t, upgradeCommandFor(cnf, internal.InstallHomebrew, "/usr/local/bin/upsun")) - 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")) -} - -func TestShellQuote(t *testing.T) { - cases := []struct{ in, want string }{ - {"/usr/local/bin", "/usr/local/bin"}, - {"/home/Jane Doe/.local/bin", "'/home/Jane Doe/.local/bin'"}, - {"/tmp/it's", `'/tmp/it'\''s'`}, - {"/tmp/$(id)", "'/tmp/$(id)'"}, - } - for _, c := range cases { - assert.Equal(t, c.want, shellQuote(c.in)) - } -} - -func TestPrintUpdateMessageWithAltConfig(t *testing.T) { - cnf, err := config.FromYAML([]byte(` -application: - {name: Example CLI, slug: example-cli, executable: example, env_prefix: EXAMPLE_CLI_, user_config_dir: .example-cli} -service: {name: Example, env_prefix: EXAMPLE_, project_config_dir: .example} -api: {base_url: "https://api.example.com", auth_url: "https://auth.example.com"} -detection: {git_remote_name: example, site_domains: [example.site]} -ssh: {domain_wildcards: ["*.example.site"]} -`)) - require.NoError(t, err) - bin := cnf.Embedded() - rel := &internal.ReleaseInfo{Version: "9.9.9", URL: "https://example.com/release"} - - buf := &bytes.Buffer{} - printUpdateMessage(buf, rel, cnf, internal.InstallScoop) - assert.Contains(t, buf.String(), "A new release of the "+bin.Application.Name+" is available") - assert.Contains(t, buf.String(), "scoop update "+bin.Application.Executable) - - // Without an upgrade command, an alt CLI (e.g. with a private copy of the binary) shows nothing. - buf.Reset() - printUpdateMessage(buf, rel, cnf, internal.InstallUnknown) - assert.Empty(t, buf.String()) -} - -func TestPrintUpdateMessageUnknownMethod(t *testing.T) { - t.Setenv("CLI_CONFIG_FILE", "") - b, err := config.LoadYAML() - require.NoError(t, err) - cnf, err := config.FromYAML(b) - require.NoError(t, err) - - buf := &bytes.Buffer{} - printUpdateMessage(buf, &internal.ReleaseInfo{Version: "9.9.9", URL: "https://example.com/release"}, cnf, - internal.InstallUnknown) - assert.Contains(t, buf.String(), "https://github.com/"+cnf.Wrapper.GitHubRepo+"#upgrade") -} 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/update_message_test.go b/commands/update_message_test.go new file mode 100644 index 00000000..4a903ad6 --- /dev/null +++ b/commands/update_message_test.go @@ -0,0 +1,198 @@ +package commands + +import ( + "bytes" + "os/exec" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/upsun/cli/internal" + "github.com/upsun/cli/internal/config" +) + +func TestUpgradeCommandFor(t *testing.T) { + cnf := testConfig() + cnf.Wrapper.HomebrewTap = "upsun/tap/upsun-cli" + 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, 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 + want string + }{ + {internal.InstallHomebrew, "brew update && brew upgrade upsun/tap/upsun-cli"}, + {internal.InstallScoop, "scoop update upsun"}, + {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.InstallApt, "sudo apt update && sudo apt install --only-upgrade upsun-cli"}, + {internal.InstallDnf, "sudo dnf upgrade --refresh 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 + } + for _, c := range cases { + t.Run(string(c.method), func(t *testing.T) { + assert.Equal(t, c.want, upgradeCommandFor(cnf, c.method, "/usr/local/bin/upsun")) + }) + } +} + +func TestUpgradeCommandForMissingConfigFallsBack(t *testing.T) { + cnf := testConfig() // no Wrapper.* fields set + // Homebrew/npm/winget/script require their config field; without it, fall back (empty). + assert.Empty(t, upgradeCommandFor(cnf, internal.InstallHomebrew, "/usr/local/bin/upsun")) + 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 TestPackageUpgradeCommandPrivilege(t *testing.T) { + assert.Equal(t, "apt update && apt install --only-upgrade upsun-cli", + 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) { + cases := []struct{ in, want string }{ + {"/usr/local/bin", "/usr/local/bin"}, + {"/home/Jane Doe/.local/bin", "'/home/Jane Doe/.local/bin'"}, + {"/tmp/it's", `'/tmp/it'\''s'`}, + {"/tmp/$(id)", "'/tmp/$(id)'"}, + } + for _, c := range cases { + assert.Equal(t, c.want, shellQuote(c.in)) + } +} + +func TestPrintUpdateMessageWithAltConfig(t *testing.T) { + cnf, err := config.FromYAML([]byte(` +application: + {name: Example CLI, slug: example-cli, executable: example, env_prefix: EXAMPLE_CLI_, user_config_dir: .example-cli} +service: {name: Example, env_prefix: EXAMPLE_, project_config_dir: .example} +api: {base_url: "https://api.example.com", auth_url: "https://auth.example.com"} +detection: {git_remote_name: example, site_domains: [example.site]} +ssh: {domain_wildcards: ["*.example.site"]} +`)) + require.NoError(t, err) + bin := cnf.Embedded() + rel := &internal.ReleaseInfo{Version: "9.9.9", URL: "https://example.com/release"} + + buf := &bytes.Buffer{} + printUpdateMessage(buf, rel, cnf, internal.InstallScoop) + assert.Contains(t, buf.String(), "A new release of the "+bin.Application.Name+" is available") + assert.Contains(t, buf.String(), "scoop update "+bin.Application.Executable) + + // Without an upgrade command, an alt CLI (e.g. with a private copy of the binary) shows nothing. + buf.Reset() + printUpdateMessage(buf, rel, cnf, internal.InstallUnknown) + assert.Empty(t, buf.String()) +} + +func TestPrintUpdateMessageUnknownMethod(t *testing.T) { + t.Setenv("CLI_CONFIG_FILE", "") + b, err := config.LoadYAML() + require.NoError(t, err) + cnf, err := config.FromYAML(b) + require.NoError(t, err) + + buf := &bytes.Buffer{} + printUpdateMessage(buf, &internal.ReleaseInfo{Version: "9.9.9", URL: "https://example.com/release"}, cnf, + 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/docs/design/update-message-install-detection.md b/docs/design/update-message-install-detection.md index 29f503c1..052ef438 100644 --- a/docs/design/update-message-install-detection.md +++ b/docs/design/update-message-install-detection.md @@ -4,6 +4,58 @@ 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. +- 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 + 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. + - 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`. + - 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): + - `apt update && apt install --only-upgrade ` + - `dnf upgrade --refresh ` + - `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. +- 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. 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 The CLI checks GitHub for a newer release and, if one exists, prints a message @@ -61,7 +113,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 @@ -206,7 +259,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 | @@ -370,9 +424,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. @@ -424,8 +477,8 @@ upgrade line per method, including empty-config fallbacks. ## Resolved decisions -- `package` installs: total silence, no hint. The OS handles updates. -- Manual `dpkg -i`/`rpm -i`: treated as `package` (suppressed). Acceptable. +- `package` installs: originally silent; now notified (see the revision at the top). +- 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 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..87a25475 100644 --- a/internal/install.go +++ b/internal/install.go @@ -15,7 +15,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 ( @@ -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,9 @@ type installProbe struct { getenv func(string) string fileExists func(string) bool brewPrefix func() (string, bool) - pkgOwned func(exe string) bool + pkgName string // the apt, dnf/yum and apk package, e.g. "upsun-cli" + pkgManager func(exe string) InstallMethod + inRepo func(m InstallMethod, pkg string) bool } var ( @@ -53,9 +53,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 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)) @@ -77,18 +77,10 @@ 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() + pkgName: bin.Wrapper.PackageName, + pkgManager: owningPackageManager, + inRepo: packageInRepository, } - return packageMarkerExists(resolvedExecutable(), bin.Application.Slug, fileExists) } // IsWinget is a cheap check (no subprocess) for a winget install. @@ -110,6 +102,9 @@ func detectInstallMethod(p *installProbe) InstallMethod { return m } if packageMarkerExists(p.exe, p.slug, p.fileExists) { + if m := p.packageMethod(); m != InstallUnknown { + return m + } return InstallPackage } n := normPath(p.exe) @@ -127,14 +122,31 @@ 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.packageMethod(); m != InstallUnknown { + return m + } } return InstallScript } 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 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) + if m == InstallUnknown || m == InstallPackage { + return m + } + if p.pkgName == "" || !p.inRepo(m, p.pkgName) { + return InstallPackage + } + return m +} + // 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 != "" { @@ -158,7 +170,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 +257,61 @@ 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. +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}, + 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 + }{ + {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 := 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 = run(ctx, p, q.args[1:]...) + if ctx.Err() != nil { + return InstallPackage + } + if err != nil { + continue } + if q.method == InstallDnf { + return rpmFrontend(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..9bfcae3c 100644 --- a/internal/install_test.go +++ b/internal/install_test.go @@ -1,7 +1,12 @@ package internal import ( + "context" + "errors" + "os/exec" "path" + "slices" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -43,16 +48,50 @@ 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: InstallApt, + }, + { + 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 }, + pkgName: "example-cli", + inRepo: func(m InstallMethod, pkg string) bool { return m == InstallApk && pkg == "example-cli" }, + }, + want: InstallApk, + }, + { + 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 }, + pkgName: "example-cli", + inRepo: func(InstallMethod, string) bool { return false }, + }, + want: InstallPackage, + }, + { + 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, + fileExists: fileAt("/usr/share/upsun/install-source"), + pkgManager: func(string) InstallMethod { return InstallApt }, + }, want: InstallPackage, }, { - name: "package marker present", + 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 +187,16 @@ 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 + }, + pkgName: "example-cli", + inRepo: func(InstallMethod, string) bool { return true }, }, - want: InstallPackage, + want: InstallDnf, }, { name: "homebrew via brew prefix", @@ -172,19 +218,82 @@ 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 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) { + 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 +304,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/package_repo.go b/internal/package_repo.go new file mode 100644 index 00000000..3a12e24b --- /dev/null +++ b/internal/package_repo.go @@ -0,0 +1,138 @@ +package internal + +import ( + "context" + "os" + "os/exec" + "regexp" + "strings" + "time" +) + +// 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() + 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 + }) +} + +// 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 +} + +// 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" shows the package +// as installed (from the dpkg status file), and lists another source, i.e. a +// repository. +func aptPolicyHasRepository(out string) bool { + table, installed, repo := false, false, false + for line := range strings.Lines(out) { + if strings.TrimSpace(line) == "Version table:" { + table = true + continue + } + if !table { + continue + } + m := aptSource.FindStringSubmatch(line) + switch { + case len(m) != 2 || isNumber(m[1]): + case m[1] == "/var/lib/dpkg/status": + installed = true + default: + repo = true + } + } + return installed && repo +} + +func isNumber(s string) bool { + return strings.Trim(s, "0123456789") == "" +} + +// 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) + switch { + case line == "" || strings.HasSuffix(line, ":"): + case line == "lib/apk/db/installed": + installed = true + default: + repo = true + } + } + return installed && repo +} + +// 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 "" +} + +// 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 false +} diff --git a/internal/package_repo_test.go b/internal/package_repo_test.go new file mode 100644 index 00000000..952d427b --- /dev/null +++ b/internal/package_repo_test.go @@ -0,0 +1,152 @@ +package internal + +import ( + "errors" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// Outputs captured from the package managers, for a package installed from a +// repository, installed from a downloaded file, and not installed. +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 +` + 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: + lib/apk/db/installed + https://repositories.upsun.com/alpine +` + 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 +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 TestInRepository(t *testing.T) { + cases := []struct { + name string + method InstallMethod + outputs map[string]string // command line -> output; other commands fail + want bool + }{ + {"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, + }, true}, + {"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}, + {"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}, + {"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) { + 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") + } + assert.Equal(t, c.want, inRepository(c.method, "upsun-cli", output)) + }) + } +} + +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")) +} 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..132db657 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 @@ -61,29 +62,35 @@ 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 } -// 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 +108,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 +151,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) }) }