|
| 1 | +/* |
| 2 | +Copyright © 2026 Intercube <opensource@intercube.io> |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | +package cmd |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "encoding/json" |
| 21 | + "fmt" |
| 22 | + "net/http" |
| 23 | + "os" |
| 24 | + "os/exec" |
| 25 | + "path/filepath" |
| 26 | + "strings" |
| 27 | + "time" |
| 28 | + |
| 29 | + "github.com/spf13/cobra" |
| 30 | + "golang.org/x/mod/semver" |
| 31 | +) |
| 32 | + |
| 33 | +const ( |
| 34 | + // modulePath is the Go module that hosts the CLI. |
| 35 | + modulePath = "github.com/intercube/cli" |
| 36 | + // installPath is the package built into the `intercube` binary. |
| 37 | + installPath = modulePath + "/cmd/intercube" |
| 38 | + // goProxy is the public Go module proxy used to discover the latest tag. |
| 39 | + // The repository is public, so no authentication is required. |
| 40 | + goProxy = "https://proxy.golang.org" |
| 41 | +) |
| 42 | + |
| 43 | +var forceUpdate bool |
| 44 | + |
| 45 | +// selfUpdateCmd updates the running intercube binary to the latest (or a |
| 46 | +// specified) tagged version by re-running `go install`. |
| 47 | +var selfUpdateCmd = &cobra.Command{ |
| 48 | + Use: "self-update [version]", |
| 49 | + Short: "Update the Intercube CLI to the latest version", |
| 50 | + Long: `Update the Intercube CLI by reinstalling it with the Go toolchain. |
| 51 | +
|
| 52 | +By default this installs the latest published version. Pass an explicit |
| 53 | +version (e.g. "intercube self-update v1.0.19") to pin or roll back. |
| 54 | +
|
| 55 | +Requires the Go toolchain to be installed and on your PATH.`, |
| 56 | + Args: cobra.MaximumNArgs(1), |
| 57 | + RunE: runSelfUpdate, |
| 58 | +} |
| 59 | + |
| 60 | +func init() { |
| 61 | + selfUpdateCmd.Flags().BoolVarP(&forceUpdate, "force", "f", false, "reinstall even if already up to date") |
| 62 | + rootCmd.AddCommand(selfUpdateCmd) |
| 63 | +} |
| 64 | + |
| 65 | +func runSelfUpdate(cmd *cobra.Command, args []string) error { |
| 66 | + ctx := cmd.Context() |
| 67 | + current := currentVersion() |
| 68 | + |
| 69 | + // Resolve the target version: an explicit argument, or "latest". |
| 70 | + target := "latest" |
| 71 | + if len(args) == 1 { |
| 72 | + target = strings.TrimSpace(args[0]) |
| 73 | + } |
| 74 | + |
| 75 | + // When targeting latest, look up the newest tag so we can report it and |
| 76 | + // skip needless reinstalls. A lookup failure is non-fatal: we warn and |
| 77 | + // proceed to let `go install` do the work. |
| 78 | + if target == "latest" { |
| 79 | + latest, err := latestVersion(ctx) |
| 80 | + if err != nil { |
| 81 | + fmt.Fprintf(os.Stderr, "warning: could not check for the latest version: %v\n", err) |
| 82 | + } else { |
| 83 | + target = latest |
| 84 | + if !forceUpdate && current == latest { |
| 85 | + fmt.Printf("Intercube CLI is already up to date (%s)\n", current) |
| 86 | + return nil |
| 87 | + } |
| 88 | + if !forceUpdate && semver.IsValid(current) && semver.Compare(current, latest) > 0 { |
| 89 | + fmt.Printf("Intercube CLI %s is newer than the latest published version (%s); nothing to do\n", current, latest) |
| 90 | + return nil |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + goBin, err := exec.LookPath("go") |
| 96 | + if err != nil { |
| 97 | + return fmt.Errorf("the Go toolchain is required to self-update but `go` was not found on your PATH.\n"+ |
| 98 | + "Install Go (https://go.dev/dl/) or update manually with:\n go install %s@latest", installPath) |
| 99 | + } |
| 100 | + |
| 101 | + spec := installPath + "@" + target |
| 102 | + fmt.Printf("Updating Intercube CLI (%s -> %s)...\n", current, target) |
| 103 | + |
| 104 | + install := exec.CommandContext(ctx, goBin, "install", spec) |
| 105 | + install.Stdout = os.Stdout |
| 106 | + install.Stderr = os.Stderr |
| 107 | + install.Env = os.Environ() |
| 108 | + if err := install.Run(); err != nil { |
| 109 | + return fmt.Errorf("`go install %s` failed: %w", spec, err) |
| 110 | + } |
| 111 | + |
| 112 | + fmt.Printf("Updated Intercube CLI to %s.\n", target) |
| 113 | + warnIfShadowed(ctx, goBin) |
| 114 | + return nil |
| 115 | +} |
| 116 | + |
| 117 | +// latestVersion queries the public Go module proxy for the most recent tagged |
| 118 | +// version of the module. |
| 119 | +func latestVersion(ctx context.Context) (string, error) { |
| 120 | + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 121 | + defer cancel() |
| 122 | + |
| 123 | + url := fmt.Sprintf("%s/%s/@latest", goProxy, modulePath) |
| 124 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 125 | + if err != nil { |
| 126 | + return "", err |
| 127 | + } |
| 128 | + |
| 129 | + resp, err := http.DefaultClient.Do(req) |
| 130 | + if err != nil { |
| 131 | + return "", err |
| 132 | + } |
| 133 | + defer resp.Body.Close() |
| 134 | + |
| 135 | + if resp.StatusCode != http.StatusOK { |
| 136 | + return "", fmt.Errorf("unexpected status %s from %s", resp.Status, url) |
| 137 | + } |
| 138 | + |
| 139 | + var payload struct { |
| 140 | + Version string `json:"Version"` |
| 141 | + } |
| 142 | + if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil { |
| 143 | + return "", err |
| 144 | + } |
| 145 | + if payload.Version == "" { |
| 146 | + return "", fmt.Errorf("no version returned by %s", url) |
| 147 | + } |
| 148 | + return payload.Version, nil |
| 149 | +} |
| 150 | + |
| 151 | +// warnIfShadowed alerts the user when `go install` wrote the new binary to a |
| 152 | +// directory other than the one the currently-running binary lives in, which |
| 153 | +// can happen when an older copy appears earlier on PATH. |
| 154 | +func warnIfShadowed(ctx context.Context, goBin string) { |
| 155 | + installDir := goInstallDir(ctx, goBin) |
| 156 | + if installDir == "" { |
| 157 | + return |
| 158 | + } |
| 159 | + |
| 160 | + self, err := os.Executable() |
| 161 | + if err != nil { |
| 162 | + return |
| 163 | + } |
| 164 | + if selfPath, err := filepath.EvalSymlinks(self); err == nil { |
| 165 | + self = selfPath |
| 166 | + } |
| 167 | + |
| 168 | + if filepath.Dir(self) != installDir { |
| 169 | + fmt.Fprintf(os.Stderr, |
| 170 | + "\nNote: the updated binary was installed to %s,\n"+ |
| 171 | + "but the Intercube CLI you just ran is at %s.\n"+ |
| 172 | + "Make sure %s is early on your PATH, or run the updated binary directly.\n", |
| 173 | + installDir, self, installDir) |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +// goInstallDir returns the directory `go install` writes binaries to, |
| 178 | +// i.e. $GOBIN if set, otherwise $GOPATH/bin. |
| 179 | +func goInstallDir(ctx context.Context, goBin string) string { |
| 180 | + if gobin := strings.TrimSpace(goEnv(ctx, goBin, "GOBIN")); gobin != "" { |
| 181 | + return gobin |
| 182 | + } |
| 183 | + if gopath := strings.TrimSpace(goEnv(ctx, goBin, "GOPATH")); gopath != "" { |
| 184 | + // GOPATH may contain a list; the first entry receives `go install` output. |
| 185 | + first := filepath.SplitList(gopath)[0] |
| 186 | + if first != "" { |
| 187 | + return filepath.Join(first, "bin") |
| 188 | + } |
| 189 | + } |
| 190 | + return "" |
| 191 | +} |
| 192 | + |
| 193 | +// goEnv reads a single value from `go env`. |
| 194 | +func goEnv(ctx context.Context, goBin, key string) string { |
| 195 | + out, err := exec.CommandContext(ctx, goBin, "env", key).Output() |
| 196 | + if err != nil { |
| 197 | + return "" |
| 198 | + } |
| 199 | + return strings.TrimSpace(string(out)) |
| 200 | +} |
0 commit comments