diff --git a/README.md b/README.md index b1b1c53..dd9b05c 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ but Ghostty. ```sh # macOS on Apple silicon; for other systems, replace darwin-arm64 with # darwin-amd64, linux-amd64 or linux-arm64 -curl -fLo ghosttyconf https://git.micw.org/mike/ghosttyconf/releases/download/1.0.0/ghosttyconf-darwin-arm64 +curl -fLo ghosttyconf https://git.micw.org/mike/ghosttyconf/releases/download/1.0.1/ghosttyconf-darwin-arm64 chmod +x ghosttyconf mv ghosttyconf ~/bin/ # or any other directory in your $PATH ``` @@ -77,6 +77,29 @@ make install # installs ghosttyconf into $(go env GOPATH)/bin `make build` builds `./ghosttyconf` in the source directory instead. +### Updating + +```sh +ghosttyconf --update # install the newest release in place of this binary +ghosttyconf --check-update # only check +``` + +The new binary is downloaded next to the old one and started once with +`--version` before it replaces the old one, so a broken download never takes +its place. If ghosttyconf lives in a directory you cannot write to, such as +`/usr/local/bin`, run `sudo ghosttyconf --update`. + +Once a day, ghosttyconf also asks git.micw.org in the background whether there +is a newer release. If there is, the next start says so in the header of the +editor, and again in the terminal after you quit. Nothing is installed without +`--update`. The check stays quiet when stderr is not a terminal, and +`GHOSTTYCONF_NO_UPDATE_CHECK=1` turns it off. Its result is kept in +`~/Library/Caches/ghosttyconf/update.json` on macOS and +`~/.cache/ghosttyconf/update.json` on Linux; losing it only means asking once +more. + +Self-update arrived in 1.0.1. Replace 1.0.0 by hand once. + ## 💡 Quick start ```sh @@ -199,6 +222,8 @@ ghosttyconf [flags] [config-file] --no-reload do not reload Ghostty after saving --offline do not run ghostty; use the built-in option list --print-path print the config file that would be edited and exit + --update install the newest release in place of this binary + --check-update only check whether there is a newer release --version print the version and exit ``` diff --git a/docs/development.md b/docs/development.md index 1d00ce9..918a97e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -26,6 +26,7 @@ for macOS and Linux. Other platforms only save. | `main.go` | flags, startup, wiring | | `version.go`, `version.txt` | the version: `version.txt` is the released one, `build.sh` injects it | | `build.sh` | builds the release binaries into `./bin` | +| `selfupdate.go` | `--update`, `--check-update` and the daily background check against the Gitea releases | | `internal/schema` | the option schema: kinds, categories, platform detection, value validation; `schema.json` is embedded | | `internal/config` | the comment- and layout-preserving config file model, atomic saving | | `internal/ghostty` | finding and running the `ghostty` binary (docs, themes, fonts, actions, validation), config paths, reload | @@ -64,6 +65,30 @@ on git.micw.org. Every regular file in `./bin` is attached to it. If the tag already exists with a longer annotation, that annotation becomes the release notes. `./bin` is not part of the repository. +### Self-update + +`selfupdate.go` is the copyable template from nscan (originally goca). Only +its configuration block is specific to ghosttyconf: the repository URL, the +asset name and `GHOSTTYCONF_NO_UPDATE_CHECK`. It relies on the release layout +above, so keep these when changing the build or the release: + +- The tag is the bare version number. +- The assets are named `ghosttyconf--`, exactly as `build.sh` names + them. +- `ghosttyconf --version` prints the version number. The downloaded binary is + started with it, and the update is refused if the number is missing. +- The release is neither a draft nor a prerelease. Gitea's + `/releases/latest` skips both, so a prerelease is a way to publish without + offering it as an update. + +The daily check starts the program again as `ghosttyconf --update-refresh` +and doesn't wait for it. `main` takes that argument before the flags, so it +stays out of the help. The note goes to +`os.UserCacheDir()/ghosttyconf/update.json`. `tools/screenshots.sh` sets +`GHOSTTYCONF_NO_UPDATE_CHECK=1`, so no update hint lands in a screenshot. The +tests in `selfupdate_test.go` run against a fake Gitea built with `httptest` +and never touch the network. + ## The schema Ghostty's own documentation (`ghostty +show-config --default --docs`) contains diff --git a/docs/guide.md b/docs/guide.md index 8eb5f9a..6835ec8 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -12,6 +12,7 @@ the [README](../README.md). - [Key bindings](#key-bindings) - [Saving](#saving) - [Reloading Ghostty](#reloading-ghostty) +- [Updating ghosttyconf](#updating-ghosttyconf) - [Troubleshooting](#troubleshooting) ## Which file is edited @@ -279,6 +280,29 @@ The documentation of an option mentions this where it matters. Use `--no-reload` to only save. The status line then reminds you of the shortcut. +## Updating ghosttyconf + +`ghosttyconf --update` installs the newest release from +[git.micw.org](https://git.micw.org/mike/ghosttyconf/releases) in place of the +running binary, and `ghosttyconf --check-update` only looks. The update: + +1. asks for the newest release that is neither a draft nor a prerelease, +2. downloads `ghosttyconf--` next to the running binary and checks + its size, +3. starts the download once with `--version` and expects the new version + number, +4. renames it over the old binary. A symlink stays and the file behind it is + replaced. + +If any step fails, the old binary stays as it was. + +Once a day, a normal start also asks in the background, without delaying the +start. A newer release then shows up on the next start, in yellow on the +right of the header and at the top of the help (`?`), and once more as a line +in the terminal after you quit. Nothing is installed on its own. The check +stays quiet when stderr is not a terminal, and `GHOSTTYCONF_NO_UPDATE_CHECK=1` +turns it off. + ## Troubleshooting **"Ghostty refused the AppleScript command"**: your config sets @@ -296,6 +320,12 @@ Ghostty release, see [Development](development.md#updating-for-a-new-ghostty-rel **A key combination can't be recorded**: Ghostty or macOS handled it before ghosttyconf could see it. Type it into the trigger field. +**"cannot write to …" on `--update`**: ghosttyconf lives in a directory you +can't write to, such as `/usr/local/bin`. Run `sudo ghosttyconf --update`. + +**`--update` is an unknown flag**: that is version 1.0.0, from before +self-update. Download the newest release by hand once. + **Validation fails for an entry you didn't touch**: the problem was already in your file. ghosttyconf marks invalid values in red. Fix or reset them, or save anyway. diff --git a/internal/ui/app.go b/internal/ui/app.go index 4f4d459..be5bf60 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -99,6 +99,7 @@ type App struct { quitAfterSave bool autoReload bool version string + update string // a newer release, if one is known // Screen regions from the last render, for mouse handling. catRect, optRect, docRect rect @@ -159,6 +160,9 @@ func (a *App) SetAutoReload(on bool) { a.autoReload = on } // SetVersion sets the program version shown in the help. func (a *App) SetVersion(v string) { a.version = v } +// SetUpdate names a newer release, shown in the header and the help. +func (a *App) SetUpdate(v string) { a.update = v } + func (a *App) Init() tea.Cmd { if a.gh == nil { return nil @@ -407,7 +411,7 @@ func (a *App) updateBrowse(km tea.KeyMsg) tea.Cmd { case "q": return a.quit() case "?", "f1": - a.dlg = helpDialog(a.version) + a.dlg = helpDialog(a.version, a.update) return nil case "/", "ctrl+f": // Every search starts fresh, like "/" in less or vim. diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index b545d6e..97d64c5 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -5,6 +5,7 @@ import ( "testing" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" "ghosttyconf/internal/config" "ghosttyconf/internal/schema" @@ -218,3 +219,27 @@ func TestUnknownKeyIsListed(t *testing.T) { t.Fatal("unknown key not rendered") } } + +func TestUpdateHintShown(t *testing.T) { + a := newTestApp(t, "") + a.SetVersion("1.0.0") + a.SetUpdate("1.0.1") + header := func() string { return strings.SplitN(ansi.Strip(a.View()), "\n", 2)[0] } + if h := header(); !strings.Contains(h, "ghosttyconf 1.0.1 available · ") || !strings.Contains(h, "options") { + t.Errorf("header at 160 columns: %q", h) + } + // Short of space, the update outlasts the option count. + a.Update(tea.WindowSizeMsg{Width: 80, Height: 24}) + if h := header(); !strings.Contains(h, "ghosttyconf 1.0.1 available") || strings.Contains(h, "options") { + t.Errorf("header at 80 columns: %q", h) + } + press(a, "?") + if !strings.Contains(ansi.Strip(a.View()), "1.0.1 is available, run ghosttyconf --update") { + t.Error("help does not mention the update") + } + + a = newTestApp(t, "") + if h := header(); strings.Contains(h, "available") || !strings.Contains(h, "options") { + t.Errorf("header without an update: %q", h) + } +} diff --git a/internal/ui/dialogs.go b/internal/ui/dialogs.go index b4e51b3..2715d36 100644 --- a/internal/ui/dialogs.go +++ b/internal/ui/dialogs.go @@ -99,13 +99,13 @@ func (d *dialog) view(width, height int) string { return framed(d.title, content, w, len(lines)+2, color) } -func helpDialog(version string) *dialog { +func helpDialog(version, update string) *dialog { k := func(key, desc string) string { return stKey.Render(fit(key, 16)) + desc } title := "Help" if version != "" { title = "Help · ghosttyconf " + version } - return &dialog{ + d := &dialog{ title: title, lines: []string{ stBold.Render("Browsing"), @@ -155,4 +155,10 @@ func helpDialog(version string) *dialog { }, keys: []dialogKey{{"esc", "Close"}}, } + if update != "" { + note := stChanged.Render("ghosttyconf "+update+" is available") + + stDim.Render(", run ") + "ghosttyconf --update" + stDim.Render(" after quitting") + d.lines = append([]string{note, ""}, d.lines...) + } + return d } diff --git a/internal/ui/view.go b/internal/ui/view.go index ee0ee1b..0b2c55e 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -31,9 +31,19 @@ func (a *App) View() string { func (a *App) viewHeader() string { title := stTitle.Render("Ghostty Config Editor") + " " - right := stHeader.Render(fmt.Sprintf(" %s · %d options ", a.sch.Source, len(a.sch.Options))) - if lipgloss.Width(title)+lipgloss.Width(right)+20 > a.width { - right = "" + info := stHeader.Render(fmt.Sprintf(" %s · %d options ", a.sch.Source, len(a.sch.Options))) + fits := func(s string) bool { return lipgloss.Width(title)+lipgloss.Width(s)+20 <= a.width } + // A newer release outlasts the option count when space runs short; the + // help says how to get it. + upd := " ghosttyconf " + a.update + " available" + var right string + switch { + case a.update != "" && fits(stChanged.Render(upd)+stHeader.Render(" ·")+info): + right = stChanged.Render(upd) + stHeader.Render(" ·") + info + case a.update != "" && fits(stChanged.Render(upd+" ")): + right = stChanged.Render(upd + " ") + case fits(info): + right = info } path := shortPath(a.file.Path) if !a.file.Exists { diff --git a/main.go b/main.go index 4f585b9..f1ea763 100644 --- a/main.go +++ b/main.go @@ -16,12 +16,21 @@ import ( ) func main() { + // The background look for a newer release (selfupdate.go). Taken before + // the flags, so it can stay out of the help. + if len(os.Args) == 2 && os.Args[1] == updateRefreshFlag { + selfUpdate.refresh() + return + } + configPath := flag.String("config", "", "config file to edit (default: Ghostty's default config file)") ghosttyBin := flag.String("ghostty", "", "path to the ghostty binary (default: search $PATH and /Applications)") offline := flag.Bool("offline", false, "do not run ghostty; use the built-in option list") printPath := flag.Bool("print-path", false, "print the config file that would be edited and exit") noReload := flag.Bool("no-reload", false, "do not ask Ghostty to reload its configuration after saving") showVersion := flag.Bool("version", false, "print the version and exit") + update := flag.Bool("update", false, "install the newest release in place of this binary and exit") + checkUpdate := flag.Bool("check-update", false, "check for a newer release and exit") flag.Usage = func() { fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [flags] [config-file]\n\n", filepath.Base(os.Args[0])) fmt.Fprintf(flag.CommandLine.Output(), "A terminal editor for the Ghostty configuration (version %s). Flags:\n", Version) @@ -32,6 +41,19 @@ func main() { fmt.Println("ghosttyconf", Version) return } + if *update || *checkUpdate { + var err error + if *update { + err = selfUpdate.install(os.Stdout) + } else { + err = selfUpdate.check(os.Stdout) + } + if err != nil { + fmt.Fprintln(os.Stderr, "ghosttyconf:", err) + os.Exit(1) + } + return + } if flag.NArg() > 1 { flag.Usage() os.Exit(2) @@ -85,6 +107,15 @@ func run(path, ghosttyBin string, offline, autoReload bool) error { app := ui.New(sch, gh, file) app.SetAutoReload(autoReload) app.SetVersion(Version) + // Costs nothing: the hint comes from a note in the cache, and the asking + // happens at most once a day, in the background. + if hint := selfUpdate.daily(); hint != "" { + app.SetUpdate(selfUpdate.loadState().Latest) + // Once more after the editor has closed, where `ghosttyconf --update` + // can be typed right away. Deferred before RestoreTerminal, so it + // runs after it. + defer fmt.Fprintln(os.Stderr, hint) + } p := tea.NewProgram(app, tea.WithAltScreen(), tea.WithMouseCellMotion()) defer ui.RestoreTerminal() _, err = p.Run() diff --git a/selfupdate.go b/selfupdate.go new file mode 100644 index 0000000..f788612 --- /dev/null +++ b/selfupdate.go @@ -0,0 +1,495 @@ +// selfupdate.go — updating oneself from the releases of a Gitea instance. +// +// The file is meant to be copied: take it into another program, adjust the +// configuration block below, hang `--update` and `--check-update` into the +// options — done. It needs nothing but the standard library, and apart from +// that block it brings no names that do not begin with "selfUpdate" or +// "update". +// +// It assumes the layout build.sh produces: one release per version, whose tag +// is the bare number (1.0.2, a leading "v" is allowed), holding one asset +// "--" each — that is, exactly the files from ./bin. +// +// Taken from nscan, with goca's spelling of the hints: ghosttyconf takes a +// config file as its argument, so `ghosttyconf update` would be a file name, +// and --update is the only way to say it. +// Under /api/v1/repos///releases/latest Gitea hands out the newest +// release that is neither a draft nor a prerelease; GitHub speaks the same +// route with different field names and is therefore not covered. +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" +) + +// ------------------------------------------------------------ Configuration + +var selfUpdate = selfUpdater{ + repo: "https://git.micw.org/mike/ghosttyconf", + asset: "ghosttyconf", + current: Version, // from version.go, set by build.sh + verify: []string{"--version"}, + every: 24 * time.Hour, + quietEnv: "GHOSTTYCONF_NO_UPDATE_CHECK", +} + +type selfUpdater struct { + repo string // repo URL as in the browser: https://host/owner/repo + asset string // base name of the assets, "--" is added + current string // the running version + verify []string // trial run of the download; empty skips it + every time.Duration // how often to look on its own; 0 turns that off + quietEnv string // this environment variable set: keep quiet as well +} + +// updateRefreshFlag is the option the program calls itself with, in the +// background. It is deliberately absent from the help. +const updateRefreshFlag = "--update-refresh" + +// ------------------------------------------------------------ Looking by itself + +// daily is the hook for the ordinary run of the program. It costs nothing: in +// the foreground the network is never touched. What comes back is the line +// pointing at a new version — or "", when there is nothing to say; what it +// looks like is up to the caller. Should the note be older than `every`, daily +// starts a background run on the side, whose answer the next call will find +// waiting. +func (u selfUpdater) daily() string { + if u.every <= 0 || os.Getenv(u.quietEnv) != "" || !updateOnTerminal() { + return "" + } + st := u.loadState() // no file: the zero value, hence due at once + + if time.Since(st.Checked) >= u.every { + // The timestamp moves on before the asking, not after: otherwise two + // simultaneous runs start two queries, and a server that is not in the + // mood would get a new one on every call. If the note does not stay + // put, nothing is asked either — else an unwritable cache directory + // would mean one process per call. + st.Checked = time.Now() + if u.saveState(st) == nil { + u.spawnRefresh() + } + } + + if st.Latest == "" || updateCompare(st.Latest, u.current) <= 0 { + return "" + } + return fmt.Sprintf("%s %s is available, run '%s --update'", u.asset, st.Latest, u.asset) +} + +// refresh is the background run: ask, write it down, stay quiet. The writing +// down is done by latest; if the query fails, the old state remains. +func (u selfUpdater) refresh() { + _, _ = u.latest() +} + +// spawnRefresh calls this program once more, only to ask, and does not wait. +// Without a Wait the child is adopted by init when this process ends — it thus +// outlives the call, and the call's output stays untouched by it. +func (u selfUpdater) spawnRefresh() { + exe, err := os.Executable() + if err != nil { + return + } + cmd := exec.Command(exe, updateRefreshFlag) + cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil // everything to /dev/null + if cmd.Start() == nil { + cmd.Process.Release() + } +} + +// The hint is meant for the person sitting there. Running in a pipe, in a +// script or under cron, the program neither asks nor says anything. +func updateOnTerminal() bool { + st, err := os.Stderr.Stat() + return err == nil && st.Mode()&os.ModeCharDevice != 0 +} + +// --------------------------------------------------------------------- Note + +// updateState is what is left between two calls: when the last question was +// asked and what came of it. +type updateState struct { + Checked time.Time `json:"checked"` + Latest string `json:"latest"` +} + +// The note lives in the cache directory, not in the configuration: if it gets +// lost, the only cost is asking once too early. +func (u selfUpdater) statePath() (string, error) { + dir, err := os.UserCacheDir() + if err != nil { + return "", err + } + return filepath.Join(dir, u.asset, "update.json"), nil +} + +func (u selfUpdater) loadState() updateState { + var st updateState + path, err := u.statePath() + if err != nil { + return st + } + b, err := os.ReadFile(path) + if err != nil { + return st + } + json.Unmarshal(b, &st) // a broken file counts as none + return st +} + +func (u selfUpdater) saveState(st updateState) error { + path, err := u.statePath() + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + b, err := json.Marshal(st) + if err != nil { + return err + } + // By way of a file alongside, so that a simultaneous run never comes upon + // half a JSON. + tmp := path + ".new" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + if err := os.Rename(tmp, path); err != nil { + os.Remove(tmp) + return err + } + return nil +} + +// ------------------------------------------------------------------ The work + +// check only looks and touches nothing. +func (u selfUpdater) check(w io.Writer) error { + rel, err := u.latest() + if err != nil { + return err + } + if updateCompare(rel.TagName, u.current) <= 0 { + fmt.Fprintf(w, "%s %s is up to date\n", u.asset, u.current) + return nil + } + fmt.Fprintf(w, "%s %s is available, running %s\n %s\n run '%s --update' to install it\n", + u.asset, rel.TagName, u.current, rel.HTMLURL, u.asset) + return nil +} + +// install fetches the newest release and replaces the running file with it. +func (u selfUpdater) install(w io.Writer) error { + rel, err := u.latest() + if err != nil { + return err + } + if updateCompare(rel.TagName, u.current) <= 0 { + fmt.Fprintf(w, "%s %s is up to date\n", u.asset, u.current) + return nil + } + + want := fmt.Sprintf("%s-%s-%s", u.asset, runtime.GOOS, runtime.GOARCH) + if runtime.GOOS == "windows" { + want += ".exe" // build.sh keeps the extension on the Windows asset + } + var src *updateAsset + for i := range rel.Assets { + if rel.Assets[i].Name == want { + src = &rel.Assets[i] + break + } + } + if src == nil { + names := make([]string, len(rel.Assets)) + for i, a := range rel.Assets { + names[i] = a.Name + } + return fmt.Errorf("release %s has no %q (only %s)", rel.TagName, want, strings.Join(names, ", ")) + } + + exe, err := os.Executable() + if err != nil { + return fmt.Errorf("cannot locate the running binary: %w", err) + } + // An installed ghosttyconf may be a symlink into ./bin. What should be replaced + // is the file behind it, not the link. + if real, err := filepath.EvalSymlinks(exe); err == nil { + exe = real + } + mode := os.FileMode(0o755) + if st, err := os.Stat(exe); err == nil { + mode = st.Mode().Perm() + } + + fmt.Fprintf(w, "downloading %s %s (%s)\n", want, rel.TagName, updateSize(src.Size)) + tmp, err := u.download(src, exe, mode) + if err != nil { + return err + } + defer os.Remove(tmp) // only bites when the renaming below falls through + + if err := u.probe(tmp, rel.TagName); err != nil { + return err + } + if err := updateReplace(tmp, exe); err != nil { + return err + } + + fmt.Fprintf(w, "%s %s → %s, at %s\n", u.asset, u.current, rel.TagName, exe) + return nil +} + +func (u selfUpdater) download(a *updateAsset, exe string, mode os.FileMode) (string, error) { + // The new file comes into being next to the old one: same filesystem, so + // the renaming at the end is one atomic step and not half a copy. It also + // comes into being before the first byte — a missing write permission ought + // to show up before a few megabytes have gone down the wire. + dir := filepath.Dir(exe) + f, err := os.CreateTemp(dir, "."+filepath.Base(exe)+".new") + if err != nil { + var pe *os.PathError // the path is in the message already + if errors.As(err, &pe) { + err = pe.Err + } + return "", fmt.Errorf("cannot write to %s: %w (use sudo, or install %s elsewhere)", dir, err, u.asset) + } + tmp := f.Name() + + resp, err := updateGet(context.Background(), a.URL) + if err != nil { + f.Close() + os.Remove(tmp) + return "", err + } + defer resp.Body.Close() + + n, err := io.Copy(f, resp.Body) + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil && a.Size > 0 && n != a.Size { + err = fmt.Errorf("got %d of %d bytes from %s", n, a.Size, a.URL) + } + if err == nil { + err = os.Chmod(tmp, mode) + } + if err != nil { + os.Remove(tmp) + return "", err + } + return tmp, nil +} + +// probe calls the freshly fetched runner once. That catches a file that is +// truncated, built for the wrong platform, or not executable in the first +// place, before it replaces the running one. +func (u selfUpdater) probe(path, tag string) error { + if len(u.verify) == 0 { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + out, err := exec.CommandContext(ctx, path, u.verify...).CombinedOutput() + if err != nil { + return fmt.Errorf("the downloaded binary does not run: %w", err) + } + if !strings.Contains(string(out), strings.TrimPrefix(tag, "v")) { + return fmt.Errorf("the downloaded binary reports %q, expected %s", + strings.TrimSpace(string(out)), tag) + } + return nil +} + +// updateReplace swaps the running file for the new one. +func updateReplace(tmp, exe string) error { + if err := os.Rename(tmp, exe); err == nil { + return nil + } + // Unix overwrites the file of a running program without complaint, Windows + // does not: there the old one has to be got out of the way first. Deleting + // it becomes possible when this process ends at the earliest — so the + // tidying up is allowed to fail. + old := exe + ".old" + os.Remove(old) + if err := os.Rename(exe, old); err != nil { + return fmt.Errorf("cannot replace %s: %w", exe, err) + } + if err := os.Rename(tmp, exe); err != nil { + os.Rename(old, exe) // back to how it was + return fmt.Errorf("cannot replace %s: %w", exe, err) + } + os.Remove(old) + return nil +} + +// -------------------------------------------------------------------- Gitea + +type updateRelease struct { + TagName string `json:"tag_name"` + HTMLURL string `json:"html_url"` + Assets []updateAsset `json:"assets"` +} + +type updateAsset struct { + Name string `json:"name"` + Size int64 `json:"size"` + URL string `json:"browser_download_url"` +} + +func (u selfUpdater) latest() (updateRelease, error) { + base, err := u.apiBase() + if err != nil { + return updateRelease{}, err + } + // The question is a small one; if it hangs, it does not hang for long. The + // generous time limit of updateClient is meant for the download. + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + resp, err := updateGet(ctx, base+"/releases/latest") + if err != nil { + return updateRelease{}, err + } + defer resp.Body.Close() + + var rel updateRelease + if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil { + return updateRelease{}, fmt.Errorf("unexpected answer from %s: %w", base, err) + } + if rel.TagName == "" { + return updateRelease{}, fmt.Errorf("%s has no releases", u.repo) + } + + // Every question that succeeds fills the note — no matter whether it came + // from --update, from --check-update or from the background run. + u.saveState(updateState{Checked: time.Now(), Latest: rel.TagName}) + return rel, nil +} + +// apiBase turns https://host/owner/repo into the API root of the repo. +func (u selfUpdater) apiBase() (string, error) { + bad := fmt.Errorf("repo %q: expected https://host/owner/repo", u.repo) + + ref, err := url.Parse(strings.TrimSuffix(strings.TrimSuffix(u.repo, "/"), ".git")) + if err != nil || ref.Host == "" { + return "", bad + } + parts := strings.Split(strings.Trim(ref.Path, "/"), "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", bad + } + return fmt.Sprintf("%s://%s/api/v1/repos/%s/%s", ref.Scheme, ref.Host, parts[0], parts[1]), nil +} + +// One time limit for all of it: the look costs a few hundred milliseconds, the +// download a few megabytes — both may hang, but not forever. +// +// The certificate is verified, plainly, by the default transport: on a host +// that cannot build the chain, the update check fails loudly rather than +// accepting whatever binary the network hands it. +var updateClient = &http.Client{Timeout: 5 * time.Minute} + +func updateGet(ctx context.Context, target string) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "selfupdate.go (+"+runtime.GOOS+"/"+runtime.GOARCH+")") + + resp, err := updateClient.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, fmt.Errorf("GET %s: %s", target, resp.Status) + } + return resp, nil +} + +// ------------------------------------------------------------------ Numbers + +// updateCompare compares two versions component by component, numerically, so +// that 1.1.10 lands behind 1.1.9 and not in front of it. A leading "v" does not +// count, missing places count as 0 (1.1 == 1.1.0), and a suffix on the number +// makes the version older, not newer (1.1.6-rc1 < 1.1.6). The result is the one +// of strings.Compare: -1, 0, 1. +func updateCompare(a, b string) int { + as := strings.Split(strings.TrimPrefix(a, "v"), ".") + bs := strings.Split(strings.TrimPrefix(b, "v"), ".") + + for i := 0; i < len(as) || i < len(bs); i++ { + x, y := "0", "0" + if i < len(as) { + x = as[i] + } + if i < len(bs) { + y = bs[i] + } + if c := updateComparePart(x, y); c != 0 { + return c + } + } + return 0 +} + +func updateComparePart(a, b string) int { + na, ra := updateSplitNum(a) + nb, rb := updateSplitNum(b) + switch { + case na != nb: + if na < nb { + return -1 + } + return 1 + case ra == rb: + return 0 + case ra == "": // 1.1.6 is finished, 1.1.6-rc1 is not yet + return 1 + case rb == "": + return -1 + } + return strings.Compare(ra, rb) +} + +// updateSplitNum separates "10-rc1" into 10 and "-rc1". +func updateSplitNum(s string) (int, string) { + i := 0 + for i < len(s) && s[i] >= '0' && s[i] <= '9' { + i++ + } + n, _ := strconv.Atoi(s[:i]) + return n, s[i:] +} + +// updateSize is deliberately a small formatting of its own — the file is meant +// to stand on its own. +func updateSize(b int64) string { + const k = 1024 + switch { + case b > k*k: + return fmt.Sprintf("%.1f MB", float64(b)/k/k) + case b > k: + return fmt.Sprintf("%.1f KB", float64(b)/k) + default: + return fmt.Sprintf("%d B", b) + } +} diff --git a/selfupdate_test.go b/selfupdate_test.go new file mode 100644 index 0000000..00e91b2 --- /dev/null +++ b/selfupdate_test.go @@ -0,0 +1,155 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestUpdateCompare(t *testing.T) { + tests := []struct { + a, b string + want int + }{ + {"1.0.1", "1.0.0", 1}, + {"1.0.10", "1.0.9", 1}, + {"v1.0.2", "1.0.2", 0}, + {"1.1", "1.1.0", 0}, + {"1.0.2-rc1", "1.0.2", -1}, + {"0.9.9", "1.0.0", -1}, + } + for _, tt := range tests { + if got := updateCompare(tt.a, tt.b); got != tt.want { + t.Errorf("updateCompare(%q, %q) = %d, want %d", tt.a, tt.b, got, tt.want) + } + } +} + +func TestUpdateAPIBase(t *testing.T) { + got, err := selfUpdate.apiBase() + if err != nil || got != "https://git.micw.org/api/v1/repos/mike/ghosttyconf" { + t.Errorf("apiBase = %q, %v", got, err) + } + if _, err := (selfUpdater{repo: "https://git.micw.org/ghosttyconf"}).apiBase(); err == nil { + t.Error("repo without owner accepted") + } +} + +// fakeForge serves a Gitea release with tag 9.9.9 whose asset is a shell +// script answering --version like ghosttyconf does. +func fakeForge(t *testing.T, size int64) (*httptest.Server, []byte) { + t.Helper() + bin := []byte("#!/bin/sh\necho ghosttyconf 9.9.9\n") + if size == 0 { + size = int64(len(bin)) + } + mux := http.NewServeMux() + var srv *httptest.Server + mux.HandleFunc("/api/v1/repos/mike/ghosttyconf/releases/latest", func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{ + "tag_name": "9.9.9", + "html_url": srv.URL + "/mike/ghosttyconf/releases/tag/9.9.9", + "assets": []map[string]any{{ + "name": fmt.Sprintf("ghosttyconf-%s-%s", runtime.GOOS, runtime.GOARCH), + "size": size, + "browser_download_url": srv.URL + "/download", + }}, + }) + }) + mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) { w.Write(bin) }) + srv = httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv, bin +} + +// isolateCache keeps the update note out of the real cache directory. +func isolateCache(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", dir) + t.Setenv("XDG_CACHE_HOME", dir) +} + +func TestUpdateCheck(t *testing.T) { + isolateCache(t) + srv, _ := fakeForge(t, 0) + u := selfUpdater{repo: srv.URL + "/mike/ghosttyconf", asset: "ghosttyconf", current: "1.0.1"} + + var out bytes.Buffer + if err := u.check(&out); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "ghosttyconf 9.9.9 is available, running 1.0.1") || + !strings.Contains(out.String(), "run 'ghosttyconf --update'") { + t.Errorf("check said %q", out.String()) + } + if st := u.loadState(); st.Latest != "9.9.9" || st.Checked.IsZero() { + t.Errorf("note after check: %+v", st) + } + + out.Reset() + u.current = "9.9.9" + if err := u.check(&out); err != nil || !strings.Contains(out.String(), "up to date") { + t.Errorf("check on the newest version said %q, %v", out.String(), err) + } +} + +func TestUpdateDownloadProbeReplace(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fake binary is a shell script") + } + isolateCache(t) + srv, bin := fakeForge(t, 0) + u := selfUpdater{repo: srv.URL + "/mike/ghosttyconf", asset: "ghosttyconf", current: "1.0.1", verify: []string{"--version"}} + rel, err := u.latest() + if err != nil { + t.Fatal(err) + } + + exe := filepath.Join(t.TempDir(), "ghosttyconf") + if err := os.WriteFile(exe, []byte("old"), 0o755); err != nil { + t.Fatal(err) + } + tmp, err := u.download(&rel.Assets[0], exe, 0o755) + if err != nil { + t.Fatal(err) + } + if filepath.Dir(tmp) != filepath.Dir(exe) { + t.Errorf("download landed in %s, not next to the binary", tmp) + } + if err := u.probe(tmp, "9.9.8"); err == nil { + t.Error("probe accepted a binary reporting another version") + } + if err := u.probe(tmp, rel.TagName); err != nil { + t.Fatal(err) + } + if err := updateReplace(tmp, exe); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(exe); !bytes.Equal(got, bin) { + t.Errorf("binary after replace: %q", got) + } +} + +func TestUpdateRejectsShortDownload(t *testing.T) { + isolateCache(t) + srv, _ := fakeForge(t, 1<<20) // the release claims more than is served + u := selfUpdater{repo: srv.URL + "/mike/ghosttyconf", asset: "ghosttyconf", current: "1.0.1"} + rel, err := u.latest() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + if _, err := u.download(&rel.Assets[0], filepath.Join(dir, "ghosttyconf"), 0o755); err == nil { + t.Fatal("short download accepted") + } + if left, _ := os.ReadDir(dir); len(left) != 0 { + t.Errorf("leftovers after a failed download: %v", left) + } +} diff --git a/tools/screenshots.sh b/tools/screenshots.sh index 5e80d1f..ebb3e60 100755 --- a/tools/screenshots.sh +++ b/tools/screenshots.sh @@ -46,9 +46,10 @@ keybind = super+k=unbind keybind = ctrl+grave_accent=toggle_quick_terminal EOF -# HOME points at the demo so the title bar shows ~/.config/ghostty/… +# HOME points at the demo so the title bar shows ~/.config/ghostty/…, and the +# update check stays off so no "newer release" lands in a screenshot. tmux new-session -d -s "$SESSION" -x $COLS -y $ROWS \ - "cd '$tmp/home' && env HOME='$tmp/home' COLORTERM=truecolor '$tmp/ghosttyconf' --no-reload" + "cd '$tmp/home' && env HOME='$tmp/home' COLORTERM=truecolor GHOSTTYCONF_NO_UPDATE_CHECK=1 '$tmp/ghosttyconf' --no-reload" sleep 2 keys() { diff --git a/version.go b/version.go index cd4f599..b6776c1 100644 --- a/version.go +++ b/version.go @@ -3,4 +3,4 @@ package main // Version is a var, not a const, so build.sh can put the built number in via // -ldflags "-X main.Version=…". The value here only ever shows up in a bare // `go build`; the version actually built is the one in version.txt. -var Version = "1.0.0" +var Version = "1.0.1" diff --git a/version.txt b/version.txt index 3eefcb9..7dea76e 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.0.0 +1.0.1