Skip to content

Commit 022bb5f

Browse files
authored
Merge pull request #69 from intercube/feature/add-self-update-command
Add self-update and version commands to CLI
2 parents 657ca36 + 606972a commit 022bb5f

6 files changed

Lines changed: 288 additions & 2 deletions

File tree

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,33 @@
11
## Intercube CLI
22
This command line interface allows you to connect, manage, and synchronize data from your Intercube cubes (servers).
33

4+
### Installing & updating
5+
6+
Install (or update) with the Go toolchain:
7+
8+
```bash
9+
go install github.com/intercube/cli/cmd/intercube@latest
10+
```
11+
12+
Once installed, you can update in place without remembering that command:
13+
14+
```bash
15+
intercube self-update # update to the latest version
16+
intercube self-update v1.0.19 # pin or roll back to a specific version
17+
intercube self-update --force # reinstall even if already up to date
18+
```
19+
20+
`self-update` shells out to `go install`, so it requires the Go toolchain on your
21+
PATH. It installs to your `$GOBIN` (or `$GOPATH/bin`); if a different copy of
22+
`intercube` appears earlier on your PATH, the command warns you so you can fix it.
23+
24+
Check your current version any time:
25+
26+
```bash
27+
intercube version
28+
intercube --version
29+
```
30+
431
### Onboarding
532

633
Use the onboarding command to set up your CLI config interactively:

cmd/root.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ var Verbose bool
3131

3232
// rootCmd represents the base command when called without any subcommands
3333
var rootCmd = &cobra.Command{
34-
Use: "intercube",
35-
Short: "Intercube CLI",
34+
Use: "intercube",
35+
Short: "Intercube CLI",
36+
Version: currentVersion(),
3637
Long: `Intercube CLI for host access, API operations, and environment sync.
3738
3839
Tip: use "intercube ssh" for host access.

cmd/self-update.go

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
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+
}

cmd/version.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
"fmt"
20+
"runtime/debug"
21+
22+
"github.com/spf13/cobra"
23+
)
24+
25+
// devVersion is reported when the binary was not installed from a tagged
26+
// module version (e.g. built locally with `go build` or `go run`).
27+
const devVersion = "dev"
28+
29+
// currentVersion returns the module version embedded by the Go toolchain.
30+
// For binaries installed via `go install module@version` this is the git tag
31+
// (e.g. "v1.0.20"); for local builds it is empty or "(devel)", in which case
32+
// we report devVersion.
33+
func currentVersion() string {
34+
info, ok := debug.ReadBuildInfo()
35+
if !ok {
36+
return devVersion
37+
}
38+
if v := info.Main.Version; v != "" && v != "(devel)" {
39+
return v
40+
}
41+
return devVersion
42+
}
43+
44+
// versionCmd represents the version command.
45+
var versionCmd = &cobra.Command{
46+
Use: "version",
47+
Short: "Print the Intercube CLI version",
48+
Run: func(cmd *cobra.Command, args []string) {
49+
fmt.Println(currentVersion())
50+
},
51+
}
52+
53+
func init() {
54+
rootCmd.AddCommand(versionCmd)
55+
}

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ require (
1111
github.com/spf13/viper v1.21.0
1212
github.com/tcnksm/go-httpstat v0.2.0
1313
github.com/zalando/go-keyring v0.2.8
14+
golang.org/x/mod v0.37.0
1415
golang.org/x/term v0.44.0
1516
)
1617

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
119119
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
120120
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
121121
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
122+
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
123+
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
122124
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
123125
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
124126
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=

0 commit comments

Comments
 (0)