From 2d1445ec3db0e0fb46e0cac2019bdf068de99cf8 Mon Sep 17 00:00:00 2001 From: Montana Date: Wed, 1 Jul 2026 08:07:22 -0700 Subject: [PATCH 1/6] feat: warn when src-cli is older than the instance's recommended version Before running a command, src does a best-effort check of the running version against the version recommended by the configured instance (/.api/src-cli/version) and prints a single stderr warning when behind. Fail-open, 3s timeout, stderr only so --json is unaffected. Skips version/help/no-arg, dev builds, and SRC_SKIP_VERSION_CHECK. Compares major/minor/patch only. Adds unit tests. Closes #930. Supersedes #1339, #1343. --- cmd/src/main.go | 4 + cmd/src/version_check.go | 135 +++++++++++++++++++++++++++++++++ cmd/src/version_check_test.go | 139 ++++++++++++++++++++++++++++++++++ 3 files changed, 278 insertions(+) create mode 100644 cmd/src/version_check.go create mode 100644 cmd/src/version_check_test.go diff --git a/cmd/src/main.go b/cmd/src/main.go index 8635301b8a..3bf43b18da 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -41,6 +41,10 @@ func main() { log.SetFlags(0) log.SetPrefix("") + // Best-effort warning if src-cli is behind the version recommended by the + // configured instance. Fail-open, bounded by a short timeout, stderr only. + maybeWarnVersion(os.Args[1:]) + ranMigratedCmd, exitCode, err := maybeRunMigratedCommand() if ranMigratedCmd { if err != nil { diff --git a/cmd/src/version_check.go b/cmd/src/version_check.go new file mode 100644 index 0000000000..820a823f31 --- /dev/null +++ b/cmd/src/version_check.go @@ -0,0 +1,135 @@ +package main + +import ( + "context" + "fmt" + "os" + "strconv" + "strings" + "time" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/version" +) + +// versionCheckTimeout bounds the best-effort recommended-version lookup so it +// never noticeably delays a command. +const versionCheckTimeout = 3 * time.Second + +// maybeWarnVersion performs a best-effort check of the running src-cli version +// against the version recommended by the configured Sourcegraph instance and +// prints a single warning to stderr if src-cli is behind. +// +// It is entirely fail-open: any error (missing config, network failure, +// unreachable instance, unparseable version) results in no output. It writes +// only to stderr, so --json output on stdout is unaffected. +func maybeWarnVersion(args []string) { + if skipVersionCheck(args) { + return + } + + // Read config independently of command dispatch. Note: this runs before + // flag parsing, so -endpoint/-config flags are not honored here; the + // endpoint is resolved from SRC_ENDPOINT, the config file, or the default. + cfg, err := readConfig() + if err != nil { + return // fail-open: missing or invalid config + } + + ctx, cancel := context.WithTimeout(context.Background(), versionCheckTimeout) + defer cancel() + + client := cfg.apiClient(&api.Flags{}, os.Stderr) + recommended, err := getRecommendedVersion(ctx, client) + if err != nil || recommended == "" { + return // fail-open: network error, unreachable, or unsupported instance + } + + if isOlderVersion(version.BuildTag, recommended) { + fmt.Fprintf(os.Stderr, + "warning: src-cli v%s is older than the version recommended by your Sourcegraph instance (v%s). "+ + "Run `src version` for details, or set SRC_SKIP_VERSION_CHECK=1 to silence this.\n", + version.BuildTag, recommended) + } +} + +// skipVersionCheck reports whether the version check should be skipped for this +// invocation. Dev builds, an explicit opt-out env var, and +// version/help/no-arg invocations are all skipped. +func skipVersionCheck(args []string) bool { + // Dev builds have no meaningful version to compare. + if version.BuildTag == version.DefaultBuildTag { + return true + } + + // Explicit opt-out. + if _, ok := os.LookupEnv("SRC_SKIP_VERSION_CHECK"); ok { + return true + } + + // No subcommand: `src` alone just prints usage. + if len(args) == 0 { + return true + } + + // version and help invocations already surface version info / need no nag. + for _, arg := range args { + switch arg { + case "version", "help", "-h", "-help", "--help": + return true + } + } + + return false +} + +// isOlderVersion reports whether current is strictly older than recommended, +// comparing only major/minor/patch so prereleases do not trigger spurious +// warnings. If either version is unparseable it returns false (fail-open). +func isOlderVersion(current, recommended string) bool { + cMaj, cMin, cPatch, ok := parseVersion(current) + if !ok { + return false + } + rMaj, rMin, rPatch, ok := parseVersion(recommended) + if !ok { + return false + } + + if cMaj != rMaj { + return cMaj < rMaj + } + if cMin != rMin { + return cMin < rMin + } + return cPatch < rPatch +} + +// parseVersion extracts the major, minor, and patch components from a semver +// string, tolerating a leading "v" and ignoring any prerelease or build +// metadata suffix (e.g. "v1.2.3-rc1+meta" -> 1, 2, 3). +func parseVersion(s string) (major, minor, patch int, ok bool) { + s = strings.TrimPrefix(strings.TrimSpace(s), "v") + + // Drop prerelease and build metadata: 1.2.3-rc1+meta -> 1.2.3 + if i := strings.IndexAny(s, "-+"); i >= 0 { + s = s[:i] + } + + parts := strings.SplitN(s, ".", 3) + if len(parts) != 3 { + return 0, 0, 0, false + } + + var err error + if major, err = strconv.Atoi(parts[0]); err != nil { + return 0, 0, 0, false + } + if minor, err = strconv.Atoi(parts[1]); err != nil { + return 0, 0, 0, false + } + if patch, err = strconv.Atoi(parts[2]); err != nil { + return 0, 0, 0, false + } + return major, minor, patch, true +} diff --git a/cmd/src/version_check_test.go b/cmd/src/version_check_test.go new file mode 100644 index 0000000000..83b8d1fea1 --- /dev/null +++ b/cmd/src/version_check_test.go @@ -0,0 +1,139 @@ +package main + +import ( + "os" + "testing" + + "github.com/sourcegraph/src-cli/internal/version" +) + +func TestParseVersion(t *testing.T) { + tests := []struct { + name string + in string + major, minor, patch int + ok bool + }{ + {"plain", "1.2.3", 1, 2, 3, true}, + {"leading v", "v1.2.3", 1, 2, 3, true}, + {"surrounding whitespace", " 1.2.3\n", 1, 2, 3, true}, + {"prerelease suffix ignored", "1.2.3-rc1", 1, 2, 3, true}, + {"build metadata ignored", "1.2.3+abc123", 1, 2, 3, true}, + {"prerelease and metadata ignored", "v1.2.3-rc1+abc", 1, 2, 3, true}, + {"multi-digit components", "10.20.30", 10, 20, 30, true}, + {"missing patch", "1.2", 0, 0, 0, false}, + {"extra component unparseable", "1.2.3.4", 0, 0, 0, false}, + {"empty", "", 0, 0, 0, false}, + {"non-numeric", "a.b.c", 0, 0, 0, false}, + {"partially numeric", "1.x.3", 0, 0, 0, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + maj, min, patch, ok := parseVersion(tt.in) + if ok != tt.ok { + t.Fatalf("parseVersion(%q) ok = %v, want %v", tt.in, ok, tt.ok) + } + if !tt.ok { + return // components are meaningless when ok is false + } + if maj != tt.major || min != tt.minor || patch != tt.patch { + t.Errorf("parseVersion(%q) = (%d, %d, %d), want (%d, %d, %d)", + tt.in, maj, min, patch, tt.major, tt.minor, tt.patch) + } + }) + } +} + +func TestIsOlderVersion(t *testing.T) { + tests := []struct { + name string + current string + recommended string + want bool + }{ + {"older patch", "1.2.3", "1.2.4", true}, + {"older minor", "1.2.3", "1.3.0", true}, + {"older major", "1.2.3", "2.0.0", true}, + {"equal", "1.2.3", "1.2.3", false}, + {"newer patch", "1.2.4", "1.2.3", false}, + {"newer major", "2.0.0", "1.9.9", false}, + {"prerelease on current, same core", "1.2.3-rc1", "1.2.3", false}, + {"prerelease on recommended, same core", "1.2.3", "1.2.3-rc1", false}, + {"leading v tolerated", "v1.2.3", "1.2.4", true}, + {"unparseable current fails open", "garbage", "1.2.3", false}, + {"unparseable recommended fails open", "1.2.3", "garbage", false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isOlderVersion(tt.current, tt.recommended); got != tt.want { + t.Errorf("isOlderVersion(%q, %q) = %v, want %v", + tt.current, tt.recommended, got, tt.want) + } + }) + } +} + +func TestSkipVersionCheck(t *testing.T) { + // Ensure the opt-out env var is absent for the non-env cases, restoring + // whatever the developer's environment had afterward. + if orig, ok := os.LookupEnv("SRC_SKIP_VERSION_CHECK"); ok { + os.Unsetenv("SRC_SKIP_VERSION_CHECK") + t.Cleanup(func() { os.Setenv("SRC_SKIP_VERSION_CHECK", orig) }) + } + + // Pretend this is a release build for everything except the dev-build case. + origTag := version.BuildTag + t.Cleanup(func() { version.BuildTag = origTag }) + version.BuildTag = "5.1.2" + + t.Run("dev build is skipped", func(t *testing.T) { + version.BuildTag = version.DefaultBuildTag + defer func() { version.BuildTag = "5.1.2" }() + + if !skipVersionCheck([]string{"search", "foo"}) { + t.Error("expected dev build to be skipped") + } + }) + + t.Run("opt-out env var is skipped", func(t *testing.T) { + t.Setenv("SRC_SKIP_VERSION_CHECK", "1") + + if !skipVersionCheck([]string{"search", "foo"}) { + t.Error("expected SRC_SKIP_VERSION_CHECK to skip the check") + } + }) + + t.Run("empty env value still counts as set", func(t *testing.T) { + t.Setenv("SRC_SKIP_VERSION_CHECK", "") + + if !skipVersionCheck([]string{"search", "foo"}) { + t.Error("expected a present-but-empty env var to skip the check") + } + }) + + argCases := []struct { + name string + args []string + want bool + }{ + {"no args", nil, true}, + {"version subcommand", []string{"version"}, true}, + {"help subcommand", []string{"help"}, true}, + {"-h flag", []string{"-h"}, true}, + {"-help flag", []string{"-help"}, true}, + {"--help flag", []string{"--help"}, true}, + {"version after global flag", []string{"-v", "version"}, true}, + {"normal command", []string{"search", "-json", "foo"}, false}, + {"normal multi-arg command", []string{"batch", "preview", "-f", "x.yaml"}, false}, + } + + for _, tt := range argCases { + t.Run(tt.name, func(t *testing.T) { + if got := skipVersionCheck(tt.args); got != tt.want { + t.Errorf("skipVersionCheck(%v) = %v, want %v", tt.args, got, tt.want) + } + }) + } +} From 150eedc8cf19540ea6caf4cda3f8cda524a16046 Mon Sep 17 00:00:00 2001 From: Marc LeBlanc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:37:05 -0600 Subject: [PATCH 2/6] fix: make the outdated-version warning safe to ship - Fix a nil pointer panic on every command in release builds: the check built its API client from a zero-value api.Flags. - Run the check after flags and config are resolved, so -endpoint and -config are honored and the right instance is asked. - Ask the instance at most once every 24 hours per endpoint, caching the answer, including a failed lookup, under the user cache directory, so an instance that does not answer cannot delay every command. - Compare versions with Masterminds/semver, which is already linked into the binary, instead of a hand-written parser. - Skip 'src version' by its parsed subcommand instead of scanning every argument for the word. - Test the check end to end against a fake instance. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp --- CHANGELOG.md | 2 + cmd/src/cmd.go | 1 + cmd/src/main.go | 4 - cmd/src/run_migration_compat.go | 1 + cmd/src/version_check.go | 167 ++++++++++--------------- cmd/src/version_check_test.go | 215 ++++++++++++++++++-------------- go.mod | 2 +- 7 files changed, 191 insertions(+), 201 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bd9a46ff0..4700ef0041 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- `src` now prints a warning to stderr when it is older than the version recommended by your Sourcegraph instance. The recommended version is looked up at most once every 24 hours per instance. To disable the check, set the `SRC_SKIP_VERSION_CHECK` environment variable to any non-blank string. [#930](https://github.com/sourcegraph/src-cli/issues/930) + ### Changed ### Fixed diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 65d1d9982a..388ae09248 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -86,6 +86,7 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] if err != nil { log.Fatal("reading config: ", err) } + maybeWarnOutdatedVersion(cfg, name) exitCode, err := runLegacy(cmd, flagSet) if err != nil { diff --git a/cmd/src/main.go b/cmd/src/main.go index 3bf43b18da..8635301b8a 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -41,10 +41,6 @@ func main() { log.SetFlags(0) log.SetPrefix("") - // Best-effort warning if src-cli is behind the version recommended by the - // configured instance. Fail-open, bounded by a short timeout, stderr only. - maybeWarnVersion(os.Args[1:]) - ranMigratedCmd, exitCode, err := maybeRunMigratedCommand() if ranMigratedCmd { if err != nil { diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index 6671b07da3..cabce4f97e 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -44,6 +44,7 @@ func maybeRunMigratedCommand() (isMigrated bool, exitCode int, err error) { if err != nil { log.Fatal("reading config: ", err) } + maybeWarnOutdatedVersion(cfg, subCommand) exitCode, err = runMigrated() return diff --git a/cmd/src/version_check.go b/cmd/src/version_check.go index 820a823f31..6c6ae1238e 100644 --- a/cmd/src/version_check.go +++ b/cmd/src/version_check.go @@ -3,133 +3,96 @@ package main import ( "context" "fmt" + "io" + "net/url" "os" - "strconv" - "strings" + "path/filepath" "time" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/Masterminds/semver" + "github.com/sourcegraph/src-cli/internal/version" ) -// versionCheckTimeout bounds the best-effort recommended-version lookup so it -// never noticeably delays a command. -const versionCheckTimeout = 3 * time.Second +const ( + // versionCheckTimeout bounds the recommended-version lookup, which runs + // before the command the user asked for. + versionCheckTimeout = 3 * time.Second + + // versionCheckInterval is how long the result of a lookup is reused before + // the instance is asked again. + versionCheckInterval = 24 * time.Hour +) -// maybeWarnVersion performs a best-effort check of the running src-cli version -// against the version recommended by the configured Sourcegraph instance and -// prints a single warning to stderr if src-cli is behind. +// maybeWarnOutdatedVersion prints a warning to stderr when src-cli is older +// than the version recommended by the configured Sourcegraph instance. // -// It is entirely fail-open: any error (missing config, network failure, -// unreachable instance, unparseable version) results in no output. It writes -// only to stderr, so --json output on stdout is unaffected. -func maybeWarnVersion(args []string) { - if skipVersionCheck(args) { +// It never fails the command: an unreachable instance, an unparseable version, +// or an unwritable cache all result in no warning. +func maybeWarnOutdatedVersion(cfg *config, subcommand string) { + if skipVersionCheck(subcommand) { return } - - // Read config independently of command dispatch. Note: this runs before - // flag parsing, so -endpoint/-config flags are not honored here; the - // endpoint is resolved from SRC_ENDPOINT, the config file, or the default. - cfg, err := readConfig() + cacheDir, err := os.UserCacheDir() if err != nil { - return // fail-open: missing or invalid config - } - - ctx, cancel := context.WithTimeout(context.Background(), versionCheckTimeout) - defer cancel() - - client := cfg.apiClient(&api.Flags{}, os.Stderr) - recommended, err := getRecommendedVersion(ctx, client) - if err != nil || recommended == "" { - return // fail-open: network error, unreachable, or unsupported instance + return } - - if isOlderVersion(version.BuildTag, recommended) { - fmt.Fprintf(os.Stderr, - "warning: src-cli v%s is older than the version recommended by your Sourcegraph instance (v%s). "+ - "Run `src version` for details, or set SRC_SKIP_VERSION_CHECK=1 to silence this.\n", - version.BuildTag, recommended) + cachePath := filepath.Join(cacheDir, "sourcegraph", "src-cli", "recommended-version-"+url.QueryEscape(cfg.endpointURL.String())) + if warning := outdatedVersionWarning(cfg, cachePath); warning != "" { + fmt.Fprintln(os.Stderr, warning) } } -// skipVersionCheck reports whether the version check should be skipped for this -// invocation. Dev builds, an explicit opt-out env var, and -// version/help/no-arg invocations are all skipped. -func skipVersionCheck(args []string) bool { - // Dev builds have no meaningful version to compare. - if version.BuildTag == version.DefaultBuildTag { - return true - } - - // Explicit opt-out. - if _, ok := os.LookupEnv("SRC_SKIP_VERSION_CHECK"); ok { - return true - } - - // No subcommand: `src` alone just prints usage. - if len(args) == 0 { - return true - } - - // version and help invocations already surface version info / need no nag. - for _, arg := range args { - switch arg { - case "version", "help", "-h", "-help", "--help": - return true - } - } - - return false +// skipVersionCheck reports whether the version check is disabled, has no +// version to compare, or is redundant because the command is 'src version'. +func skipVersionCheck(subcommand string) bool { + return os.Getenv("SRC_SKIP_VERSION_CHECK") != "" || + version.BuildTag == version.DefaultBuildTag || + subcommand == "version" } -// isOlderVersion reports whether current is strictly older than recommended, -// comparing only major/minor/patch so prereleases do not trigger spurious -// warnings. If either version is unparseable it returns false (fail-open). -func isOlderVersion(current, recommended string) bool { - cMaj, cMin, cPatch, ok := parseVersion(current) - if !ok { - return false - } - rMaj, rMin, rPatch, ok := parseVersion(recommended) - if !ok { - return false +// outdatedVersionWarning returns the warning to print, or "" when src-cli is +// not known to be older than the version the instance recommends. +func outdatedVersionWarning(cfg *config, cachePath string) string { + current, err := semver.NewVersion(version.BuildTag) + if err != nil { + return "" } - - if cMaj != rMaj { - return cMaj < rMaj + recommended, err := semver.NewVersion(recommendedVersion(cfg, cachePath)) + if err != nil { + return "" } - if cMin != rMin { - return cMin < rMin + if !current.LessThan(recommended) { + return "" } - return cPatch < rPatch + return fmt.Sprintf("⚠️ Warning: src-cli %s is older than %s, the version recommended by %s. "+ + "To upgrade, see https://github.com/sourcegraph/src-cli#installation. "+ + "To silence this warning, set SRC_SKIP_VERSION_CHECK=1.", + current, recommended, cfg.endpointURL) } -// parseVersion extracts the major, minor, and patch components from a semver -// string, tolerating a leading "v" and ignoring any prerelease or build -// metadata suffix (e.g. "v1.2.3-rc1+meta" -> 1, 2, 3). -func parseVersion(s string) (major, minor, patch int, ok bool) { - s = strings.TrimPrefix(strings.TrimSpace(s), "v") - - // Drop prerelease and build metadata: 1.2.3-rc1+meta -> 1.2.3 - if i := strings.IndexAny(s, "-+"); i >= 0 { - s = s[:i] +// recommendedVersion returns the src-cli version recommended by the configured +// instance, or "" when it is unknown. The answer is cached in the file at +// cachePath for versionCheckInterval, so most commands make no extra request. +func recommendedVersion(cfg *config, cachePath string) string { + if info, err := os.Stat(cachePath); err == nil && time.Since(info.ModTime()) < versionCheckInterval { + cached, _ := os.ReadFile(cachePath) + return string(cached) } - parts := strings.SplitN(s, ".", 3) - if len(parts) != 3 { - return 0, 0, 0, false + // Record the attempt before the lookup, so that an instance that does not + // answer delays one command per versionCheckInterval instead of every + // command. Without a writable cache there is no such bound, so do not look. + if os.MkdirAll(filepath.Dir(cachePath), 0o700) != nil || os.WriteFile(cachePath, nil, 0o600) != nil { + return "" } - var err error - if major, err = strconv.Atoi(parts[0]); err != nil { - return 0, 0, 0, false - } - if minor, err = strconv.Atoi(parts[1]); err != nil { - return 0, 0, 0, false - } - if patch, err = strconv.Atoi(parts[2]); err != nil { - return 0, 0, 0, false + ctx, cancel := context.WithTimeout(context.Background(), versionCheckTimeout) + defer cancel() + recommended, err := getRecommendedVersion(ctx, cfg.apiClient(nil, io.Discard)) + if err != nil { + return "" } - return major, minor, patch, true + _ = os.WriteFile(cachePath, []byte(recommended), 0o600) + return recommended } diff --git a/cmd/src/version_check_test.go b/cmd/src/version_check_test.go index 83b8d1fea1..765956880d 100644 --- a/cmd/src/version_check_test.go +++ b/cmd/src/version_check_test.go @@ -1,138 +1,165 @@ package main import ( + "fmt" + "net/http" + "net/http/httptest" "os" + "path/filepath" + "strings" "testing" + "time" "github.com/sourcegraph/src-cli/internal/version" ) -func TestParseVersion(t *testing.T) { - tests := []struct { - name string - in string - major, minor, patch int - ok bool - }{ - {"plain", "1.2.3", 1, 2, 3, true}, - {"leading v", "v1.2.3", 1, 2, 3, true}, - {"surrounding whitespace", " 1.2.3\n", 1, 2, 3, true}, - {"prerelease suffix ignored", "1.2.3-rc1", 1, 2, 3, true}, - {"build metadata ignored", "1.2.3+abc123", 1, 2, 3, true}, - {"prerelease and metadata ignored", "v1.2.3-rc1+abc", 1, 2, 3, true}, - {"multi-digit components", "10.20.30", 10, 20, 30, true}, - {"missing patch", "1.2", 0, 0, 0, false}, - {"extra component unparseable", "1.2.3.4", 0, 0, 0, false}, - {"empty", "", 0, 0, 0, false}, - {"non-numeric", "a.b.c", 0, 0, 0, false}, - {"partially numeric", "1.x.3", 0, 0, 0, false}, - } +// setBuildTag pretends that src-cli was built as the given release. +func setBuildTag(t *testing.T, buildTag string) { + t.Helper() + original := version.BuildTag + t.Cleanup(func() { version.BuildTag = original }) + version.BuildTag = buildTag +} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - maj, min, patch, ok := parseVersion(tt.in) - if ok != tt.ok { - t.Fatalf("parseVersion(%q) ok = %v, want %v", tt.in, ok, tt.ok) - } - if !tt.ok { - return // components are meaningless when ok is false - } - if maj != tt.major || min != tt.minor || patch != tt.patch { - t.Errorf("parseVersion(%q) = (%d, %d, %d), want (%d, %d, %d)", - tt.in, maj, min, patch, tt.major, tt.minor, tt.patch) - } - }) - } +// versionServer is a fake Sourcegraph instance that answers every request with +// the given status and recommended version, and counts the requests it gets. +func versionServer(t *testing.T, status int, recommended string) (cfg *config, requests *int) { + t.Helper() + requests = new(int) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *requests++ + if r.URL.Path != "/.api/src-cli/version" { + t.Errorf("unexpected request path %q", r.URL.Path) + } + w.WriteHeader(status) + fmt.Fprintf(w, `{"version": %q}`, recommended) + })) + t.Cleanup(server.Close) + return &config{endpointURL: mustParseURL(t, server.URL), accessToken: "token"}, requests } -func TestIsOlderVersion(t *testing.T) { +func TestOutdatedVersionWarning(t *testing.T) { tests := []struct { name string current string + status int recommended string - want bool + wantWarning bool }{ - {"older patch", "1.2.3", "1.2.4", true}, - {"older minor", "1.2.3", "1.3.0", true}, - {"older major", "1.2.3", "2.0.0", true}, - {"equal", "1.2.3", "1.2.3", false}, - {"newer patch", "1.2.4", "1.2.3", false}, - {"newer major", "2.0.0", "1.9.9", false}, - {"prerelease on current, same core", "1.2.3-rc1", "1.2.3", false}, - {"prerelease on recommended, same core", "1.2.3", "1.2.3-rc1", false}, - {"leading v tolerated", "v1.2.3", "1.2.4", true}, - {"unparseable current fails open", "garbage", "1.2.3", false}, - {"unparseable recommended fails open", "1.2.3", "garbage", false}, + {name: "older patch", current: "6.4.1", status: http.StatusOK, recommended: "6.4.2", wantWarning: true}, + {name: "older, compared as numbers not strings", current: "9.9.9", status: http.StatusOK, recommended: "10.0.0", wantWarning: true}, + {name: "newer, compared as numbers not strings", current: "10.0.0", status: http.StatusOK, recommended: "9.9.9"}, + {name: "same version", current: "6.4.2", status: http.StatusOK, recommended: "6.4.2"}, + {name: "instance does not recommend a version", current: "6.4.2", status: http.StatusNotFound}, + {name: "instance returns an error", current: "6.4.2", status: http.StatusInternalServerError, recommended: "7.0.0"}, + {name: "instance returns an unparseable version", current: "6.4.2", status: http.StatusOK, recommended: "latest"}, + {name: "running an unparseable version", current: "custom-build", status: http.StatusOK, recommended: "7.0.0"}, } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := isOlderVersion(tt.current, tt.recommended); got != tt.want { - t.Errorf("isOlderVersion(%q, %q) = %v, want %v", - tt.current, tt.recommended, got, tt.want) + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, test.current) + cfg, _ := versionServer(t, test.status, test.recommended) + + warning := outdatedVersionWarning(cfg, filepath.Join(t.TempDir(), "recommended-version")) + + if !test.wantWarning { + if warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + return + } + for _, want := range []string{test.current, test.recommended, cfg.endpointURL.String(), "SRC_SKIP_VERSION_CHECK"} { + if !strings.Contains(warning, want) { + t.Errorf("warning %q does not mention %q", warning, want) + } } }) } } -func TestSkipVersionCheck(t *testing.T) { - // Ensure the opt-out env var is absent for the non-env cases, restoring - // whatever the developer's environment had afterward. - if orig, ok := os.LookupEnv("SRC_SKIP_VERSION_CHECK"); ok { - os.Unsetenv("SRC_SKIP_VERSION_CHECK") - t.Cleanup(func() { os.Setenv("SRC_SKIP_VERSION_CHECK", orig) }) +func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { + makeStale := func(t *testing.T, cachePath string) { + t.Helper() + stale := time.Now().Add(-versionCheckInterval - time.Minute) + if err := os.Chtimes(cachePath, stale, stale); err != nil { + t.Fatal(err) + } } - // Pretend this is a release build for everything except the dev-build case. - origTag := version.BuildTag - t.Cleanup(func() { version.BuildTag = origTag }) - version.BuildTag = "5.1.2" + t.Run("answer is reused until it is stale", func(t *testing.T) { + setBuildTag(t, "6.4.1") + cfg, requests := versionServer(t, http.StatusOK, "6.4.2") + cachePath := filepath.Join(t.TempDir(), "nested", "recommended-version") - t.Run("dev build is skipped", func(t *testing.T) { - version.BuildTag = version.DefaultBuildTag - defer func() { version.BuildTag = "5.1.2" }() + for range 2 { + if warning := outdatedVersionWarning(cfg, cachePath); warning == "" { + t.Fatal("got no warning, want one on every command") + } + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } - if !skipVersionCheck([]string{"search", "foo"}) { - t.Error("expected dev build to be skipped") + makeStale(t, cachePath) + outdatedVersionWarning(cfg, cachePath) + if *requests != 2 { + t.Fatalf("got %d requests after the cache went stale, want 2", *requests) } }) - t.Run("opt-out env var is skipped", func(t *testing.T) { - t.Setenv("SRC_SKIP_VERSION_CHECK", "1") + t.Run("failed lookup is not retried until it is stale", func(t *testing.T) { + setBuildTag(t, "6.4.1") + cfg, requests := versionServer(t, http.StatusInternalServerError, "") + cachePath := filepath.Join(t.TempDir(), "recommended-version") - if !skipVersionCheck([]string{"search", "foo"}) { - t.Error("expected SRC_SKIP_VERSION_CHECK to skip the check") + for range 2 { + if warning := outdatedVersionWarning(cfg, cachePath); warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) } }) - t.Run("empty env value still counts as set", func(t *testing.T) { - t.Setenv("SRC_SKIP_VERSION_CHECK", "") + t.Run("no lookup without a writable cache", func(t *testing.T) { + setBuildTag(t, "6.4.1") + cfg, requests := versionServer(t, http.StatusOK, "6.4.2") + // A regular file where the cache directory should be. + blocker := filepath.Join(t.TempDir(), "blocker") + if err := os.WriteFile(blocker, nil, 0o600); err != nil { + t.Fatal(err) + } - if !skipVersionCheck([]string{"search", "foo"}) { - t.Error("expected a present-but-empty env var to skip the check") + if warning := outdatedVersionWarning(cfg, filepath.Join(blocker, "recommended-version")); warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + if *requests != 0 { + t.Fatalf("got %d requests, want 0", *requests) } }) +} - argCases := []struct { - name string - args []string - want bool +func TestSkipVersionCheck(t *testing.T) { + tests := []struct { + name string + buildTag string + optOut string + subcommand string + want bool }{ - {"no args", nil, true}, - {"version subcommand", []string{"version"}, true}, - {"help subcommand", []string{"help"}, true}, - {"-h flag", []string{"-h"}, true}, - {"-help flag", []string{"-help"}, true}, - {"--help flag", []string{"--help"}, true}, - {"version after global flag", []string{"-v", "version"}, true}, - {"normal command", []string{"search", "-json", "foo"}, false}, - {"normal multi-arg command", []string{"batch", "preview", "-f", "x.yaml"}, false}, + {name: "release build running a command", buildTag: "6.4.2", subcommand: "search", want: false}, + {name: "opted out", buildTag: "6.4.2", optOut: "1", subcommand: "search", want: true}, + {name: "dev build", buildTag: version.DefaultBuildTag, subcommand: "search", want: true}, + {name: "src version", buildTag: "6.4.2", subcommand: "version", want: true}, } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, test.buildTag) + t.Setenv("SRC_SKIP_VERSION_CHECK", test.optOut) - for _, tt := range argCases { - t.Run(tt.name, func(t *testing.T) { - if got := skipVersionCheck(tt.args); got != tt.want { - t.Errorf("skipVersionCheck(%v) = %v, want %v", tt.args, got, tt.want) + if got := skipVersionCheck(test.subcommand); got != test.want { + t.Errorf("skipVersionCheck(%q) = %v, want %v", test.subcommand, got, test.want) } }) } diff --git a/go.mod b/go.mod index e90ea68b3f..3a1dfd626f 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.27.3 require ( cloud.google.com/go/storage v1.70.0 + github.com/Masterminds/semver v1.5.0 github.com/aws/aws-sdk-go-v2/config v1.33.12 github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0 github.com/aws/aws-sdk-go-v2/service/eks v1.105.1 @@ -57,7 +58,6 @@ require ( github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 // indirect - github.com/Masterminds/semver v1.5.0 // indirect github.com/alecthomas/chroma/v2 v2.27.0 // indirect github.com/aws/aws-sdk-go-v2 v1.47.5 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.20.12 // indirect From 05700b31326a09833e1fec9531806c075e1412c1 Mon Sep 17 00:00:00 2001 From: Marc LeBlanc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:56:42 -0600 Subject: [PATCH 3/6] fix: run the version check with the command's own API client The check ran before the subcommand's flags were parsed, so it ignored -insecure-skip-verify and never warned on instances with an untrusted certificate. It also ran twice for nested legacy commands such as 'src repos list', which printed the warning twice. Run it once per process from config.apiClient instead, using the client the command asked for. Commands that never talk to the instance, such as 'src search -h', no longer trigger a lookup. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp --- cmd/src/cmd.go | 1 - cmd/src/main.go | 8 ++- cmd/src/run_migration_compat.go | 1 - cmd/src/version_check.go | 33 +++++++---- cmd/src/version_check_test.go | 102 ++++++++++++++++++++++++++++---- 5 files changed, 117 insertions(+), 28 deletions(-) diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 388ae09248..65d1d9982a 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -86,7 +86,6 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] if err != nil { log.Fatal("reading config: ", err) } - maybeWarnOutdatedVersion(cfg, name) exitCode, err := runLegacy(cmd, flagSet) if err != nil { diff --git a/cmd/src/main.go b/cmd/src/main.go index 8635301b8a..cf941eeb96 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -156,7 +156,13 @@ func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { } } - return api.NewClient(opts) + client := api.NewClient(opts) + // Checked here rather than before the command is dispatched, so that the + // lookup uses the command's own flags, such as -insecure-skip-verify. + warnOutdatedVersionOnce.Do(func() { + maybeWarnOutdatedVersion(client, c.endpointURL, flag.CommandLine.Arg(0)) + }) + return client } // readConfig reads the config file from the given path. diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index cabce4f97e..6671b07da3 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -44,7 +44,6 @@ func maybeRunMigratedCommand() (isMigrated bool, exitCode int, err error) { if err != nil { log.Fatal("reading config: ", err) } - maybeWarnOutdatedVersion(cfg, subCommand) exitCode, err = runMigrated() return diff --git a/cmd/src/version_check.go b/cmd/src/version_check.go index 6c6ae1238e..21cf575fac 100644 --- a/cmd/src/version_check.go +++ b/cmd/src/version_check.go @@ -3,14 +3,15 @@ package main import ( "context" "fmt" - "io" "net/url" "os" "path/filepath" + "sync" "time" "github.com/Masterminds/semver" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/version" ) @@ -24,12 +25,17 @@ const ( versionCheckInterval = 24 * time.Hour ) +// warnOutdatedVersionOnce limits the check to once per run of src-cli, however +// many API clients the command creates. +var warnOutdatedVersionOnce sync.Once + // maybeWarnOutdatedVersion prints a warning to stderr when src-cli is older -// than the version recommended by the configured Sourcegraph instance. +// than the version recommended by the Sourcegraph instance at endpointURL, +// which it asks using client. // // It never fails the command: an unreachable instance, an unparseable version, // or an unwritable cache all result in no warning. -func maybeWarnOutdatedVersion(cfg *config, subcommand string) { +func maybeWarnOutdatedVersion(client api.Client, endpointURL *url.URL, subcommand string) { if skipVersionCheck(subcommand) { return } @@ -37,8 +43,8 @@ func maybeWarnOutdatedVersion(cfg *config, subcommand string) { if err != nil { return } - cachePath := filepath.Join(cacheDir, "sourcegraph", "src-cli", "recommended-version-"+url.QueryEscape(cfg.endpointURL.String())) - if warning := outdatedVersionWarning(cfg, cachePath); warning != "" { + cachePath := filepath.Join(cacheDir, "sourcegraph", "src-cli", "recommended-version-"+url.QueryEscape(endpointURL.String())) + if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning != "" { fmt.Fprintln(os.Stderr, warning) } } @@ -53,12 +59,12 @@ func skipVersionCheck(subcommand string) bool { // outdatedVersionWarning returns the warning to print, or "" when src-cli is // not known to be older than the version the instance recommends. -func outdatedVersionWarning(cfg *config, cachePath string) string { +func outdatedVersionWarning(client api.Client, endpointURL *url.URL, cachePath string) string { current, err := semver.NewVersion(version.BuildTag) if err != nil { return "" } - recommended, err := semver.NewVersion(recommendedVersion(cfg, cachePath)) + recommended, err := semver.NewVersion(recommendedVersion(client, cachePath)) if err != nil { return "" } @@ -68,13 +74,14 @@ func outdatedVersionWarning(cfg *config, cachePath string) string { return fmt.Sprintf("⚠️ Warning: src-cli %s is older than %s, the version recommended by %s. "+ "To upgrade, see https://github.com/sourcegraph/src-cli#installation. "+ "To silence this warning, set SRC_SKIP_VERSION_CHECK=1.", - current, recommended, cfg.endpointURL) + current, recommended, endpointURL) } -// recommendedVersion returns the src-cli version recommended by the configured -// instance, or "" when it is unknown. The answer is cached in the file at -// cachePath for versionCheckInterval, so most commands make no extra request. -func recommendedVersion(cfg *config, cachePath string) string { +// recommendedVersion returns the src-cli version recommended by the instance +// that client talks to, or "" when it is unknown. The answer is cached in the +// file at cachePath for versionCheckInterval, so most commands make no extra +// request. +func recommendedVersion(client api.Client, cachePath string) string { if info, err := os.Stat(cachePath); err == nil && time.Since(info.ModTime()) < versionCheckInterval { cached, _ := os.ReadFile(cachePath) return string(cached) @@ -89,7 +96,7 @@ func recommendedVersion(cfg *config, cachePath string) string { ctx, cancel := context.WithTimeout(context.Background(), versionCheckTimeout) defer cancel() - recommended, err := getRecommendedVersion(ctx, cfg.apiClient(nil, io.Discard)) + recommended, err := getRecommendedVersion(ctx, client) if err != nil { return "" } diff --git a/cmd/src/version_check_test.go b/cmd/src/version_check_test.go index 765956880d..a65847aada 100644 --- a/cmd/src/version_check_test.go +++ b/cmd/src/version_check_test.go @@ -2,14 +2,19 @@ package main import ( "fmt" + "io" + "log" "net/http" "net/http/httptest" + "net/url" "os" "path/filepath" "strings" + "sync" "testing" "time" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/version" ) @@ -23,7 +28,7 @@ func setBuildTag(t *testing.T, buildTag string) { // versionServer is a fake Sourcegraph instance that answers every request with // the given status and recommended version, and counts the requests it gets. -func versionServer(t *testing.T, status int, recommended string) (cfg *config, requests *int) { +func versionServer(t *testing.T, status int, recommended string) (client api.Client, endpointURL *url.URL, requests *int) { t.Helper() requests = new(int) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -35,7 +40,8 @@ func versionServer(t *testing.T, status int, recommended string) (cfg *config, r fmt.Fprintf(w, `{"version": %q}`, recommended) })) t.Cleanup(server.Close) - return &config{endpointURL: mustParseURL(t, server.URL), accessToken: "token"}, requests + endpointURL = mustParseURL(t, server.URL) + return api.NewClient(api.ClientOpts{EndpointURL: endpointURL, AccessToken: "token", Out: io.Discard}), endpointURL, requests } func TestOutdatedVersionWarning(t *testing.T) { @@ -58,9 +64,9 @@ func TestOutdatedVersionWarning(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { setBuildTag(t, test.current) - cfg, _ := versionServer(t, test.status, test.recommended) + client, endpointURL, _ := versionServer(t, test.status, test.recommended) - warning := outdatedVersionWarning(cfg, filepath.Join(t.TempDir(), "recommended-version")) + warning := outdatedVersionWarning(client, endpointURL, filepath.Join(t.TempDir(), "recommended-version")) if !test.wantWarning { if warning != "" { @@ -68,7 +74,7 @@ func TestOutdatedVersionWarning(t *testing.T) { } return } - for _, want := range []string{test.current, test.recommended, cfg.endpointURL.String(), "SRC_SKIP_VERSION_CHECK"} { + for _, want := range []string{test.current, test.recommended, endpointURL.String(), "SRC_SKIP_VERSION_CHECK"} { if !strings.Contains(warning, want) { t.Errorf("warning %q does not mention %q", warning, want) } @@ -88,11 +94,11 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { t.Run("answer is reused until it is stale", func(t *testing.T) { setBuildTag(t, "6.4.1") - cfg, requests := versionServer(t, http.StatusOK, "6.4.2") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") cachePath := filepath.Join(t.TempDir(), "nested", "recommended-version") for range 2 { - if warning := outdatedVersionWarning(cfg, cachePath); warning == "" { + if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning == "" { t.Fatal("got no warning, want one on every command") } } @@ -101,19 +107,36 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { } makeStale(t, cachePath) - outdatedVersionWarning(cfg, cachePath) + outdatedVersionWarning(client, endpointURL, cachePath) if *requests != 2 { t.Fatalf("got %d requests after the cache went stale, want 2", *requests) } }) + t.Run("upgrading silences the warning without another lookup", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") + cachePath := filepath.Join(t.TempDir(), "recommended-version") + if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning == "" { + t.Fatal("got no warning before upgrading, want one") + } + + setBuildTag(t, "6.4.2") + if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning != "" { + t.Fatalf("got warning %q after upgrading, want none", warning) + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } + }) + t.Run("failed lookup is not retried until it is stale", func(t *testing.T) { setBuildTag(t, "6.4.1") - cfg, requests := versionServer(t, http.StatusInternalServerError, "") + client, endpointURL, requests := versionServer(t, http.StatusInternalServerError, "") cachePath := filepath.Join(t.TempDir(), "recommended-version") for range 2 { - if warning := outdatedVersionWarning(cfg, cachePath); warning != "" { + if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning != "" { t.Fatalf("got warning %q, want none", warning) } } @@ -124,14 +147,14 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { t.Run("no lookup without a writable cache", func(t *testing.T) { setBuildTag(t, "6.4.1") - cfg, requests := versionServer(t, http.StatusOK, "6.4.2") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") // A regular file where the cache directory should be. blocker := filepath.Join(t.TempDir(), "blocker") if err := os.WriteFile(blocker, nil, 0o600); err != nil { t.Fatal(err) } - if warning := outdatedVersionWarning(cfg, filepath.Join(blocker, "recommended-version")); warning != "" { + if warning := outdatedVersionWarning(client, endpointURL, filepath.Join(blocker, "recommended-version")); warning != "" { t.Fatalf("got warning %q, want none", warning) } if *requests != 0 { @@ -164,3 +187,58 @@ func TestSkipVersionCheck(t *testing.T) { }) } } + +// TestAPIClientWarnsAboutOutdatedVersion covers where the check is hooked in: +// config.apiClient, which every command that talks to the instance calls with +// its own flags. +func TestAPIClientWarnsAboutOutdatedVersion(t *testing.T) { + tests := []struct { + name string + insecureSkipVerify bool + wantWarnings int + }{ + {name: "self-signed instance with -insecure-skip-verify is warned once, however many clients", insecureSkipVerify: true, wantWarnings: 1}, + {name: "self-signed instance without -insecure-skip-verify is not trusted", insecureSkipVerify: false, wantWarnings: 0}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, "6.4.1") + t.Setenv("SRC_SKIP_VERSION_CHECK", "") + // Wherever os.UserCacheDir looks on this operating system. + for _, name := range []string{"HOME", "XDG_CACHE_HOME", "LocalAppData"} { + t.Setenv(name, t.TempDir()) + } + warnOutdatedVersionOnce = sync.Once{} + t.Cleanup(func() { warnOutdatedVersionOnce = sync.Once{} }) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"version": "6.4.2"}`) + })) + server.Config.ErrorLog = log.New(io.Discard, "", 0) // rejected certificates + server.StartTLS() + t.Cleanup(server.Close) + cfg := &config{endpointURL: mustParseURL(t, server.URL), accessToken: "token"} + flags := api.NewFlagsFromValues(false, false, false, test.insecureSkipVerify, false) + + stderr := os.Stderr + t.Cleanup(func() { os.Stderr = stderr }) + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = writer + for range 2 { + cfg.apiClient(flags, io.Discard) + } + writer.Close() + output, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + + if got := strings.Count(string(output), "Warning: src-cli 6.4.1 is older than 6.4.2"); got != test.wantWarnings { + t.Errorf("got %d warnings, want %d; stderr: %q", got, test.wantWarnings, output) + } + }) + } +} From 71363c82b4753d0859101e940aa446814422821b Mon Sep 17 00:00:00 2001 From: Marc LeBlanc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:58:01 -0600 Subject: [PATCH 4/6] docs: document the outdated-version warning and SRC_SKIP_VERSION_CHECK --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 37100691a3..c4a716f9f6 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,10 @@ You can then invoke it via `src-cli`. `src` waits up to 1 minute for the server to start responding to a request. To change this, set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to a duration such as `30s` or `10m`, or to `0` to disable the timeout. This timeout only applies until the server sends its response headers — responses that stream data for a long time, such as large search job results, are not interrupted. +## Version check + +`src` prints a warning to stderr when it is older than the version recommended by your Sourcegraph instance. It asks the instance at most once every 24 hours, and the check never fails a command. To upgrade, see [Installation](#installation). To disable the check, set the `SRC_SKIP_VERSION_CHECK` environment variable to any non-blank string. + ## Telemetry `src` includes the operating system and architecture in the `User-Agent` header sent to Sourcegraph. For example, running `src` version 3.21.10 on an x86-64 Linux host will result in this header: From 4a40d41b847d090b99d3c9cb563c8d03b6769d86 Mon Sep 17 00:00:00 2001 From: Marc LeBlanc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:42:47 -0600 Subject: [PATCH 5/6] feat: make 'src version' warn too, and refresh the cached version 'src version' was the one command that never warned. It now prints the warning from the answer it just got from the instance, and caches that answer, so the commands that follow warn about the same version. It still makes a single request, and 'src version -client-only' still makes none: the check that other commands get from config.apiClient keeps skipping 'src version'. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp --- cmd/src/version.go | 18 ++-- cmd/src/version_check.go | 69 +++++++++++---- cmd/src/version_check_test.go | 159 +++++++++++++++++++++++++--------- 3 files changed, 183 insertions(+), 63 deletions(-) diff --git a/cmd/src/version.go b/cmd/src/version.go index fad3a42f78..64d0659f44 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "net/url" "os" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -42,17 +43,19 @@ var versionCommand = clicompat.Wrap(&cli.Command{ HideVersion: true, Action: func(ctx context.Context, c *cli.Command) error { args := VersionArgs{ - Client: cfg.apiClient(clicompat.APIFlagsFromCmd(c), os.Stdout), - ClientOnly: c.Bool("client-only"), + Client: cfg.apiClient(clicompat.APIFlagsFromCmd(c), os.Stdout), + EndpointURL: cfg.endpointURL, + ClientOnly: c.Bool("client-only"), } return versionHandler(args) }, }) type VersionArgs struct { - ClientOnly bool - Client api.Client - Output io.Writer + ClientOnly bool + Client api.Client + EndpointURL *url.URL + Output io.Writer } func versionHandler(args VersionArgs) error { @@ -68,9 +71,10 @@ func versionHandler(args VersionArgs) error { if recommendedVersion == "" { fmt.Println("Recommended version: ") fmt.Println("This Sourcegraph instance does not support this feature.") - return nil + } else { + fmt.Printf("Recommended version: %s or later\n", recommendedVersion) } - fmt.Printf("Recommended version: %s or later\n", recommendedVersion) + warnOutdatedVersionFromLookup(recommendedVersion, args.EndpointURL) return nil } diff --git a/cmd/src/version_check.go b/cmd/src/version_check.go index 21cf575fac..b3892e40ea 100644 --- a/cmd/src/version_check.go +++ b/cmd/src/version_check.go @@ -31,40 +31,56 @@ var warnOutdatedVersionOnce sync.Once // maybeWarnOutdatedVersion prints a warning to stderr when src-cli is older // than the version recommended by the Sourcegraph instance at endpointURL, -// which it asks using client. +// which it asks using client unless a recent answer is cached. // // It never fails the command: an unreachable instance, an unparseable version, // or an unwritable cache all result in no warning. func maybeWarnOutdatedVersion(client api.Client, endpointURL *url.URL, subcommand string) { - if skipVersionCheck(subcommand) { + // 'src version' asks the instance itself, and then calls + // warnOutdatedVersionFromLookup with the answer. + if subcommand == "version" || skipVersionCheck() { return } - cacheDir, err := os.UserCacheDir() + cachePath, err := recommendedVersionCachePath(endpointURL) if err != nil { return } - cachePath := filepath.Join(cacheDir, "sourcegraph", "src-cli", "recommended-version-"+url.QueryEscape(endpointURL.String())) - if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning != "" { - fmt.Fprintln(os.Stderr, warning) + printOutdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL) +} + +// warnOutdatedVersionFromLookup is the check for 'src version', which has just +// been told the recommended version by the instance at endpointURL. The answer +// is cached, so that the commands that follow warn about the same version. +func warnOutdatedVersionFromLookup(recommended string, endpointURL *url.URL) { + if skipVersionCheck() { + return } + if cachePath, err := recommendedVersionCachePath(endpointURL); err == nil { + _ = cacheRecommendedVersion(cachePath, recommended) + } + printOutdatedVersionWarning(recommended, endpointURL) +} + +// skipVersionCheck reports whether the version check is disabled, or has no +// version to compare. +func skipVersionCheck() bool { + return os.Getenv("SRC_SKIP_VERSION_CHECK") != "" || version.BuildTag == version.DefaultBuildTag } -// skipVersionCheck reports whether the version check is disabled, has no -// version to compare, or is redundant because the command is 'src version'. -func skipVersionCheck(subcommand string) bool { - return os.Getenv("SRC_SKIP_VERSION_CHECK") != "" || - version.BuildTag == version.DefaultBuildTag || - subcommand == "version" +func printOutdatedVersionWarning(recommended string, endpointURL *url.URL) { + if warning := outdatedVersionWarning(recommended, endpointURL); warning != "" { + fmt.Fprintln(os.Stderr, warning) + } } // outdatedVersionWarning returns the warning to print, or "" when src-cli is -// not known to be older than the version the instance recommends. -func outdatedVersionWarning(client api.Client, endpointURL *url.URL, cachePath string) string { +// not known to be older than the recommended version. +func outdatedVersionWarning(recommendedVersion string, endpointURL *url.URL) string { current, err := semver.NewVersion(version.BuildTag) if err != nil { return "" } - recommended, err := semver.NewVersion(recommendedVersion(client, cachePath)) + recommended, err := semver.NewVersion(recommendedVersion) if err != nil { return "" } @@ -77,6 +93,25 @@ func outdatedVersionWarning(client api.Client, endpointURL *url.URL, cachePath s current, recommended, endpointURL) } +// recommendedVersionCachePath returns the file that holds the version +// recommended by the instance at endpointURL. +func recommendedVersionCachePath(endpointURL *url.URL) (string, error) { + cacheDir, err := os.UserCacheDir() + if err != nil { + return "", err + } + return filepath.Join(cacheDir, "sourcegraph", "src-cli", "recommended-version-"+url.QueryEscape(endpointURL.String())), nil +} + +// cacheRecommendedVersion records recommended, and the time it was learned, in +// the file at cachePath. +func cacheRecommendedVersion(cachePath, recommended string) error { + if err := os.MkdirAll(filepath.Dir(cachePath), 0o700); err != nil { + return err + } + return os.WriteFile(cachePath, []byte(recommended), 0o600) +} + // recommendedVersion returns the src-cli version recommended by the instance // that client talks to, or "" when it is unknown. The answer is cached in the // file at cachePath for versionCheckInterval, so most commands make no extra @@ -90,7 +125,7 @@ func recommendedVersion(client api.Client, cachePath string) string { // Record the attempt before the lookup, so that an instance that does not // answer delays one command per versionCheckInterval instead of every // command. Without a writable cache there is no such bound, so do not look. - if os.MkdirAll(filepath.Dir(cachePath), 0o700) != nil || os.WriteFile(cachePath, nil, 0o600) != nil { + if cacheRecommendedVersion(cachePath, "") != nil { return "" } @@ -100,6 +135,6 @@ func recommendedVersion(client api.Client, cachePath string) string { if err != nil { return "" } - _ = os.WriteFile(cachePath, []byte(recommended), 0o600) + _ = cacheRecommendedVersion(cachePath, recommended) return recommended } diff --git a/cmd/src/version_check_test.go b/cmd/src/version_check_test.go index a65847aada..e67f52e687 100644 --- a/cmd/src/version_check_test.go +++ b/cmd/src/version_check_test.go @@ -44,6 +44,34 @@ func versionServer(t *testing.T, status int, recommended string) (client api.Cli return api.NewClient(api.ClientOpts{EndpointURL: endpointURL, AccessToken: "token", Out: io.Discard}), endpointURL, requests } +// useTemporaryCacheDir points os.UserCacheDir at an empty directory. +func useTemporaryCacheDir(t *testing.T) { + t.Helper() + // Wherever os.UserCacheDir looks on this operating system. + for _, name := range []string{"HOME", "XDG_CACHE_HOME", "LocalAppData"} { + t.Setenv(name, t.TempDir()) + } +} + +// captureStderr returns what run writes to os.Stderr. +func captureStderr(t *testing.T, run func()) string { + t.Helper() + stderr := os.Stderr + defer func() { os.Stderr = stderr }() + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = writer + run() + writer.Close() + output, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + return string(output) +} + func TestOutdatedVersionWarning(t *testing.T) { tests := []struct { name string @@ -66,7 +94,7 @@ func TestOutdatedVersionWarning(t *testing.T) { setBuildTag(t, test.current) client, endpointURL, _ := versionServer(t, test.status, test.recommended) - warning := outdatedVersionWarning(client, endpointURL, filepath.Join(t.TempDir(), "recommended-version")) + warning := outdatedVersionWarning(recommendedVersion(client, filepath.Join(t.TempDir(), "recommended-version")), endpointURL) if !test.wantWarning { if warning != "" { @@ -98,7 +126,7 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { cachePath := filepath.Join(t.TempDir(), "nested", "recommended-version") for range 2 { - if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning == "" { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning == "" { t.Fatal("got no warning, want one on every command") } } @@ -107,7 +135,7 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { } makeStale(t, cachePath) - outdatedVersionWarning(client, endpointURL, cachePath) + outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL) if *requests != 2 { t.Fatalf("got %d requests after the cache went stale, want 2", *requests) } @@ -117,12 +145,12 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { setBuildTag(t, "6.4.1") client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") cachePath := filepath.Join(t.TempDir(), "recommended-version") - if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning == "" { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning == "" { t.Fatal("got no warning before upgrading, want one") } setBuildTag(t, "6.4.2") - if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning != "" { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning != "" { t.Fatalf("got warning %q after upgrading, want none", warning) } if *requests != 1 { @@ -136,7 +164,7 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { cachePath := filepath.Join(t.TempDir(), "recommended-version") for range 2 { - if warning := outdatedVersionWarning(client, endpointURL, cachePath); warning != "" { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning != "" { t.Fatalf("got warning %q, want none", warning) } } @@ -154,7 +182,7 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { t.Fatal(err) } - if warning := outdatedVersionWarning(client, endpointURL, filepath.Join(blocker, "recommended-version")); warning != "" { + if warning := outdatedVersionWarning(recommendedVersion(client, filepath.Join(blocker, "recommended-version")), endpointURL); warning != "" { t.Fatalf("got warning %q, want none", warning) } if *requests != 0 { @@ -165,29 +193,95 @@ func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { func TestSkipVersionCheck(t *testing.T) { tests := []struct { - name string - buildTag string - optOut string - subcommand string - want bool + name string + buildTag string + optOut string + want bool }{ - {name: "release build running a command", buildTag: "6.4.2", subcommand: "search", want: false}, - {name: "opted out", buildTag: "6.4.2", optOut: "1", subcommand: "search", want: true}, - {name: "dev build", buildTag: version.DefaultBuildTag, subcommand: "search", want: true}, - {name: "src version", buildTag: "6.4.2", subcommand: "version", want: true}, + {name: "release build", buildTag: "6.4.2", want: false}, + {name: "opted out", buildTag: "6.4.2", optOut: "1", want: true}, + {name: "dev build", buildTag: version.DefaultBuildTag, want: true}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { setBuildTag(t, test.buildTag) t.Setenv("SRC_SKIP_VERSION_CHECK", test.optOut) - if got := skipVersionCheck(test.subcommand); got != test.want { - t.Errorf("skipVersionCheck(%q) = %v, want %v", test.subcommand, got, test.want) + if got := skipVersionCheck(); got != test.want { + t.Errorf("skipVersionCheck() = %v, want %v", got, test.want) } }) } } +// TestVersionCommandChecksWithItsOwnLookup covers 'src version', which always +// asks the instance: it warns with that answer and caches it, instead of +// running the check that other commands get from config.apiClient. +func TestVersionCommandChecksWithItsOwnLookup(t *testing.T) { + const warning = "Warning: src-cli 6.4.1 is older than 6.4.3" + + // setup returns a fake instance that recommends 6.4.3, and the path of a + // cache that was told 6.4.2 a moment ago. + setup := func(t *testing.T) (client api.Client, endpointURL *url.URL, requests *int, cachePath string) { + t.Helper() + setBuildTag(t, "6.4.1") + t.Setenv("SRC_SKIP_VERSION_CHECK", "") + useTemporaryCacheDir(t) + client, endpointURL, requests = versionServer(t, http.StatusOK, "6.4.3") + cachePath, err := recommendedVersionCachePath(endpointURL) + if err != nil { + t.Fatal(err) + } + if err := cacheRecommendedVersion(cachePath, "6.4.2"); err != nil { + t.Fatal(err) + } + return client, endpointURL, requests, cachePath + } + + t.Run("warns with the answer it gets, and caches it for later commands", func(t *testing.T) { + client, endpointURL, requests, cachePath := setup(t) + + stderr := captureStderr(t, func() { + // The check that config.apiClient runs for every command. + maybeWarnOutdatedVersion(client, endpointURL, "version") + if err := versionHandler(VersionArgs{Client: client, EndpointURL: endpointURL}); err != nil { + t.Error(err) + } + }) + + if got := strings.Count(stderr, "Warning:"); got != 1 || !strings.Contains(stderr, warning) { + t.Errorf("got stderr %q, want only %q", stderr, warning) + } + if cached := recommendedVersion(client, cachePath); cached != "6.4.3" { + t.Errorf("got cached version %q, want 6.4.3", cached) + } + if *requests != 1 { + t.Errorf("got %d requests, want 1", *requests) + } + }) + + t.Run("-client-only does not ask the instance", func(t *testing.T) { + client, endpointURL, requests, cachePath := setup(t) + + stderr := captureStderr(t, func() { + maybeWarnOutdatedVersion(client, endpointURL, "version") + if err := versionHandler(VersionArgs{Client: client, EndpointURL: endpointURL, ClientOnly: true}); err != nil { + t.Error(err) + } + }) + + if stderr != "" { + t.Errorf("got stderr %q, want none", stderr) + } + if cached := recommendedVersion(client, cachePath); cached != "6.4.2" { + t.Errorf("got cached version %q, want 6.4.2 left alone", cached) + } + if *requests != 0 { + t.Errorf("got %d requests, want 0", *requests) + } + }) +} + // TestAPIClientWarnsAboutOutdatedVersion covers where the check is hooked in: // config.apiClient, which every command that talks to the instance calls with // its own flags. @@ -204,10 +298,7 @@ func TestAPIClientWarnsAboutOutdatedVersion(t *testing.T) { t.Run(test.name, func(t *testing.T) { setBuildTag(t, "6.4.1") t.Setenv("SRC_SKIP_VERSION_CHECK", "") - // Wherever os.UserCacheDir looks on this operating system. - for _, name := range []string{"HOME", "XDG_CACHE_HOME", "LocalAppData"} { - t.Setenv(name, t.TempDir()) - } + useTemporaryCacheDir(t) warnOutdatedVersionOnce = sync.Once{} t.Cleanup(func() { warnOutdatedVersionOnce = sync.Once{} }) @@ -220,24 +311,14 @@ func TestAPIClientWarnsAboutOutdatedVersion(t *testing.T) { cfg := &config{endpointURL: mustParseURL(t, server.URL), accessToken: "token"} flags := api.NewFlagsFromValues(false, false, false, test.insecureSkipVerify, false) - stderr := os.Stderr - t.Cleanup(func() { os.Stderr = stderr }) - reader, writer, err := os.Pipe() - if err != nil { - t.Fatal(err) - } - os.Stderr = writer - for range 2 { - cfg.apiClient(flags, io.Discard) - } - writer.Close() - output, err := io.ReadAll(reader) - if err != nil { - t.Fatal(err) - } + stderr := captureStderr(t, func() { + for range 2 { + cfg.apiClient(flags, io.Discard) + } + }) - if got := strings.Count(string(output), "Warning: src-cli 6.4.1 is older than 6.4.2"); got != test.wantWarnings { - t.Errorf("got %d warnings, want %d; stderr: %q", got, test.wantWarnings, output) + if got := strings.Count(stderr, "Warning: src-cli 6.4.1 is older than 6.4.2"); got != test.wantWarnings { + t.Errorf("got %d warnings, want %d; stderr: %q", got, test.wantWarnings, stderr) } }) } From 6b0e81f6ac1d1b1d1b4ae88524a93738e4256da7 Mon Sep 17 00:00:00 2001 From: Marc LeBlanc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:44:56 -0600 Subject: [PATCH 6/6] docs: remove the README section on the version check The warning already names SRC_SKIP_VERSION_CHECK and links to the upgrade instructions, and CHANGELOG.md describes the feature. This reverts commit 71363c82b4753d0859101e940aa446814422821b. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp --- README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.md b/README.md index c4a716f9f6..37100691a3 100644 --- a/README.md +++ b/README.md @@ -201,10 +201,6 @@ You can then invoke it via `src-cli`. `src` waits up to 1 minute for the server to start responding to a request. To change this, set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to a duration such as `30s` or `10m`, or to `0` to disable the timeout. This timeout only applies until the server sends its response headers — responses that stream data for a long time, such as large search job results, are not interrupted. -## Version check - -`src` prints a warning to stderr when it is older than the version recommended by your Sourcegraph instance. It asks the instance at most once every 24 hours, and the check never fails a command. To upgrade, see [Installation](#installation). To disable the check, set the `SRC_SKIP_VERSION_CHECK` environment variable to any non-blank string. - ## Telemetry `src` includes the operating system and architecture in the `User-Agent` header sent to Sourcegraph. For example, running `src` version 3.21.10 on an x86-64 Linux host will result in this header: