From 276e5a37568816dcc5970fa2279e0615516150a2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 15 Nov 2026 18:08:00 +0100 Subject: [PATCH] [SQUASHED] improve-auto-updates --- README.md | 22 +- docs-master/Config.md | 7 +- docs-master/dev/README.md | 1 + docs-master/dev/Update_Checks.md | 207 ++++++ go.mod | 3 +- go.sum | 2 - pkg/app/app.go | 5 +- pkg/app/entry_point.go | 60 +- pkg/app/entry_point_test.go | 98 +++ pkg/config/app_state.go | 27 +- pkg/config/user_config.go | 5 +- pkg/constants/links.go | 9 +- pkg/gocui/gui.go | 23 + pkg/gui/background.go | 12 + pkg/gui/controllers.go | 6 +- pkg/gui/controllers/helpers/update_helper.go | 458 +++++++++++-- pkg/gui/controllers/quit_actions.go | 16 - pkg/gui/controllers/status_controller.go | 15 +- pkg/gui/dummies.go | 4 +- pkg/gui/gui.go | 22 +- pkg/gui/information_panel.go | 7 +- pkg/gui/layout.go | 2 +- pkg/gui/types/common.go | 3 - pkg/gui/types/version_number.go | 7 + pkg/gui/types/version_number_test.go | 12 + pkg/i18n/english.go | 82 ++- .../status/check_for_update_in_dev_build.go | 27 + pkg/integration/tests/test_list.go | 1 + pkg/updates/build_source.go | 15 + pkg/updates/install.go | 259 +++++++ pkg/updates/install_test.go | 212 ++++++ pkg/updates/installation.go | 126 ++++ pkg/updates/installation_test.go | 159 +++++ pkg/updates/latest_version.go | 44 ++ pkg/updates/latest_version_test.go | 66 ++ pkg/updates/updates.go | 641 ++++++++++-------- pkg/updates/updates_test.go | 529 +++++++++++++++ pkg/utils/lines.go | 26 +- pkg/utils/lines_test.go | 8 + schema-master/config.json | 4 +- vendor/github.com/kardianos/osext/LICENSE | 27 - vendor/github.com/kardianos/osext/README.md | 21 - vendor/github.com/kardianos/osext/osext.go | 33 - .../github.com/kardianos/osext/osext_go18.go | 9 - .../github.com/kardianos/osext/osext_plan9.go | 22 - .../kardianos/osext/osext_procfs.go | 36 - .../kardianos/osext/osext_sysctl.go | 126 ---- .../kardianos/osext/osext_windows.go | 36 - vendor/modules.txt | 3 - 49 files changed, 2787 insertions(+), 758 deletions(-) create mode 100644 docs-master/dev/Update_Checks.md create mode 100644 pkg/app/entry_point_test.go create mode 100644 pkg/integration/tests/status/check_for_update_in_dev_build.go create mode 100644 pkg/updates/build_source.go create mode 100644 pkg/updates/install.go create mode 100644 pkg/updates/install_test.go create mode 100644 pkg/updates/installation.go create mode 100644 pkg/updates/installation_test.go create mode 100644 pkg/updates/latest_version.go create mode 100644 pkg/updates/latest_version_test.go create mode 100644 pkg/updates/updates_test.go delete mode 100644 vendor/github.com/kardianos/osext/LICENSE delete mode 100644 vendor/github.com/kardianos/osext/README.md delete mode 100644 vendor/github.com/kardianos/osext/osext.go delete mode 100644 vendor/github.com/kardianos/osext/osext_go18.go delete mode 100644 vendor/github.com/kardianos/osext/osext_plan9.go delete mode 100644 vendor/github.com/kardianos/osext/osext_procfs.go delete mode 100644 vendor/github.com/kardianos/osext/osext_sysctl.go delete mode 100644 vendor/github.com/kardianos/osext/osext_windows.go diff --git a/README.md b/README.md index ef7ac0c4a..180139eec 100644 --- a/README.md +++ b/README.md @@ -243,9 +243,23 @@ In the branches panel, lazygit can show which of your branches have an associate _Most of the above packages are maintained by third parties so be sure to vet them yourself and confirm that the maintainer is a trustworthy looking person who attends local sports games and gives back to their communities with barbeque fundraisers etc_ + + + ### Binary Releases -For Windows, Mac OS(10.12+) or Linux, you can download a binary release [here](../../releases). +For Windows, macOS (10.12+), Linux or FreeBSD, you can download a binary release [here](../../releases). + +If you install it in a folder that you can write to, lazygit keeps itself up to date. It checks for a new release once a day and offers to install it. This is also a good way to get the latest version if your package manager has an older one; uninstall it there first. + +On macOS, Linux and FreeBSD, extract `lazygit` from the archive for your platform into a folder that is on your PATH, e.g. `~/.local/bin`: + +```sh +mkdir -p ~/.local/bin +tar -xzf lazygit_*_linux_x86_64.tar.gz -C ~/.local/bin lazygit +``` + +On Windows, extract `lazygit.exe` from the zip archive for your platform into a folder such as `%LOCALAPPDATA%\Programs\lazygit`, and add that folder to your PATH. ### Dev container feature @@ -358,11 +372,13 @@ For **Debian 12 "Bookworm", Ubuntu 25.04 "Plucky Puffin"** and earlier: ```sh LAZYGIT_VERSION=$(curl -s "https://api.github.com/repos/jesseduffield/lazygit/releases/latest" | \grep -Po '"tag_name": *"v\K[^"]*') LAZYGIT_ARCH=$(uname -m | sed -e 's/aarch64/arm64/') -curl -Lo lazygit.tar.gz "https://github.com/jesseduffield/lazygit/releases/download/v${LAZYGIT_VERSION}/lazygit_${LAZYGIT_VERSION}_Linux_${LAZYGIT_ARCH}.tar.gz" +curl -Lo lazygit.tar.gz "https://github.com/jesseduffield/lazygit/releases/download/v${LAZYGIT_VERSION}/lazygit_${LAZYGIT_VERSION}_linux_${LAZYGIT_ARCH}.tar.gz" tar xf lazygit.tar.gz lazygit -sudo install lazygit -D -t /usr/local/bin/ +install lazygit -D -t ~/.local/bin/ ``` +This installs lazygit into `~/.local/bin`, so that it can keep itself up to date. On Debian and Ubuntu, the default `~/.profile` adds this folder to your PATH if it exists when you log in. + Verify the correct installation of lazygit: ```sh diff --git a/docs-master/Config.md b/docs-master/Config.md index f97dec8fb..a9f10db1b 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -588,10 +588,15 @@ worktree: # Periodic update checks update: # One of: 'prompt' (default) | 'background' | 'never' + # 'prompt': check for updates regularly, and remind you when there is one. + # 'background': like 'prompt', but if lazygit was installed from one of our + # release archives, install updates without asking. + # 'never': check for updates, and show a note in the bottom-right corner when + # there is one, but don't remind you of it. method: prompt # Period in days between update checks - days: 14 + days: 1 # Background refreshes refresher: diff --git a/docs-master/dev/README.md b/docs-master/dev/README.md index fcfcf2741..ecf344f66 100644 --- a/docs-master/dev/README.md +++ b/docs-master/dev/README.md @@ -6,3 +6,4 @@ * [Demo Recordings](./Demo_Recordings.md) * [Find base commit for fixup design](Find_Base_Commit_For_Fixup_Design.md) * [Profiling](Profiling.md) +* [Update Checks](Update_Checks.md) diff --git a/docs-master/dev/Update_Checks.md b/docs-master/dev/Update_Checks.md new file mode 100644 index 000000000..ccfd9cfec --- /dev/null +++ b/docs-master/dev/Update_Checks.md @@ -0,0 +1,207 @@ +# Update Checks + +lazygit checks for new releases and tells the user about them. If it was +installed from one of our release archives, it can also install them. The code +is in `pkg/updates` and in `UpdateHelper` (`pkg/gui/controllers/helpers`). + +Whether all of this works for users only shows in the release after the one +that contains a change, because only then is there a newer version for the +released code to find. So test changes to this feature by hand before +releasing them, following the test plan below. + +## How it works + +### Install kinds + +`DetectInstallation` decides how lazygit was installed. It looks at the build +source (`-X main.buildSource=...`), the version, and the path of the +executable: + +| Kind | How we detect it | What we offer | +|---|---|---| +| Release | build source `binaryRelease`, not in a package manager's folder | install in place, if we can write to the folder | +| Homebrew | build source `Homebrew`, or the path contains `/Cellar/lazygit/` | show the command | +| go install | build source `goInstall` (see `mergeBuildInfo`) | show the command | +| Scoop, winget, Chocolatey | path of the executable | show the command | +| Other | any other build with a release version | tell the user to check their package manager | +| Dev build | the version isn't `X.Y.Z` | nothing; `u` is disabled | + +Scoop, winget, Chocolatey, mise and others install our release archives +unchanged, so the build source of their binaries is `binaryRelease`. We must +not update those in place, because the package manager would then report the +wrong version. + +### Checks + +- At startup, if the last successful check is at least `update.days` ago + (default 1). Every hour, lazygit tests again whether a check is due. +- With `u` in the status panel. + +All install kinds compare with our latest release on GitHub. Package managers +get a new release some time later; the menu tells the user so. + +The result goes into the `updates` section of `state.yml`, which all running +instances share. + +### Telling the user + +- A note in the bottom-right corner ("Update available", or "Restart to use + vX" after an install). Clicking it opens the update menu. +- The update menu, when the user hasn't used lazygit for a minute and no popup + is open. It has "Remind me tomorrow" and "Skip this version", and a link to + the release notes in its first line. Whatever the user chooses, including + closing the menu, counts as a response, and the menu doesn't appear again for + a day. Clicking the link doesn't count. +- A message after lazygit exits, for users who never leave lazygit idle. It + appears at most once a day, and not on a day when the user responded to the + menu. It doesn't count as a response. +- The menu at startup, if the update has been available for a week and the + user never responded to the menu for it. + +Every idle instance shows the menu. Otherwise an instance that the user forgot +in some terminal tab would get the reminder every day, and the others never. +When the user responds in one instance, the others close their menus within +ten seconds. + +With `update.method: background`, lazygit installs a new release without +asking if it can. With `never`, it still checks and shows the note, but doesn't +remind the user. + +## Automated tests + +The unit tests in `pkg/updates` cover the install kinds, the asset names (against +the names of a real release), the build source in `.goreleaser.yml`, fetching +the latest version, downloading and installing against a test server, +replacing the executable on Unix and Windows, and when checks and reminders are +due. CI runs them on Windows too. + +The integration test `status/check_for_update_in_dev_build` checks that `u` is +disabled for dev builds. + +## Manual test plan + +### Setup + +Build a binary that pretends to be an older release. It finds the real latest +release on GitHub and updates to it. The code of the release that it installs +doesn't matter, so this tests exactly what the next release will do. + +```sh +mkdir -p /tmp/lg/bin /tmp/lg/config +go build -ldflags='-X main.buildSource=binaryRelease -X main.version=0.60.0' -o /tmp/lg/bin/lazygit +printf 'disableStartupPopups: true\n' > /tmp/lg/config/config.yml +``` + +Run it with `CONFIG_DIR=/tmp/lg/config /tmp/lg/bin/lazygit -debug` so that it +uses its own `config.yml` and `state.yml`, and watch the log with +`lazygit --logs` in another terminal. Edit the `updates` section of +`/tmp/lg/config/state.yml` to set up a scenario. Setting `lastcheck` to 0 makes +lazygit check at the next start; setting `lastresponse` and `lastexitmessage` +to 0 allows reminders right away. + +For the other install kinds, use these build sources: `Homebrew`, `goInstall`, +or `unknown` (Other). Set `os.openLink` in the config to something like +`echo {{link}} >> /tmp/lg/links` to see which links lazygit opens without +opening a browser. On Windows, put the binary into a folder like +`...\scoop\apps\lazygit\0.60.0\` to test the package manager detection. + +To test a real `go install` build with the code of your branch, serve the +branch to `go install` as a made-up release version through a local module +proxy. Pick a version that doesn't exist and is older than the latest release. +The separate module cache keeps the made-up version out of your real one. + +```sh +V=v0.60.99 +P=/tmp/lg/proxy/github.com/jesseduffield/lazygit/@v +mkdir -p $P +git archive --format=zip --prefix=github.com/jesseduffield/lazygit@$V/ -o $P/$V.zip HEAD +git show HEAD:go.mod > $P/$V.mod +echo "{\"Version\":\"$V\"}" > $P/$V.info +echo $V > $P/list +GOMODCACHE=/tmp/lg/modcache GOBIN=/tmp/lg/bin GOFLAGS=-modcacherw \ + GOPROXY="file:///tmp/lg/proxy,https://proxy.golang.org" \ + GONOSUMDB=github.com/jesseduffield/lazygit \ + go install github.com/jesseduffield/lazygit@$V +``` + +### Release archive in a writable folder + +- [ ] At startup, the note says "Update available". The log shows one check. +- [ ] Starting again on the same day shows the note without a check. +- [ ] `u` shows the menu with "Install now". Clicking "Release notes" in its + first line opens the releases page, and the menu stays open. +- [ ] Installing shows a waiting + status, then a toast. The note says "Restart to use vX". `lazygit + --version` shows the new version, and no temporary files are left in the + folder. +- [ ] `u` after installing shows the toast again instead of the menu. +- [ ] Clicking the note opens the menu. +- [ ] Without input, the menu appears after a minute, not earlier. It doesn't + appear while another popup is open, or while lazygit runs a + subprocess (e.g. the editor). +- [ ] Esc and "Remind me tomorrow" close the menu; the menu doesn't appear + again that day, and neither does the message after exiting. "Skip this + version" stops reminders for this version; the note stays. +- [ ] Quitting prints the message to the terminal. Quitting again on the same + day doesn't. An idle instance still shows the menu afterwards. +- [ ] With `latestversionfoundat` a week ago and `respondedversion` empty, + the menu appears at startup. +- [ ] Two instances in two terminals, both idle: both show the menu. + Responding in one closes the menu in the other within ten seconds. +- [ ] After installing in one instance, the other one closes its menu and + doesn't remind any more. Its note says "Restart to use vX" after its + next hourly check. +- [ ] `update.method: background` installs at startup without asking. +- [ ] `update.method: never`: the check happens and the note appears, but + there's no menu and no message after exiting; `u` works. +- [ ] Installed through a symlink (e.g. `~/bin/lazygit` pointing to the + binary): the update replaces the binary, and the symlink stays. + +### Release archive in a folder that isn't writable + +- [ ] Make the folder read-only, or use `/usr/local/bin` owned by root. The + menu explains that lazygit can't update itself and offers the + installation instructions instead of "Install now". The exit message + says the same. + +### Other kinds + +- [ ] `Homebrew`: the menu and the exit message show `brew upgrade lazygit`, + the menu says that package managers can take a while, and "Copy + command" copies the command. +- [ ] `goInstall`, or a real `go install` build (see above): `lazygit + --version` shows `build source=goInstall`, and the menu and the exit + message show + `go install github.com/jesseduffield/lazygit@latest`, and "Copy command" + copies it. +- [ ] `unknown` (Other): the menu tells the user to check their package + manager and offers the installation instructions. +- [ ] A binary in a mise folder (`.../mise/installs/lazygit/0.60.0/`) with + build source `binaryRelease` counts as Other. +- [ ] Dev build (`just build`, or `go install` from a branch): the + bottom-right corner shows the release that the build is based on and + its commit, e.g. `v0.66.3+d0d00783`, with `-dirty` if there are + uncommitted changes. `u` shows a popup that says why it can't check. No + note, and the log shows no check. + +### Windows + +- [ ] Installing replaces the running `lazygit.exe`. The old one remains as + `.lazygit-old-` until the next start of lazygit, which deletes + it. +- [ ] A binary in `C:\Program Files\lazygit` (not writable without admin + rights) gets the explanation instead of "Install now". +- [ ] Scoop, winget and Chocolatey folders get their commands. + +### Errors + +- [ ] Without network, the startup check only logs an error; `u` shows it. +- [ ] Installing with a broken network shows the error, and the old binary + still works. + +### After a release + +- [ ] The release assets have the names that `assetName` produces + (`TestAssetName` lists the names of a real release). +- [ ] In the release after the next one, the released version finds and + installs the new one. diff --git a/go.mod b/go.mod index 8f3b8806f..9db00ad4a 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,6 @@ require ( github.com/integrii/flaggy v1.8.0 github.com/jesseduffield/generics v0.0.0-20250517122708-b0b4a53a6f5c github.com/jesseduffield/lazycore v0.0.0-20221012050358-03d2e40243c5 - github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 github.com/karimkhaleel/jsonschema v0.0.0-20231001195015-d933f0d94ea3 github.com/kyokomi/emoji/v2 v2.2.14 github.com/lucasb-eyer/go-colorful v1.4.1 @@ -41,6 +40,7 @@ require ( github.com/stretchr/testify v1.12.1 github.com/xo/terminfo v1.2.0 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 + golang.org/x/mod v0.41.0 golang.org/x/sync v0.24.0 golang.org/x/sys v0.49.0 gopkg.in/ozeidan/fuzzy-patricia.v3 v3.0.0 @@ -66,7 +66,6 @@ require ( github.com/onsi/gomega v1.34.1 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/mod v0.41.0 // indirect golang.org/x/term v0.46.0 // indirect golang.org/x/text v0.42.0 // indirect golang.org/x/tools v0.49.0 // indirect diff --git a/go.sum b/go.sum index 7524589e5..d58a53bb9 100644 --- a/go.sum +++ b/go.sum @@ -56,8 +56,6 @@ github.com/jesseduffield/generics v0.0.0-20250517122708-b0b4a53a6f5c/go.mod h1:F github.com/jesseduffield/lazycore v0.0.0-20221012050358-03d2e40243c5 h1:CDuQmfOjAtb1Gms6a1p5L2P8RhbLUq5t8aL7PiQd2uY= github.com/jesseduffield/lazycore v0.0.0-20221012050358-03d2e40243c5/go.mod h1:qxN4mHOAyeIDLP7IK7defgPClM/z1Kze8VVQiaEjzsQ= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA= -github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= github.com/karimkhaleel/jsonschema v0.0.0-20231001195015-d933f0d94ea3 h1:s995u+gNQADMaixtNOs+jilRC/Q78q0UXSI7+4T0cDE= github.com/karimkhaleel/jsonschema v0.0.0-20231001195015-d933f0d94ea3/go.mod h1:MCbEh21gjOzxc31udr3u4QM9DAdf8TFJCZz3u5hYIxA= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= diff --git a/pkg/app/app.go b/pkg/app/app.go index c82eee112..22ed51c87 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -99,10 +99,7 @@ func NewApp(config config.AppConfigurer, test integrationTypes.IntegrationTest, app.OSCommand = oscommands.NewOSCommand(common, config, oscommands.GetPlatform(), oscommands.NewNullGuiIO(app.Log)) - updater, err := updates.NewUpdater(common, config, app.OSCommand) - if err != nil { - return app, err - } + updater := updates.NewUpdater(common, config) dirName, err := os.Getwd() if err != nil { diff --git a/pkg/app/entry_point.go b/pkg/app/entry_point.go index d69e7f4ab..e0388a14f 100644 --- a/pkg/app/entry_point.go +++ b/pkg/app/entry_point.go @@ -19,10 +19,14 @@ import ( appTypes "github.com/jesseduffield/lazygit/pkg/app/types" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/env" + "github.com/jesseduffield/lazygit/pkg/gui/types" integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types" "github.com/jesseduffield/lazygit/pkg/logs/tail" + "github.com/jesseduffield/lazygit/pkg/updates" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" + "golang.org/x/mod/module" + "golang.org/x/mod/semver" "gopkg.in/yaml.v3" ) @@ -52,7 +56,8 @@ type BuildInfo struct { func Start(buildInfo *BuildInfo, integrationTest integrationTypes.IntegrationTest) { cliArgs := parseCliArgsAndEnvVars() - mergeBuildInfo(buildInfo) + goBuildInfo, _ := debug.ReadBuildInfo() + mergeBuildInfo(buildInfo, goBuildInfo) if cliArgs.RepoPath != "" { if cliArgs.WorkTree != "" || cliArgs.GitDir != "" { @@ -277,7 +282,7 @@ func parseGitArg(gitArg string) appTypes.GitArg { // into the binary by default e.g. the git commit hash. So in this function // we merge the two together, giving priority to the stuff set by LDFLAGS. // Note: this mutates the argument passed in -func mergeBuildInfo(buildInfo *BuildInfo) { +func mergeBuildInfo(buildInfo *BuildInfo, goBuildInfo *debug.BuildInfo) { // if the version has already been set by build flags then we'll honour that. // chances are it's something like v0.31.0 which is more informative than a // commit hash. @@ -287,8 +292,7 @@ func mergeBuildInfo(buildInfo *BuildInfo) { buildInfo.Version = "unversioned" - goBuildInfo, ok := debug.ReadBuildInfo() - if !ok { + if goBuildInfo == nil { return } @@ -296,10 +300,21 @@ func mergeBuildInfo(buildInfo *BuildInfo) { return setting.Key == "vcs.revision" }) if ok { + // Built from a git checkout buildInfo.Commit = revision.Value - // if lazygit was built from source we'll show the version as the - // abbreviated commit hash - buildInfo.Version = utils.ShortHash(revision.Value) + buildInfo.Version = devBuildVersion(goBuildInfo.Main.Version, revision.Value) + } else if _, err := types.ParseVersionNumber(goBuildInfo.Main.Version); err == nil { + // Built with `go install github.com/jesseduffield/lazygit@`. + // Go doesn't record any VCS information in this case, but it does + // record the version of the module. + buildInfo.Version = strings.TrimPrefix(goBuildInfo.Main.Version, "v") + buildInfo.BuildSource = updates.BuildSourceGoInstall + } else if rev, err := module.PseudoVersionRev(goBuildInfo.Main.Version); err == nil { + // Built with `go install github.com/jesseduffield/lazygit@`. + // The module version is a pseudo-version, which contains the commit + // and the release that it is based on. + buildInfo.Commit = rev + buildInfo.Version = devBuildVersion(goBuildInfo.Main.Version, rev) } // if version hasn't been set we assume that neither has the date @@ -311,6 +326,37 @@ func mergeBuildInfo(buildInfo *BuildInfo) { } } +// devBuildVersion returns the version that we show for a build that isn't a +// release: the release that it is based on, and the commit, e.g. +// "v0.66.3+d0d00783", plus "-dirty" if it has uncommitted changes. +// moduleVersion is the version that Go recorded for the main module: a +// pseudo-version, or the tag of the commit, followed by "+dirty" if there were +// uncommitted changes. +func devBuildVersion(moduleVersion string, commit string) string { + moduleVersion, buildMetadata, _ := strings.Cut(moduleVersion, "+") + version := utils.ShortHash(commit) + if base := releaseBaseVersion(moduleVersion); base != "" { + version = base + "+" + version + } + if buildMetadata == "dirty" { + version += "-dirty" + } + return version +} + +// releaseBaseVersion returns the release that a module version is, or is based +// on, or "" if there is none +func releaseBaseVersion(moduleVersion string) string { + if module.IsPseudoVersion(moduleVersion) { + base, _ := module.PseudoVersionBase(moduleVersion) + return base + } + if semver.IsValid(moduleVersion) { + return moduleVersion + } + return "" +} + func getGitVersionInfo() string { cmd := exec.Command("git", "--version") stdout, _ := cmd.Output() diff --git a/pkg/app/entry_point_test.go b/pkg/app/entry_point_test.go new file mode 100644 index 000000000..b42add7e0 --- /dev/null +++ b/pkg/app/entry_point_test.go @@ -0,0 +1,98 @@ +package app + +import ( + "runtime/debug" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestMergeBuildInfo(t *testing.T) { + scenarios := []struct { + name string + buildInfo BuildInfo + goBuildInfo *debug.BuildInfo + expected BuildInfo + }{ + { + name: "version set by ldflags", + buildInfo: BuildInfo{Version: "0.66.2", BuildSource: "binaryRelease"}, + goBuildInfo: &debug.BuildInfo{ + Main: debug.Module{Version: "(devel)"}, + Settings: []debug.BuildSetting{{Key: "vcs.revision", Value: "0123456789abcdef"}}, + }, + expected: BuildInfo{Version: "0.66.2", BuildSource: "binaryRelease"}, + }, + { + name: "built from a git checkout", + buildInfo: BuildInfo{BuildSource: "unknown"}, + goBuildInfo: &debug.BuildInfo{ + Main: debug.Module{Version: "v0.66.3-0.20261103120000-0123456789ab+dirty"}, + Settings: []debug.BuildSetting{ + {Key: "vcs.revision", Value: "0123456789abcdef"}, + {Key: "vcs.time", Value: "2026-11-03T12:00:00Z"}, + }, + }, + expected: BuildInfo{ + Commit: "0123456789abcdef", + Date: "2026-11-03T12:00:00Z", + Version: "v0.66.2+01234567-dirty", + BuildSource: "unknown", + }, + }, + { + name: "built from a git checkout at a tag", + buildInfo: BuildInfo{BuildSource: "unknown"}, + goBuildInfo: &debug.BuildInfo{ + Main: debug.Module{Version: "v0.66.2"}, + Settings: []debug.BuildSetting{{Key: "vcs.revision", Value: "0123456789abcdef"}}, + }, + expected: BuildInfo{Commit: "0123456789abcdef", Version: "v0.66.2+01234567", BuildSource: "unknown"}, + }, + { + name: "built from a git checkout without module version", + buildInfo: BuildInfo{BuildSource: "unknown"}, + goBuildInfo: &debug.BuildInfo{ + Main: debug.Module{Version: "(devel)"}, + Settings: []debug.BuildSetting{{Key: "vcs.revision", Value: "0123456789abcdef"}}, + }, + expected: BuildInfo{Commit: "0123456789abcdef", Version: "01234567", BuildSource: "unknown"}, + }, + { + name: "built with go install", + buildInfo: BuildInfo{BuildSource: "unknown"}, + goBuildInfo: &debug.BuildInfo{Main: debug.Module{Version: "v0.66.2"}}, + expected: BuildInfo{Version: "0.66.2", BuildSource: "goInstall"}, + }, + { + name: "built with go install from a branch", + buildInfo: BuildInfo{BuildSource: "unknown"}, + goBuildInfo: &debug.BuildInfo{ + Main: debug.Module{Version: "v0.66.3-0.20261103120000-0123456789ab"}, + }, + expected: BuildInfo{Commit: "0123456789ab", Version: "v0.66.2+01234567", BuildSource: "unknown"}, + }, + { + name: "built with go install from a branch without tags", + buildInfo: BuildInfo{BuildSource: "unknown"}, + goBuildInfo: &debug.BuildInfo{ + Main: debug.Module{Version: "v0.0.0-20261103120000-0123456789ab"}, + }, + expected: BuildInfo{Commit: "0123456789ab", Version: "01234567", BuildSource: "unknown"}, + }, + { + name: "no build info", + buildInfo: BuildInfo{BuildSource: "unknown"}, + goBuildInfo: nil, + expected: BuildInfo{Version: "unversioned", BuildSource: "unknown"}, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + buildInfo := s.buildInfo + mergeBuildInfo(&buildInfo, s.goBuildInfo) + assert.Equal(t, s.expected, buildInfo) + }) + } +} diff --git a/pkg/config/app_state.go b/pkg/config/app_state.go index b1e55caa5..9a0d9c258 100644 --- a/pkg/config/app_state.go +++ b/pkg/config/app_state.go @@ -235,7 +235,6 @@ func writeAndClose(file *os.File, content []byte) error { // AppState stores data between runs of the app like when the last update check // was performed and which other repos have been checked out type AppState struct { - LastUpdateCheck int64 RecentRepos []string StartupPopupVersion int LastVersion string // this is the last version the user was using, for the purpose of showing release notes @@ -245,6 +244,32 @@ type AppState struct { ShellCommandsHistory []string `yaml:"customcommandshistory"` HideCommandLog bool + + Updates UpdatesState +} + +// UpdatesState is what lazygit remembers about updates +type UpdatesState struct { + // When the last successful check for an update happened (Unix time), and + // the latest version that it found + LastCheck int64 + LatestVersion string + // When a check first found LatestVersion + LatestVersionFoundAt int64 + + // When the user last responded to the update menu, in any lazygit + // instance, and the version that the menu was for + LastResponse int64 + RespondedVersion string + // The version that the user doesn't want to be reminded of + SkippedVersion string + // When lazygit last printed a reminder after exiting + LastExitMessage int64 + + // The version that an update installed in place of the executable at + // InstalledPath. It takes effect when lazygit is restarted. + InstalledVersion string + InstalledPath string } func getDefaultAppState() *AppState { diff --git a/pkg/config/user_config.go b/pkg/config/user_config.go index f86174651..72d39ca19 100644 --- a/pkg/config/user_config.go +++ b/pkg/config/user_config.go @@ -459,6 +459,9 @@ type WorktreeConfig struct { type UpdateConfig struct { // One of: 'prompt' (default) | 'background' | 'never' + // 'prompt': check for updates regularly, and remind you when there is one. + // 'background': like 'prompt', but if lazygit was installed from one of our release archives, install updates without asking. + // 'never': check for updates, and show a note in the bottom-right corner when there is one, but don't remind you of it. Method string `yaml:"method" jsonschema:"enum=prompt,enum=background,enum=never"` // Period in days between update checks Days int64 `yaml:"days" jsonschema:"minimum=0"` @@ -1005,7 +1008,7 @@ func GetDefaultConfigForPlatform(platform string) *UserConfig { }, Update: UpdateConfig{ Method: "prompt", - Days: 14, + Days: 1, }, ConfirmOnQuit: false, QuitOnTopLevelReturn: false, diff --git a/pkg/constants/links.go b/pkg/constants/links.go index 964d4d52f..9e2983951 100644 --- a/pkg/constants/links.go +++ b/pkg/constants/links.go @@ -16,10 +16,13 @@ var Links = struct { Issues string RepoUrl string Releases string + // Released binaries link here, so the anchor must never change + InstallationInstructions string }{ - RepoUrl: "https://github.com/jesseduffield/lazygit", - Issues: "https://github.com/jesseduffield/lazygit/issues", - Releases: "https://github.com/jesseduffield/lazygit/releases", + RepoUrl: "https://github.com/jesseduffield/lazygit", + Issues: "https://github.com/jesseduffield/lazygit/issues", + Releases: "https://github.com/jesseduffield/lazygit/releases", + InstallationInstructions: "https://github.com/jesseduffield/lazygit#install-the-latest-release", Docs: Docs{ CustomDiffRenderers: "https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_DiffRenderers.md", CustomKeybindings: "https://github.com/jesseduffield/lazygit/blob/master/docs/keybindings/Custom_Keybindings.md", diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 9af69f305..79f93a723 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -258,6 +258,10 @@ type Gui struct { blockInputCount int bufferedInputEvents []GocuiEvent replayPending bool + + // When the user last pressed a key, used the mouse, or pasted (Unix + // nanoseconds); see TimeSinceLastInput + lastInputTime atomic.Int64 } type NewGuiOpts struct { @@ -276,6 +280,7 @@ type NewGuiOpts struct { // NewGui returns a new Gui object with a given output mode. func NewGui(opts NewGuiOpts) (*Gui, error) { g := &Gui{} + g.lastInputTime.Store(time.Now().UnixNano()) var err error if opts.Headless { @@ -1266,6 +1271,10 @@ func (g *Gui) processRemainingEvents() (bool, error) { // handleEvent handles an event, based on its type (key-press, error, // etc.) func (g *Gui) handleEvent(ev *GocuiEvent) error { + if isUserInput(ev) { + g.lastInputTime.Store(time.Now().UnixNano()) + } + if g.withholdingInput() && eventWithheldWhileBlocking(ev) { if ev.Type == eventKey || ev.Type == eventPaste { // Buffer keys so they replay against fresh state on unblock. Buffer @@ -1300,6 +1309,10 @@ func (g *Gui) handleEvent(ev *GocuiEvent) error { } } +func isUserInput(ev *GocuiEvent) bool { + return ev.Type == eventKey || ev.Type == eventMouse || ev.Type == eventMouseMove || ev.Type == eventPaste +} + // withholdingInput reports whether events are being kept from the handlers. They // are while a block is in force, and on until the keys it buffered have been // replayed. @@ -2232,6 +2245,10 @@ func (g *Gui) Resume() error { g.suspended = false + // The user was busy in the subprocess, so the time we were suspended + // doesn't count as idle time + g.lastInputTime.Store(time.Now().UnixNano()) + // Schedule a redraw of the whole screen. Nothing else guarantees one: // flushes are skipped while suspended, and after re-engaging the screen // the terminal shows nothing until we draw again. @@ -2240,6 +2257,12 @@ func (g *Gui) Resume() error { return nil } +// TimeSinceLastInput returns how long ago the user last pressed a key, used the +// mouse, or pasted. Time spent in a subprocess doesn't count. +func (g *Gui) TimeSinceLastInput() time.Duration { + return time.Since(time.Unix(0, g.lastInputTime.Load())) +} + func (g *Gui) isSuspended() bool { g.suspendedMutex.Lock() defer g.suspendedMutex.Unlock() diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 6a4c529a1..3f05d05aa 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -80,6 +80,18 @@ func (self *BackgroundRoutineMgr) startBackgroundRoutines() { } } + // The check itself happens at most once a day (see update.days); checking + // every hour whether it is due makes sure that it happens even if lazygit + // keeps running for days. + self.goEvery(time.Hour, self.gui.stopChan, nil, func(_ bool) error { + self.gui.helpers.Update.CheckForUpdateInBackground() + return nil + }) + self.goEvery(10*time.Second, self.gui.stopChan, nil, func(_ bool) error { + self.gui.helpers.Update.RemindIfDue() + return nil + }) + if self.gui.Config.GetDebug() { self.goEvery(time.Second*time.Duration(10), self.gui.stopChan, nil, func(_ bool) error { formatBytes := func(b uint64) string { diff --git a/pkg/gui/controllers.go b/pkg/gui/controllers.go index e0915915f..8e1b49d19 100644 --- a/pkg/gui/controllers.go +++ b/pkg/gui/controllers.go @@ -87,6 +87,8 @@ func (gui *Gui) resetHelpersAndControllers() { modeHelper, ) + confirmationHelper := helpers.NewConfirmationHelper(helperCommon) + gui.helpers = &helpers.Helpers{ Refs: refsHelper, Host: helpers.NewHostHelper(helperCommon), @@ -111,11 +113,11 @@ func (gui *Gui) resetHelpersAndControllers() { DiffLine: diffLineHelper, Repos: reposHelper, RecordDirectory: recordDirectoryHelper, - Update: helpers.NewUpdateHelper(helperCommon, gui.Updater), + Update: helpers.NewUpdateHelper(helperCommon, gui.Updater, confirmationHelper), Window: windowHelper, View: viewHelper, Refresh: refreshHelper, - Confirmation: helpers.NewConfirmationHelper(helperCommon), + Confirmation: confirmationHelper, Mode: modeHelper, AppStatus: appStatusHelper, InlineStatus: helpers.NewInlineStatusHelper(helperCommon, windowHelper), diff --git a/pkg/gui/controllers/helpers/update_helper.go b/pkg/gui/controllers/helpers/update_helper.go index a108b0bf4..2feb5545e 100644 --- a/pkg/gui/controllers/helpers/update_helper.go +++ b/pkg/gui/controllers/helpers/update_helper.go @@ -2,101 +2,435 @@ package helpers import ( "errors" + "path/filepath" + "strings" + "sync/atomic" + "time" + "github.com/jesseduffield/lazygit/pkg/constants" "github.com/jesseduffield/lazygit/pkg/gocui" + "github.com/jesseduffield/lazygit/pkg/gui/context" + "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/updates" "github.com/jesseduffield/lazygit/pkg/utils" ) type UpdateHelper struct { - c *HelperCommon - updater *updates.Updater + c *HelperCommon + updater *updates.Updater + confirmationHelper *ConfirmationHelper + + // When we showed the update menu (Unix time), or 0 if it isn't showing + menuShownAt atomic.Int64 + // The prompt of the update menu, to recognize it. Only accessed on the UI + // thread. + menuPrompt string } -func NewUpdateHelper(c *HelperCommon, updater *updates.Updater) *UpdateHelper { +func NewUpdateHelper(c *HelperCommon, updater *updates.Updater, confirmationHelper *ConfirmationHelper) *UpdateHelper { return &UpdateHelper{ - c: c, - updater: updater, + c: c, + updater: updater, + confirmationHelper: confirmationHelper, } } +// The link of the note that tells the user about an update +const UpdateNoteLink = "lazygit-update:" + +// How long the user must not have used lazygit before we remind them of an +// update +const idleTimeBeforeReminder = time.Minute + +func (self *UpdateHelper) OnStartup() { + self.c.OnWorkerBackground(func(gocui.Task) error { + self.updater.CleanUpAfterUpdate() + self.CheckForUpdateInBackground() + self.RemindIfDue() + return nil + }) +} + +// RemindIfDue shows the update menu if the user hasn't used lazygit for a +// while, and a reminder is due. Every lazygit instance that is idle shows it, +// so that one that the user forgot about in some terminal tab doesn't keep the +// others from reminding them. When the user responds to the menu in one of +// them, the others close theirs. Call it on a worker. +func (self *UpdateHelper) RemindIfDue() { + if shownAt := self.menuShownAt.Load(); shownAt != 0 { + if self.updater.IsHandledAfter(time.Unix(shownAt, 0)) { + self.c.OnUIThreadBackground(self.closeUpdateMenu) + } + return + } + + reminder := updates.ReminderMenuWhenIdle + if self.updater.IsStartingUp() { + reminder = updates.ReminderMenuAtStartup + } else if self.c.GocuiGui().TimeSinceLastInput() < idleTimeBeforeReminder { + return + } + + version := self.updater.DueReminder(reminder) + if version == nil { + return + } + + menuOpts := self.updateMenuOptions(version) + self.c.OnUIThreadBackground(func() error { + // Don't get in the way of whatever the user is doing in a popup; we'll + // try again later + if self.confirmationHelper.IsPopupPanelFocused() { + return nil + } + return self.showUpdateMenu(menuOpts) + }) +} + +// showUpdateMenu shows the update menu, and remembers that it is showing. Call +// it on the UI thread. +func (self *UpdateHelper) showUpdateMenu(menuOpts types.CreateMenuOptions) error { + self.menuPrompt = menuOpts.Prompt + self.menuShownAt.Store(time.Now().Unix()) + return self.c.Menu(menuOpts) +} + +// closeUpdateMenu closes the update menu without counting this as a response, +// because the user responded in another lazygit. Call it on the UI thread. +func (self *UpdateHelper) closeUpdateMenu() error { + if self.menuShownAt.Swap(0) == 0 { + return nil + } + + // Leave the menu alone if something else is on top of it; the user can + // close it themselves then + menu := self.c.Contexts().Menu + if self.c.Context().Current().GetKey() == context.MENU_CONTEXT_KEY && menu.GetPrompt() == self.menuPrompt { + self.c.Context().Pop() + } + return nil +} + +// recordResponse records that the user responded to the update menu. Call it +// on the UI thread. +func (self *UpdateHelper) recordResponse(version *types.VersionNumber) { + self.menuShownAt.Store(0) + self.c.OnWorkerBackground(func(gocui.Task) error { + self.updater.RecordResponse(version) + return nil + }) +} + +// CheckForUpdateInBackground checks for an update if one is due, and shows the +// result in the note in the bottom-right corner. If the user config asks for it, +// it also installs the update. Call it on a worker. func (self *UpdateHelper) CheckForUpdateInBackground() { - self.updater.CheckForNewUpdate(func(newVersion string, err error) error { - if err != nil { - // ignoring the error for now so that I'm not annoying users - self.c.Log.Error(err.Error()) - return nil + if err := self.updater.CheckForUpdateIfDue(); err != nil { + self.c.Log.Errorf("Error checking for an update: %v", err) + } + + if version := self.updater.VersionToInstallInBackground(); version != nil { + if err := self.updater.Install(version); err != nil { + // We'll try again later; until then, the user gets reminders + // with the option to install the update themselves. + self.c.Log.Errorf("Error installing %s: %v", version, err) + } else { + self.c.OnUIThreadBackground(func() error { + self.c.Toast(self.updateInstalledMessage(version)) + return nil + }) } - if newVersion == "" { - return nil + } + + self.rerenderNote() +} + +func (self *UpdateHelper) rerenderNote() { + // The information view is rendered in every layout, so we only need to + // trigger one + self.c.OnUIThreadBackground(func() error { return nil }) +} + +// Note returns the note that tells the user about an update, for the bottom-right +// corner, or "" if there's nothing to tell +func (self *UpdateHelper) Note() string { + if !self.updater.ChecksEnabled() { + return "" + } + + status := self.updater.Status() + if status.InstalledVersion != nil { + return style.FgGreen.Sprint(utils.ResolvePlaceholderString( + self.c.Tr.RestartToUseNewVersion, map[string]string{"newVersion": status.InstalledVersion.String()}, + )) + } + if status.AvailableVersion != nil { + return style.FgGreen.Sprint(style.PrintHyperlink(self.c.Tr.UpdateAvailableNote, UpdateNoteLink)) + } + return "" +} + +// ExitMessage returns a message about an available update that we print after +// lazygit exits, or "" if no reminder is due. This reaches users who never +// leave lazygit idle, and they are in the shell, where they can update right +// away. +func (self *UpdateHelper) ExitMessage() string { + version := self.updater.ClaimExitMessage() + if version == nil { + return "" + } + + lines := []string{utils.ResolvePlaceholderString( + self.c.Tr.ExitMessageNewVersionAvailable, + map[string]string{ + "newVersion": version.String(), + "currentVersion": self.updater.CurrentVersion().String(), + }, + )} + + installation := self.updater.Installation() + installationInstructions := utils.ResolvePlaceholderString( + self.c.Tr.ExitMessageInstallationInstructions, + map[string]string{"url": constants.Links.InstallationInstructions}, + ) + switch { + case installation.Kind == updates.InstallKindRelease: + if err := self.updater.CheckCanInstall(); err != nil { + lines = append(lines, + utils.ResolvePlaceholderString( + self.c.Tr.UpdateFolderNotWritable, + map[string]string{"folder": filepath.Dir(installation.ExecutablePath)}, + ), + installationInstructions, + ) + } else if key := self.c.UserConfig().Keybinding.Status.CheckForUpdate.String(); key != "" { + lines = append(lines, utils.ResolvePlaceholderString( + self.c.Tr.ExitMessageInstallWithKey, map[string]string{"key": key}, + )) } - if self.c.UserConfig().Update.Method == "background" { - self.startUpdating(newVersion) - return nil + case installation.UpdateCommand() != "": + lines = append(lines, utils.ResolvePlaceholderString( + self.c.Tr.ExitMessageUpdateCommand, map[string]string{"command": installation.UpdateCommand()}, + )) + default: + lines = append(lines, self.c.Tr.ExitMessageCheckPackageManager, installationInstructions) + } + + lines = append(lines, + utils.ResolvePlaceholderString( + self.c.Tr.ExitMessageReleaseNotes, map[string]string{"url": constants.Links.Releases}, + ), + self.c.Tr.TurnOffUpdateReminders, + ) + return strings.Join(lines, "\n") +} + +// ShowUpdateMenu shows the menu for the update that the note in the +// bottom-right corner tells the user about +func (self *UpdateHelper) ShowUpdateMenu() error { + status := self.updater.Status() + if status.AvailableVersion == nil || status.InstalledVersion != nil { + return nil + } + + self.c.OnWorker(func(gocui.Task) error { + menuOpts := self.updateMenuOptions(status.AvailableVersion) + self.c.OnUIThread(func() error { + return self.showUpdateMenu(menuOpts) + }) + return nil + }) + return nil +} + +func (self *UpdateHelper) CheckForUpdateDisabledReason() *types.DisabledReason { + if self.updater.Installation().Kind == updates.InstallKindDevBuild { + return &types.DisabledReason{ + Text: utils.ResolvePlaceholderString( + self.c.Tr.UpdateCheckNotPossibleForDevBuild, + map[string]string{"version": self.c.GetConfig().GetVersion()}, + ), + // The user asked for the check, so make sure they see why it + // doesn't happen + ShowErrorInPanel: true, } - return self.showUpdatePrompt(newVersion) - }, false) + } + + if self.updater.IsInstalling() { + return &types.DisabledReason{Text: self.c.Tr.UpdateAlreadyInProgress} + } + + return nil } func (self *UpdateHelper) CheckForUpdateInForeground() error { return self.c.WithWaitingStatus(self.c.Tr.CheckingForUpdates, func(gocui.Task) error { - self.updater.CheckForNewUpdate(func(newVersion string, err error) error { - if err != nil { - return err - } - if newVersion == "" { - return errors.New(self.c.Tr.FailedToRetrieveLatestVersionErr) - } - return self.showUpdatePrompt(newVersion) - }, true) - - return nil - }) -} - -func (self *UpdateHelper) startUpdating(newVersion string) { - _ = self.c.WithWaitingStatus(self.c.Tr.UpdateInProgressWaitingStatus, func(gocui.Task) error { - self.c.State().SetUpdating(true) - err := self.updater.Update(newVersion) - return self.onUpdateFinish(err) - }) -} - -func (self *UpdateHelper) onUpdateFinish(err error) error { - self.c.State().SetUpdating(false) - self.c.OnUIThread(func() error { - self.c.SetViewContent(self.c.Views().AppStatus, "") + newVersion, err := self.updater.CheckForUpdate() if err != nil { - errMessage := utils.ResolvePlaceholderString( - self.c.Tr.UpdateFailedErr, map[string]string{ - "errMessage": err.Error(), - }, - ) - return errors.New(errMessage) + return errors.New(utils.ResolvePlaceholderString( + self.c.Tr.UpdateCheckFailed, map[string]string{"error": err.Error()}, + )) } - self.c.Alert(self.c.Tr.UpdateCompletedTitle, self.c.Tr.UpdateCompleted) + + if newVersion == nil { + self.c.OnUIThread(func() error { + self.c.Alert(self.c.Tr.NoUpdateAvailableTitle, utils.ResolvePlaceholderString( + self.c.Tr.NoUpdateAvailable, + map[string]string{"currentVersion": self.updater.CurrentVersion().String()}, + )) + return nil + }) + return nil + } + + if installedVersion := self.updater.Status().InstalledVersion; installedVersion != nil && !installedVersion.IsOlderThan(newVersion) { + self.c.OnUIThread(func() error { + self.c.Toast(self.updateInstalledMessage(installedVersion)) + return nil + }) + return nil + } + + menuOpts := self.updateMenuOptions(newVersion) + self.c.OnUIThread(func() error { + return self.showUpdateMenu(menuOpts) + }) return nil }) - - return nil } -func (self *UpdateHelper) showUpdatePrompt(newVersion string) error { - message := utils.ResolvePlaceholderString( - self.c.Tr.UpdateAvailable, map[string]string{ - "newVersion": newVersion, +// updateMenuOptions returns the options for the menu that tells the user about +// a new version. Call it on a worker, because it accesses the file system. +func (self *UpdateHelper) updateMenuOptions(newVersion *types.VersionNumber) types.CreateMenuOptions { + installation := self.updater.Installation() + // The release notes are a link rather than a menu item, because choosing a + // menu item closes the menu + paragraphs := []string{utils.ResolvePlaceholderString( + self.c.Tr.NewVersionAvailable, + map[string]string{ + "newVersion": newVersion.String(), + "currentVersion": self.updater.CurrentVersion().String(), + "releaseNotes": style.PrintHyperlink(self.c.Tr.ReleaseNotes, constants.Links.Releases), + }, + )} + items := []*types.MenuItem{} + + switch installation.Kind { + case updates.InstallKindRelease: + if err := self.updater.CheckCanInstall(); err != nil { + self.c.Log.Infof("Can't install the update: %v", err) + paragraphs = append(paragraphs, utils.ResolvePlaceholderString( + self.c.Tr.UpdateFolderNotWritable, + map[string]string{"folder": filepath.Dir(installation.ExecutablePath)}, + )) + items = append(items, self.openInstallationInstructionsMenuItem()) + } else { + items = append(items, &types.MenuItem{ + Label: self.c.Tr.InstallUpdateNow, + OnPress: func() error { return self.install(newVersion) }, + }) + } + + case updates.InstallKindHomebrew, updates.InstallKindGoInstall, updates.InstallKindScoop, + updates.InstallKindWinget, updates.InstallKindChocolatey: + paragraphs = append(paragraphs, utils.ResolvePlaceholderString( + self.c.Tr.UpdateWithPackageManager, + map[string]string{ + "packageManager": installation.PackageManagerName(), + "command": installation.UpdateCommand(), + }, + )) + if installation.Kind != updates.InstallKindGoInstall { + paragraphs = append(paragraphs, self.c.Tr.PackageManagersCanBeSlow) + } + items = append(items, &types.MenuItem{ + Label: self.c.Tr.CopyUpdateCommand, + OnPress: func() error { + if err := self.c.OS().CopyToClipboard(installation.UpdateCommand()); err != nil { + return err + } + self.c.Toast(self.c.Tr.UpdateCommandCopiedToClipboard) + return nil + }, + }) + + default: + paragraphs = append(paragraphs, self.c.Tr.UpdateFromPackageManagerOrRelease) + items = append(items, self.openInstallationInstructionsMenuItem()) + } + + items = append(items, + &types.MenuItem{ + Label: self.c.Tr.RemindMeTomorrow, + // Recording the response below is all it takes + OnPress: func() error { return nil }, + }, + &types.MenuItem{ + Label: self.c.Tr.SkipThisVersion, + OnPress: func() error { + self.c.OnWorkerBackground(func(gocui.Task) error { + self.updater.SkipVersion(newVersion) + return nil + }) + return nil + }, }, ) + paragraphs = append(paragraphs, self.c.Tr.TurnOffUpdateReminders) - self.c.Confirm(types.ConfirmOpts{ - Title: self.c.Tr.UpdateAvailableTitle, - Prompt: message, - HandleConfirm: func() error { - self.startUpdating(newVersion) + // Whatever the user chooses counts as a response, and so does closing the + // menu + for _, item := range items { + onPress := item.OnPress + item.OnPress = func() error { + self.recordResponse(newVersion) + return onPress() + } + } + + return types.CreateMenuOptions{ + Title: self.c.Tr.UpdateAvailableTitle, + Prompt: strings.Join(paragraphs, "\n\n"), + Items: items, + HideCancel: true, + OnCancel: func() error { + self.recordResponse(newVersion) return nil }, + } +} + +func (self *UpdateHelper) openInstallationInstructionsMenuItem() *types.MenuItem { + return &types.MenuItem{ + Label: self.c.Tr.OpenInstallationInstructions, + OnPress: func() error { return self.c.OS().OpenLink(constants.Links.InstallationInstructions) }, + } +} + +func (self *UpdateHelper) install(newVersion *types.VersionNumber) error { + status := utils.ResolvePlaceholderString( + self.c.Tr.InstallingUpdateStatus, map[string]string{"newVersion": newVersion.String()}, + ) + return self.c.WithWaitingStatus(status, func(gocui.Task) error { + err := self.updater.Install(newVersion) + self.c.OnUIThread(func() error { + if err != nil { + return errors.New(utils.ResolvePlaceholderString( + self.c.Tr.UpdateInstallFailed, + map[string]string{"newVersion": newVersion.String(), "error": err.Error()}, + )) + } + + self.c.Toast(self.updateInstalledMessage(newVersion)) + return nil + }) + return nil }) +} - return nil +func (self *UpdateHelper) updateInstalledMessage(version *types.VersionNumber) string { + return utils.ResolvePlaceholderString( + self.c.Tr.UpdateInstalled, map[string]string{"newVersion": version.String()}, + ) } diff --git a/pkg/gui/controllers/quit_actions.go b/pkg/gui/controllers/quit_actions.go index 9a7082542..028d6c8cb 100644 --- a/pkg/gui/controllers/quit_actions.go +++ b/pkg/gui/controllers/quit_actions.go @@ -20,10 +20,6 @@ func (self *QuitActions) QuitWithoutChangingDirectory() error { } func (self *QuitActions) quitAux() error { - if self.c.State().GetUpdating() { - return self.confirmQuitDuringUpdate() - } - return self.c.ConfirmIf(self.c.UserConfig().ConfirmOnQuit, types.ConfirmOpts{ Title: "", @@ -34,18 +30,6 @@ func (self *QuitActions) quitAux() error { }) } -func (self *QuitActions) confirmQuitDuringUpdate() error { - self.c.Confirm(types.ConfirmOpts{ - Title: self.c.Tr.ConfirmQuitDuringUpdateTitle, - Prompt: self.c.Tr.ConfirmQuitDuringUpdate, - HandleConfirm: func() error { - return gocui.ErrQuit - }, - }) - - return nil -} - func (self *QuitActions) Escape() error { // If you make changes to this function, be sure to update EscapeEnabled and EscapeDescription accordingly. diff --git a/pkg/gui/controllers/status_controller.go b/pkg/gui/controllers/status_controller.go index adc8e869c..a81cfc4ba 100644 --- a/pkg/gui/controllers/status_controller.go +++ b/pkg/gui/controllers/status_controller.go @@ -38,10 +38,11 @@ func (self *StatusController) GetKeybindings(opts types.KeybindingsOpts) []*type DisplayOnScreen: true, }, { - Keys: opts.GetKeys(opts.Config.Status.CheckForUpdate), - Handler: self.handleCheckForUpdate, - Description: self.c.Tr.CheckForUpdate, - DisplayOnScreen: true, + Keys: opts.GetKeys(opts.Config.Status.CheckForUpdate), + Handler: self.c.Helpers().Update.CheckForUpdateInForeground, + GetDisabledReason: self.c.Helpers().Update.CheckForUpdateDisabledReason, + Description: self.c.Tr.CheckForUpdate, + DisplayOnScreen: true, }, { Keys: opts.GetKeys(opts.Config.Status.RecentRepos), @@ -191,7 +192,7 @@ func (self *StatusController) showDashboard() { // Don't just take the version string as is, but format it again. This // way it will be correct even if a distribution omits the "v", or the // ".0" at the end. - versionStr = fmt.Sprintf("v%d.%d.%d", version.Major, version.Minor, version.Patch) + versionStr = version.String() } dashboardString := strings.Join( @@ -213,7 +214,3 @@ func (self *StatusController) showDashboard() { }, }) } - -func (self *StatusController) handleCheckForUpdate() error { - return self.c.Helpers().Update.CheckForUpdateInForeground() -} diff --git a/pkg/gui/dummies.go b/pkg/gui/dummies.go index 979f818e1..a92d69af3 100644 --- a/pkg/gui/dummies.go +++ b/pkg/gui/dummies.go @@ -2,7 +2,6 @@ package gui import ( "github.com/jesseduffield/lazygit/pkg/commands/git_commands" - "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/updates" @@ -10,8 +9,7 @@ import ( func NewDummyUpdater() *updates.Updater { newAppConfig := config.NewDummyAppConfig() - dummyUpdater, _ := updates.NewUpdater(common.NewDummyCommon(), newAppConfig, oscommands.NewDummyOSCommand()) - return dummyUpdater + return updates.NewUpdater(common.NewDummyCommon(), newAppConfig) } // NewDummyGui creates a new dummy GUI for testing diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 16e3fa51d..bf7167197 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -148,8 +148,6 @@ type Gui struct { // for accessing the gui's state from outside this package stateAccessor *StateAccessor - Updating bool - c *helpers.HelperCommon helpers *helpers.Helpers @@ -170,14 +168,6 @@ func (self *StateAccessor) GetRepoPathStack() *utils.Stack[types.RepoLocation] { return self.gui.RepoPathStack } -func (self *StateAccessor) GetUpdating() bool { - return self.gui.Updating -} - -func (self *StateAccessor) SetUpdating(value bool) { - self.gui.Updating = value -} - func (self *StateAccessor) GetRepoState() types.IRepoStateAccessor { return self.gui.State } @@ -418,6 +408,10 @@ func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.Context return gui.helpers.Diff.EditFilesOfDiff([]string{filepath}) } + if url == helpers.UpdateNoteLink { + return gui.helpers.Update.ShowUpdateMenu() + } + if entry, ok := strings.CutPrefix(url, helpers.DiffStatLinkScheme); ok { view, err := gui.g.View(viewname) if err != nil { @@ -1070,6 +1064,10 @@ func (gui *Gui) RunAndHandleError(startArgs appTypes.StartArgs) error { // so that they don't outlive lazygit. oscommands.TerminateLivePtys() + // Don't exit in the middle of replacing the executable with an + // update, or the user might be left without a lazygit binary + gui.Updater.WaitForInstallToFinish() + close(gui.stopChan) if errors.Is(err, gocui.ErrQuit) && !errors.As(err, &types.ErrQuitWithMessage{}) { @@ -1083,6 +1081,10 @@ func (gui *Gui) RunAndHandleError(startArgs appTypes.StartArgs) error { } } + if message := gui.helpers.Update.ExitMessage(); message != "" { + fmt.Println(message) + } + return nil } diff --git a/pkg/gui/information_panel.go b/pkg/gui/information_panel.go index a5977336a..a9b84d35e 100644 --- a/pkg/gui/information_panel.go +++ b/pkg/gui/information_panel.go @@ -9,7 +9,12 @@ func (gui *Gui) informationStr() string { return activeMode.InfoLabel() } - return gui.Config.GetVersion() + version := gui.Config.GetVersion() + if note := gui.helpers.Update.Note(); note != "" { + version = note + " " + version + } + + return version } func (gui *Gui) handleInfoClick() error { diff --git a/pkg/gui/layout.go b/pkg/gui/layout.go index d0af14b5e..2210aa9e1 100644 --- a/pkg/gui/layout.go +++ b/pkg/gui/layout.go @@ -322,7 +322,7 @@ func (gui *Gui) onInitialViewsCreation() error { gui.showRecentRepos = false } - gui.helpers.Update.CheckForUpdateInBackground() + gui.helpers.Update.OnStartup() gui.waitForIntro.Done() diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 5301a3694..bb16ce857 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -439,9 +439,6 @@ type IStateAccessor interface { GetRepoPathStack() *utils.Stack[RepoLocation] GetRepoState() IRepoStateAccessor GetDiffRendererConfigManager() *config.DiffRendererConfigManager - // tells us whether we're currently updating lazygit - GetUpdating() bool - SetUpdating(bool) GetShowExtrasWindow() bool SetShowExtrasWindow(bool) GetRetainOriginalDir() bool diff --git a/pkg/gui/types/version_number.go b/pkg/gui/types/version_number.go index ae51a2722..bff884f53 100644 --- a/pkg/gui/types/version_number.go +++ b/pkg/gui/types/version_number.go @@ -2,6 +2,7 @@ package types import ( "errors" + "fmt" "regexp" "strconv" ) @@ -16,6 +17,12 @@ func (v *VersionNumber) IsOlderThan(otherVersion *VersionNumber) bool { return this < other } +// String formats the version as "v1.2.3", regardless of how it was written when +// it was parsed +func (v *VersionNumber) String() string { + return fmt.Sprintf("v%d.%d.%d", v.Major, v.Minor, v.Patch) +} + func ParseVersionNumber(versionStr string) (*VersionNumber, error) { re := regexp.MustCompile(`^v?(\d+)\.(\d+)(?:\.(\d+))?$`) matches := re.FindStringSubmatch(versionStr) diff --git a/pkg/gui/types/version_number_test.go b/pkg/gui/types/version_number_test.go index 407a01139..e46fb2225 100644 --- a/pkg/gui/types/version_number_test.go +++ b/pkg/gui/types/version_number_test.go @@ -79,3 +79,15 @@ func TestParseVersionNumber(t *testing.T) { }) } } + +func TestVersionNumberString(t *testing.T) { + for _, versionStr := range []string{"1.2.3", "v1.2.3"} { + version, err := ParseVersionNumber(versionStr) + assert.NoError(t, err) + assert.Equal(t, "v1.2.3", version.String()) + } + + version, err := ParseVersionNumber("1.2") + assert.NoError(t, err) + assert.Equal(t, "v1.2.0", version.String()) +} diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 863062d9a..6dda7ea67 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -268,18 +268,36 @@ type TranslationSet struct { UpdatesRejectedAndForcePushDisabled string CheckForUpdate string CheckingForUpdates string + UpdateCheckFailed string + UpdateCheckNotPossibleForDevBuild string + UpdateAlreadyInProgress string + NoUpdateAvailableTitle string + NoUpdateAvailable string UpdateAvailableTitle string - UpdateAvailable string - UpdateInProgressWaitingStatus string - UpdateCompletedTitle string - UpdateCompleted string - FailedToRetrieveLatestVersionErr string - OnLatestVersionErr string - MajorVersionErr string - CouldNotFindBinaryErr string - UpdateFailedErr string - ConfirmQuitDuringUpdateTitle string - ConfirmQuitDuringUpdate string + NewVersionAvailable string + UpdateFolderNotWritable string + UpdateWithPackageManager string + PackageManagersCanBeSlow string + UpdateFromPackageManagerOrRelease string + InstallUpdateNow string + CopyUpdateCommand string + UpdateCommandCopiedToClipboard string + OpenInstallationInstructions string + ReleaseNotes string + InstallingUpdateStatus string + UpdateInstalled string + UpdateInstallFailed string + UpdateAvailableNote string + RestartToUseNewVersion string + RemindMeTomorrow string + SkipThisVersion string + TurnOffUpdateReminders string + ExitMessageNewVersionAvailable string + ExitMessageInstallWithKey string + ExitMessageUpdateCommand string + ExitMessageCheckPackageManager string + ExitMessageInstallationInstructions string + ExitMessageReleaseNotes string IntroPopupMessage string NonReloadableConfigWarningTitle string NonReloadableConfigWarning string @@ -1498,18 +1516,36 @@ func EnglishTranslationSet() *TranslationSet { UpdatesRejectedAndForcePushDisabled: "Updates were rejected and you have disabled force pushing", CheckForUpdate: "Check for update", CheckingForUpdates: "Checking for updates...", - UpdateAvailableTitle: "Update available!", - UpdateAvailable: "Download and install version {{.newVersion}}?", - UpdateInProgressWaitingStatus: "Updating", - UpdateCompletedTitle: "Update completed!", - UpdateCompleted: "Update has been installed successfully. Restart lazygit for it to take effect.", - FailedToRetrieveLatestVersionErr: "Failed to retrieve version information", - OnLatestVersionErr: "You already have the latest version", - MajorVersionErr: "New version ({{.newVersion}}) has non-backwards compatible changes compared to the current version ({{.currentVersion}})", - CouldNotFindBinaryErr: "Could not find any binary at {{.url}}", - UpdateFailedErr: "Update failed: {{.errMessage}}", - ConfirmQuitDuringUpdateTitle: "Currently updating", - ConfirmQuitDuringUpdate: "An update is in progress. Are you sure you want to quit?", + UpdateCheckFailed: "Couldn't check for updates: {{.error}}", + UpdateCheckNotPossibleForDevBuild: "This is a development build ({{.version}}), so lazygit can't check for updates.", + UpdateAlreadyInProgress: "An update is already in progress.", + NoUpdateAvailableTitle: "No update available", + NoUpdateAvailable: "You have the latest version ({{.currentVersion}}).", + UpdateAvailableTitle: "Update available", + NewVersionAvailable: "lazygit {{.newVersion}} is available ({{.releaseNotes}}). You have {{.currentVersion}}.", + UpdateFolderNotWritable: "lazygit can't update itself because you don't have write access to {{.folder}}. If you install lazygit in a folder that you can write to, it will keep itself up to date from then on.", + UpdateWithPackageManager: "You installed lazygit with {{.packageManager}}. To update it, run:\n\n{{.command}}", + PackageManagersCanBeSlow: "Package managers sometimes take a few days to get a new version.", + UpdateFromPackageManagerOrRelease: "If you installed lazygit with a package manager, check whether it has the new version yet. If it doesn't, you can install lazygit from our releases instead, and it will keep itself up to date from then on.", + InstallUpdateNow: "Install now", + CopyUpdateCommand: "Copy command", + UpdateCommandCopiedToClipboard: "Command copied to clipboard", + OpenInstallationInstructions: "Open installation instructions", + ReleaseNotes: "Release notes", + InstallingUpdateStatus: "Installing {{.newVersion}}", + UpdateInstalled: "lazygit {{.newVersion}} is installed. It takes effect the next time you start lazygit.", + UpdateInstallFailed: "Couldn't install lazygit {{.newVersion}}: {{.error}}", + UpdateAvailableNote: "Update available", + RestartToUseNewVersion: "Restart to use {{.newVersion}}", + RemindMeTomorrow: "Remind me tomorrow", + SkipThisVersion: "Skip this version", + TurnOffUpdateReminders: "To turn off these reminders, set update.method to never in your config file.", + ExitMessageNewVersionAvailable: "lazygit {{.newVersion}} is available. You have {{.currentVersion}}.", + ExitMessageInstallWithKey: "To install it, start lazygit and press {{.key}} in the status panel.", + ExitMessageUpdateCommand: "To update, run: {{.command}}", + ExitMessageCheckPackageManager: "Check whether your package manager has it yet, or install lazygit from our releases.", + ExitMessageInstallationInstructions: "Installation instructions: {{.url}}", + ExitMessageReleaseNotes: "Release notes: {{.url}}", IntroPopupMessage: englishIntroPopupMessage, NonReloadableConfigWarningTitle: "Config changed", NonReloadableConfigWarning: englishNonReloadableConfigWarning, diff --git a/pkg/integration/tests/status/check_for_update_in_dev_build.go b/pkg/integration/tests/status/check_for_update_in_dev_build.go new file mode 100644 index 000000000..190aec008 --- /dev/null +++ b/pkg/integration/tests/status/check_for_update_in_dev_build.go @@ -0,0 +1,27 @@ +package status + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var CheckForUpdateInDevBuild = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Checking for an update in a build that has no release version explains why it isn't possible", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) {}, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Status(). + Focus(). + Press(keys.Status.CheckForUpdate) + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content( + Contains("This is a development build ("). + Contains("), so lazygit can't check for updates."), + ). + Confirm() + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index f92b5f5db..3c574abce 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -656,6 +656,7 @@ var tests = []*components.IntegrationTest{ stash.StashStaged, stash.StashStagedPartialFile, stash.StashUnstaged, + status.CheckForUpdateInDevBuild, status.ClickRepoNameToOpenReposMenu, status.ClickToFocus, status.ClickWorkingTreeStateToOpenRebaseOptionsMenu, diff --git a/pkg/updates/build_source.go b/pkg/updates/build_source.go new file mode 100644 index 000000000..168c8ec2c --- /dev/null +++ b/pkg/updates/build_source.go @@ -0,0 +1,15 @@ +package updates + +// The build sources that lazygit knows about. The build source is set with +// `-X main.buildSource=...` when building lazygit. +const ( + // Set by .goreleaser.yml for our release archives + BuildSourceRelease = "binaryRelease" + + // Set by the Homebrew formula (to the name of the tap's owner) + BuildSourceHomebrew = "Homebrew" + + // Set by mergeBuildInfo for builds made with + // `go install github.com/jesseduffield/lazygit@` + BuildSourceGoInstall = "goInstall" +) diff --git a/pkg/updates/install.go b/pkg/updates/install.go new file mode 100644 index 000000000..02ec15fe2 --- /dev/null +++ b/pkg/updates/install.go @@ -0,0 +1,259 @@ +package updates + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/jesseduffield/lazygit/pkg/gui/types" +) + +// Our release archives are about 10 MB. Anything much bigger than that is not +// what we expect. +const maxArchiveSize = 200 * 1024 * 1024 + +// The prefix of the temporary file that we write the new binary to. It is in +// the folder of the executable, so that we can rename it over the executable. +const tempFilePrefix = ".lazygit-update-" + +// The prefix of the name that the old executable gets on Windows, where we +// can't delete it while it is running +const oldFilePrefix = ".lazygit-old-" + +// assetName returns the name of the release archive for the given platform, +// following the name_template in .goreleaser.yml. +func assetName(version *types.VersionNumber, goos string, goarch string) string { + arch := goarch + switch goarch { + case "amd64": + arch = "x86_64" + case "386": + arch = "32-bit" + case "arm": + arch = "armv6" + } + + extension := "tar.gz" + if goos == "windows" { + extension = "zip" + } + + return fmt.Sprintf("lazygit_%d.%d.%d_%s_%s.%s", version.Major, version.Minor, version.Patch, goos, arch, extension) +} + +func assetURL(repoURL string, version *types.VersionNumber, goos string, goarch string) string { + return fmt.Sprintf("%s/releases/download/%s/%s", repoURL, version.String(), assetName(version, goos, goarch)) +} + +func binaryName(goos string) string { + if goos == "windows" { + return "lazygit.exe" + } + return "lazygit" +} + +// checkCanReplaceExecutable returns an error if we can't create files in the +// folder of the executable. In that case we can't install an update. +func checkCanReplaceExecutable(executablePath string) error { + file, err := os.CreateTemp(filepath.Dir(executablePath), tempFilePrefix+"*") + if err != nil { + return err + } + _ = file.Close() + return os.Remove(file.Name()) +} + +// downloadBinary downloads the release archive from url, and returns the +// lazygit binary in it. +func downloadBinary(ctx context.Context, client *http.Client, url string, goos string) ([]byte, error) { + archive, err := download(ctx, client, url) + if err != nil { + return nil, err + } + + return extractBinary(archive, url, binaryName(goos)) +} + +func download(ctx context.Context, client *http.Client, url string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("%s returned %s", url, resp.Status) + } + + content, err := io.ReadAll(io.LimitReader(resp.Body, maxArchiveSize+1)) + if err != nil { + return nil, err + } + if len(content) > maxArchiveSize { + return nil, fmt.Errorf("%s is larger than %d bytes", url, maxArchiveSize) + } + return content, nil +} + +func extractBinary(archive []byte, archiveName string, name string) ([]byte, error) { + var binary []byte + var err error + if strings.HasSuffix(archiveName, ".zip") { + binary, err = extractFromZip(archive, name) + } else { + binary, err = extractFromTarGz(archive, name) + } + if err != nil { + return nil, err + } + if binary == nil { + return nil, fmt.Errorf("%s doesn't contain %s", archiveName, name) + } + return binary, nil +} + +func extractFromTarGz(archive []byte, name string) ([]byte, error) { + gzipReader, err := gzip.NewReader(bytes.NewReader(archive)) + if err != nil { + return nil, err + } + tarReader := tar.NewReader(gzipReader) + for { + header, err := tarReader.Next() + if errors.Is(err, io.EOF) { + return nil, nil + } + if err != nil { + return nil, err + } + if header.Typeflag == tar.TypeReg && path.Base(header.Name) == name { + return io.ReadAll(tarReader) + } + } +} + +func extractFromZip(archive []byte, name string) ([]byte, error) { + zipReader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive))) + if err != nil { + return nil, err + } + for _, file := range zipReader.File { + if !file.FileInfo().IsDir() && path.Base(file.Name) == name { + reader, err := file.Open() + if err != nil { + return nil, err + } + defer reader.Close() + return io.ReadAll(reader) + } + } + return nil, nil +} + +// replaceExecutable writes the new binary to a temporary file next to the +// executable, and renames it over the executable. Renaming makes the change +// atomic, and gives the new binary a new inode. The latter matters on macOS, +// where the system kills a signed binary if it was overwritten in place. +func replaceExecutable(executablePath string, binary []byte, goos string) error { + info, err := os.Stat(executablePath) + if err != nil { + return err + } + + tempPath, err := writeTempFile(filepath.Dir(executablePath), binary, info.Mode().Perm()) + if err != nil { + return err + } + + if goos == "windows" { + err = replaceRunningExecutable(executablePath, tempPath) + } else { + err = os.Rename(tempPath, executablePath) + } + if err != nil { + _ = os.Remove(tempPath) + } + return err +} + +func writeTempFile(dir string, content []byte, mode os.FileMode) (string, error) { + file, err := os.CreateTemp(dir, tempFilePrefix+"*") + if err != nil { + return "", err + } + + _, err = file.Write(content) + if err == nil { + err = file.Sync() + } + if closeErr := file.Close(); err == nil { + err = closeErr + } + if err == nil { + err = os.Chmod(file.Name(), mode) + } + if err != nil { + _ = os.Remove(file.Name()) + return "", err + } + return file.Name(), nil +} + +// Windows doesn't let us replace or delete the executable of a running +// process, but it does let us rename it. So we move it out of the way first. +// We can't delete it until lazygit exits; cleanUpAfterUpdate does this the +// next time lazygit runs. +func replaceRunningExecutable(executablePath string, newPath string) error { + oldPath := filepath.Join(filepath.Dir(executablePath), fmt.Sprintf("%s%d", oldFilePrefix, time.Now().UnixNano())) + if err := os.Rename(executablePath, oldPath); err != nil { + return err + } + if err := os.Rename(newPath, executablePath); err != nil { + _ = os.Rename(oldPath, executablePath) + return err + } + + _ = os.Remove(oldPath) + return nil +} + +// cleanUpAfterUpdate removes files that an earlier update left behind: old +// executables that we couldn't delete while they were running (on Windows), +// and temporary files of updates that didn't finish, e.g. because lazygit was +// killed. We leave recent temporary files alone, because another lazygit might +// be in the middle of an update. +func cleanUpAfterUpdate(executablePath string) { + dir := filepath.Dir(executablePath) + entries, err := os.ReadDir(dir) + if err != nil { + return + } + + for _, entry := range entries { + path := filepath.Join(dir, entry.Name()) + switch { + case strings.HasPrefix(entry.Name(), oldFilePrefix): + _ = os.Remove(path) + case strings.HasPrefix(entry.Name(), tempFilePrefix): + if info, err := entry.Info(); err == nil && time.Since(info.ModTime()) > time.Hour { + _ = os.Remove(path) + } + } + } +} diff --git a/pkg/updates/install_test.go b/pkg/updates/install_test.go new file mode 100644 index 000000000..960020c07 --- /dev/null +++ b/pkg/updates/install_test.go @@ -0,0 +1,212 @@ +package updates + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/stretchr/testify/assert" +) + +func TestAssetName(t *testing.T) { + // The assets of the v0.66.2 release + expectedNames := []string{ + "lazygit_0.66.2_darwin_arm64.tar.gz", + "lazygit_0.66.2_darwin_x86_64.tar.gz", + "lazygit_0.66.2_freebsd_32-bit.tar.gz", + "lazygit_0.66.2_freebsd_arm64.tar.gz", + "lazygit_0.66.2_freebsd_armv6.tar.gz", + "lazygit_0.66.2_freebsd_x86_64.tar.gz", + "lazygit_0.66.2_linux_32-bit.tar.gz", + "lazygit_0.66.2_linux_arm64.tar.gz", + "lazygit_0.66.2_linux_armv6.tar.gz", + "lazygit_0.66.2_linux_x86_64.tar.gz", + "lazygit_0.66.2_windows_32-bit.zip", + "lazygit_0.66.2_windows_arm64.zip", + "lazygit_0.66.2_windows_x86_64.zip", + } + + version := &types.VersionNumber{Major: 0, Minor: 66, Patch: 2} + names := []string{} + for _, goos := range []string{"darwin", "freebsd", "linux", "windows"} { + for _, goarch := range []string{"arm64", "amd64", "386", "arm"} { + // goreleaser doesn't build these + if (goos == "darwin" && (goarch == "386" || goarch == "arm")) || (goos == "windows" && goarch == "arm") { + continue + } + names = append(names, assetName(version, goos, goarch)) + } + } + + assert.ElementsMatch(t, expectedNames, names) +} + +func TestAssetURL(t *testing.T) { + version := &types.VersionNumber{Major: 0, Minor: 67, Patch: 0} + assert.Equal(t, + "https://github.com/jesseduffield/lazygit/releases/download/v0.67.0/lazygit_0.67.0_linux_x86_64.tar.gz", + assetURL("https://github.com/jesseduffield/lazygit", version, "linux", "amd64")) +} + +func TestExtractBinary(t *testing.T) { + files := map[string]string{ + "LICENSE": "license", + "README.md": "readme", + "lazygit": "unix binary", + "lazygit.exe": "windows binary", + } + + binary, err := extractBinary(makeTarGz(t, files), "lazygit_0.67.0_linux_x86_64.tar.gz", "lazygit") + assert.NoError(t, err) + assert.Equal(t, "unix binary", string(binary)) + + binary, err = extractBinary(makeZip(t, files), "lazygit_0.67.0_windows_x86_64.zip", "lazygit.exe") + assert.NoError(t, err) + assert.Equal(t, "windows binary", string(binary)) + + _, err = extractBinary(makeTarGz(t, map[string]string{"LICENSE": "license"}), "archive.tar.gz", "lazygit") + assert.EqualError(t, err, "archive.tar.gz doesn't contain lazygit") + + _, err = extractBinary([]byte("not an archive"), "archive.tar.gz", "lazygit") + assert.Error(t, err) +} + +func TestReplaceExecutable(t *testing.T) { + for _, goos := range []string{"linux", "windows"} { + t.Run(goos, func(t *testing.T) { + dir := t.TempDir() + executablePath := filepath.Join(dir, "lazygit") + assert.NoError(t, os.WriteFile(executablePath, []byte("old"), 0o755)) + + assert.NoError(t, replaceExecutable(executablePath, []byte("new"), goos)) + + assertFileContent(t, executablePath, "new") + if runtime.GOOS != "windows" { + info, err := os.Stat(executablePath) + assert.NoError(t, err) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm()) + } + assertDirContains(t, dir, "lazygit") + }) + } +} + +func TestCheckCanReplaceExecutable(t *testing.T) { + dir := t.TempDir() + executablePath := filepath.Join(dir, "lazygit") + assert.NoError(t, os.WriteFile(executablePath, []byte("old"), 0o755)) + + assert.NoError(t, checkCanReplaceExecutable(executablePath)) + assertDirContains(t, dir, "lazygit") + + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + // Windows ignores the permissions of folders, and root can write + // anywhere + return + } + + assert.NoError(t, os.Chmod(dir, 0o555)) + defer func() { _ = os.Chmod(dir, 0o755) }() + + assert.ErrorIs(t, checkCanReplaceExecutable(executablePath), os.ErrPermission) + assert.ErrorIs(t, replaceExecutable(executablePath, []byte("new"), runtime.GOOS), os.ErrPermission) + assertFileContent(t, executablePath, "old") +} + +func TestCleanUpAfterUpdate(t *testing.T) { + dir := t.TempDir() + executablePath := filepath.Join(dir, "lazygit") + for _, name := range []string{"lazygit", "lazygit.old", ".lazygit-old-123", ".lazygit-update-old", ".lazygit-update-new"} { + assert.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(name), 0o755)) + } + twoHoursAgo := time.Now().Add(-2 * time.Hour) + assert.NoError(t, os.Chtimes(filepath.Join(dir, ".lazygit-update-old"), twoHoursAgo, twoHoursAgo)) + + cleanUpAfterUpdate(executablePath) + + assertDirContains(t, dir, ".lazygit-update-new", "lazygit", "lazygit.old") +} + +func TestDownloadBinary(t *testing.T) { + archive := makeTarGz(t, map[string]string{"LICENSE": "license", "lazygit": "new"}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/releases/download/v0.67.0/lazygit_0.67.0_linux_x86_64.tar.gz" { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write(archive) + })) + defer server.Close() + + version := &types.VersionNumber{Major: 0, Minor: 67, Patch: 0} + url := assetURL(server.URL, version, "linux", "amd64") + binary, err := downloadBinary(context.Background(), server.Client(), url, "linux") + assert.NoError(t, err) + assert.Equal(t, "new", string(binary)) + + url = assetURL(server.URL, version, "linux", "arm64") + _, err = downloadBinary(context.Background(), server.Client(), url, "linux") + assert.ErrorContains(t, err, "lazygit_0.67.0_linux_arm64.tar.gz returned 404 Not Found") +} + +func makeTarGz(t *testing.T, files map[string]string) []byte { + t.Helper() + + var buffer bytes.Buffer + gzipWriter := gzip.NewWriter(&buffer) + tarWriter := tar.NewWriter(gzipWriter) + for name, content := range files { + header := &tar.Header{Name: name, Mode: 0o755, Size: int64(len(content)), Typeflag: tar.TypeReg} + assert.NoError(t, tarWriter.WriteHeader(header)) + _, err := tarWriter.Write([]byte(content)) + assert.NoError(t, err) + } + assert.NoError(t, tarWriter.Close()) + assert.NoError(t, gzipWriter.Close()) + return buffer.Bytes() +} + +func makeZip(t *testing.T, files map[string]string) []byte { + t.Helper() + + var buffer bytes.Buffer + zipWriter := zip.NewWriter(&buffer) + for name, content := range files { + writer, err := zipWriter.Create(name) + assert.NoError(t, err) + _, err = writer.Write([]byte(content)) + assert.NoError(t, err) + } + assert.NoError(t, zipWriter.Close()) + return buffer.Bytes() +} + +func assertFileContent(t *testing.T, path string, expected string) { + t.Helper() + + content, err := os.ReadFile(path) + assert.NoError(t, err) + assert.Equal(t, expected, string(content)) +} + +func assertDirContains(t *testing.T, dir string, expected ...string) { + t.Helper() + + entries, err := os.ReadDir(dir) + assert.NoError(t, err) + names := make([]string, 0, len(entries)) + for _, entry := range entries { + names = append(names, entry.Name()) + } + assert.ElementsMatch(t, expected, names) +} diff --git a/pkg/updates/installation.go b/pkg/updates/installation.go new file mode 100644 index 000000000..18425cbad --- /dev/null +++ b/pkg/updates/installation.go @@ -0,0 +1,126 @@ +package updates + +import ( + "strings" + + "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/samber/lo" +) + +// InstallKind says how lazygit was installed. This decides what we can offer +// the user when there's an update. +type InstallKind int + +const ( + // A build without a release version, e.g. one built from a git checkout. We + // don't check for updates for these. + InstallKindDevBuild InstallKind = iota + // Installed from one of our release archives. We can update it in place. + InstallKindRelease + InstallKindHomebrew + InstallKindGoInstall + InstallKindScoop + InstallKindWinget + InstallKindChocolatey + // Anything else with a release version, e.g. a package of a Linux + // distribution. We can only tell the user that there's an update. + InstallKindOther +) + +type Installation struct { + Kind InstallKind + // The path of the lazygit executable, with symlinks resolved + ExecutablePath string +} + +// Folders of package managers that install our release archives unchanged. +// The build source of these is BuildSourceRelease, but we must not update them +// in place, or the package manager would report the wrong version. +var packageManagerFolders = []string{ + "/mise/installs/", + "/.asdf/installs/", + "/aquaproj-aqua/", + "/nix/store/", + "/snap/", +} + +func DetectInstallation(buildSource string, version string, executablePath string) Installation { + kind := detectInstallKind(buildSource, version, executablePath) + return Installation{Kind: kind, ExecutablePath: executablePath} +} + +func detectInstallKind(buildSource string, version string, executablePath string) InstallKind { + if _, err := types.ParseVersionNumber(version); err != nil { + return InstallKindDevBuild + } + + // Normalize the path so that we can match Windows paths on any platform, + // and regardless of how they are capitalized. + path := strings.ToLower(strings.ReplaceAll(executablePath, `\`, "/")) + + switch { + case strings.EqualFold(buildSource, BuildSourceHomebrew) || strings.Contains(path, "/cellar/lazygit/"): + return InstallKindHomebrew + case buildSource == BuildSourceGoInstall: + return InstallKindGoInstall + case strings.Contains(path, "/scoop/apps/lazygit/"): + return InstallKindScoop + case strings.Contains(path, "/microsoft/winget/packages/jesseduffield.lazygit"): + return InstallKindWinget + case strings.Contains(path, "/chocolatey/lib/lazygit/"): + return InstallKindChocolatey + case buildSource == BuildSourceRelease && !isInPackageManagerFolder(path): + return InstallKindRelease + default: + return InstallKindOther + } +} + +func isInPackageManagerFolder(path string) bool { + // On Linux, /usr/bin belongs to the distribution's package manager + if strings.HasPrefix(path, "/usr/bin/") { + return true + } + + return lo.SomeBy(packageManagerFolders, func(folder string) bool { + return strings.Contains(path, folder) + }) +} + +// PackageManagerName returns the name of the package manager that lazygit was +// installed with, or "" if we don't know it. +func (self Installation) PackageManagerName() string { + switch self.Kind { + case InstallKindHomebrew: + return "Homebrew" + case InstallKindGoInstall: + return "go install" + case InstallKindScoop: + return "Scoop" + case InstallKindWinget: + return "winget" + case InstallKindChocolatey: + return "Chocolatey" + default: + return "" + } +} + +// UpdateCommand returns the command that updates lazygit with the package +// manager that it was installed with, or "" if we don't know it. +func (self Installation) UpdateCommand() string { + switch self.Kind { + case InstallKindHomebrew: + return "brew upgrade lazygit" + case InstallKindGoInstall: + return "go install github.com/jesseduffield/lazygit@latest" + case InstallKindScoop: + return "scoop update lazygit" + case InstallKindWinget: + return "winget upgrade JesseDuffield.lazygit" + case InstallKindChocolatey: + return "choco upgrade lazygit" + default: + return "" + } +} diff --git a/pkg/updates/installation_test.go b/pkg/updates/installation_test.go new file mode 100644 index 000000000..0a636b5fc --- /dev/null +++ b/pkg/updates/installation_test.go @@ -0,0 +1,159 @@ +package updates + +import ( + "os" + "regexp" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDetectInstallKind(t *testing.T) { + scenarios := []struct { + name string + buildSource string + version string + executablePath string + expected InstallKind + }{ + { + name: "built from a git checkout", + buildSource: "unknown", + version: "0123abcd", + executablePath: "/home/user/go/bin/lazygit", + expected: InstallKindDevBuild, + }, + { + name: "built from a git checkout based on a release", + buildSource: "unknown", + version: "v0.66.2+0123abcd-dirty", + executablePath: "/home/user/go/bin/lazygit", + expected: InstallKindDevBuild, + }, + { + name: "built without version", + buildSource: "unknown", + version: "unversioned", + executablePath: "/home/user/lazygit/lazygit", + expected: InstallKindDevBuild, + }, + { + name: "dev build with release build source", + buildSource: "binaryRelease", + version: "0.66.2-next", + executablePath: "/home/user/.local/bin/lazygit", + expected: InstallKindDevBuild, + }, + { + name: "release archive", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: "/home/user/.local/bin/lazygit", + expected: InstallKindRelease, + }, + { + name: "release archive on Windows", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: `C:\Users\user\AppData\Local\Programs\lazygit\lazygit.exe`, + expected: InstallKindRelease, + }, + { + name: "release archive in /usr/local/bin", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: "/usr/local/bin/lazygit", + expected: InstallKindRelease, + }, + { + name: "release archive in /usr/bin", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: "/usr/bin/lazygit", + expected: InstallKindOther, + }, + { + name: "release archive installed by mise", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: "/home/user/.local/share/mise/installs/lazygit/0.66.2/lazygit", + expected: InstallKindOther, + }, + { + name: "Homebrew", + buildSource: "Homebrew", + version: "0.66.2", + executablePath: "/opt/homebrew/Cellar/lazygit/0.66.2/bin/lazygit", + expected: InstallKindHomebrew, + }, + { + name: "Homebrew on Linux", + buildSource: "Homebrew", + version: "0.66.2", + executablePath: "/home/linuxbrew/.linuxbrew/Cellar/lazygit/0.66.2/bin/lazygit", + expected: InstallKindHomebrew, + }, + { + name: "Homebrew formula with a different build source", + buildSource: "someone", + version: "0.66.2", + executablePath: "/usr/local/Cellar/lazygit/0.66.2/bin/lazygit", + expected: InstallKindHomebrew, + }, + { + name: "go install", + buildSource: "goInstall", + version: "0.66.2", + executablePath: "/home/user/go/bin/lazygit", + expected: InstallKindGoInstall, + }, + { + name: "Scoop", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: `C:\Users\user\scoop\apps\lazygit\0.66.2\lazygit.exe`, + expected: InstallKindScoop, + }, + { + name: "winget", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: `C:\Users\user\AppData\Local\Microsoft\WinGet\Packages\JesseDuffield.lazygit_Microsoft.Winget.Source_8wekyb3d8bbwe\lazygit.exe`, + expected: InstallKindWinget, + }, + { + name: "Chocolatey", + buildSource: "binaryRelease", + version: "0.66.2", + executablePath: `C:\ProgramData\chocolatey\lib\lazygit\tools\lazygit.exe`, + expected: InstallKindChocolatey, + }, + { + name: "distribution package", + buildSource: "unknown", + version: "0.66.2", + executablePath: "/usr/bin/lazygit", + expected: InstallKindOther, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + installation := DetectInstallation(s.buildSource, s.version, s.executablePath) + assert.Equal(t, s.expected, installation.Kind) + assert.Equal(t, s.executablePath, installation.ExecutablePath) + }) + } +} + +func TestReleaseBuildSourceMatchesGoreleaserConfig(t *testing.T) { + content, err := os.ReadFile("../../.goreleaser.yml") + if !assert.NoError(t, err) { + return + } + + matches := regexp.MustCompile(`-X main\.buildSource=(\S+)`).FindAllStringSubmatch(string(content), -1) + if assert.Len(t, matches, 1) { + assert.Equal(t, BuildSourceRelease, matches[0][1]) + } +} diff --git a/pkg/updates/latest_version.go b/pkg/updates/latest_version.go new file mode 100644 index 000000000..0e88bd16f --- /dev/null +++ b/pkg/updates/latest_version.go @@ -0,0 +1,44 @@ +package updates + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/jesseduffield/lazygit/pkg/gui/types" +) + +// fetchLatestVersion asks GitHub for the version of the latest lazygit release. +// We use the release page instead of GitHub's REST API, because the API limits +// the number of unauthenticated requests per IP address. +func fetchLatestVersion(ctx context.Context, client *http.Client, repoURL string) (*types.VersionNumber, error) { + var data struct { + TagName string `json:"tag_name"` + } + if err := fetchJSON(ctx, client, repoURL+"/releases/latest", &data); err != nil { + return nil, err + } + + return types.ParseVersionNumber(data.TagName) +} + +func fetchJSON(ctx context.Context, client *http.Client, url string, data any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("%s returned %s", url, resp.Status) + } + + return json.NewDecoder(resp.Body).Decode(data) +} diff --git a/pkg/updates/latest_version_test.go b/pkg/updates/latest_version_test.go new file mode 100644 index 000000000..1546f6e96 --- /dev/null +++ b/pkg/updates/latest_version_test.go @@ -0,0 +1,66 @@ +package updates + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/stretchr/testify/assert" +) + +func TestFetchLatestVersion(t *testing.T) { + scenarios := []struct { + name string + status int + body string + expectedVersion *types.VersionNumber + expectedError string + }{ + { + name: "release", + status: http.StatusOK, + body: `{"id":1,"tag_name":"v0.67.0","update_url":"/jesseduffield/lazygit/releases/tag/v0.67.0"}`, + expectedVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, + { + name: "not found", + status: http.StatusNotFound, + body: `{"error":"Not Found"}`, + expectedError: "/releases/latest returned 404 Not Found", + }, + { + name: "unexpected tag", + status: http.StatusOK, + body: `{"tag_name":"nightly"}`, + expectedError: "unexpected version format: nightly", + }, + { + name: "invalid json", + status: http.StatusOK, + body: ``, + expectedError: "invalid character '<' looking for beginning of value", + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/releases/latest", r.URL.Path) + assert.Equal(t, "application/json", r.Header.Get("Accept")) + w.WriteHeader(s.status) + _, _ = w.Write([]byte(s.body)) + })) + defer server.Close() + + version, err := fetchLatestVersion(context.Background(), server.Client(), server.URL) + if s.expectedError != "" { + assert.ErrorContains(t, err, s.expectedError) + } else { + assert.NoError(t, err) + assert.Equal(t, s.expectedVersion, version) + } + }) + } +} diff --git a/pkg/updates/updates.go b/pkg/updates/updates.go index d563a456c..67a54c30d 100644 --- a/pkg/updates/updates.go +++ b/pkg/updates/updates.go @@ -1,334 +1,405 @@ package updates import ( - "encoding/json" - "fmt" - "io" + "context" + "errors" "net/http" "os" "path/filepath" "runtime" - "strings" + "sync" + "sync/atomic" "time" - "github.com/go-errors/errors" - - "github.com/kardianos/osext" - - "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/constants" - "github.com/jesseduffield/lazygit/pkg/utils" + "github.com/jesseduffield/lazygit/pkg/gui/types" ) -// Updater checks for updates and does updates +const ( + checkTimeout = 30 * time.Second + installTimeout = 10 * time.Minute + + // How long we wait before showing the update menu again after the user + // responded to it + reminderInterval = 24 * time.Hour + // How long an update must have been available before we show the update + // menu at startup, if the user hasn't responded to it otherwise + startupReminderDelay = 7 * 24 * time.Hour + // How long after lazygit started we use ReminderMenuAtStartup + startupPeriod = time.Minute +) + +// The ways in which lazygit reminds the user of an available update +type Reminder int + +const ( + // Show the update menu after the user hasn't used lazygit for a while + ReminderMenuWhenIdle Reminder = iota + // Show the update menu at startup. We only do this if the user hasn't + // responded to the menu for a long time, e.g. because they never leave + // lazygit idle. + ReminderMenuAtStartup + // Print a message to the terminal after lazygit exits + ReminderExitMessage +) + +// The part of config.AppConfigurer that the updater needs +type appStateStore interface { + ReadAppState() (*config.AppState, error) + UpdateAppState(update func(state *config.AppState)) error +} + +// Updater checks for new lazygit releases, and installs them if lazygit was +// installed from one of our release archives. type Updater struct { *common.Common - Config config.AppConfigurer - OSCommand *oscommands.OSCommand + appState appStateStore + installation Installation + currentVersion *types.VersionNumber + + httpClient *http.Client + repoURL string + goos string + goarch string + + installing atomic.Bool + + statusMutex sync.Mutex + status Status + + startTime time.Time + + // Replaced in tests + now func() time.Time + + // Held while we replace the executable, so that lazygit doesn't exit in + // the middle of it + replaceMutex sync.Mutex } -// Updaterer implements the check and update methods -type Updaterer interface { - CheckForNewUpdate() - Update() -} +func NewUpdater(cmn *common.Common, config config.AppConfigurer) *Updater { + currentVersion, _ := types.ParseVersionNumber(config.GetVersion()) -// NewUpdater creates a new updater -func NewUpdater(cmn *common.Common, config config.AppConfigurer, osCommand *oscommands.OSCommand) (*Updater, error) { return &Updater{ - Common: cmn, - Config: config, - OSCommand: osCommand, - }, nil + Common: cmn, + appState: config, + installation: DetectInstallation(config.GetBuildSource(), config.GetVersion(), executablePath()), + currentVersion: currentVersion, + httpClient: &http.Client{}, + repoURL: constants.Links.RepoUrl, + goos: runtime.GOOS, + goarch: runtime.GOARCH, + startTime: time.Now(), + now: time.Now, + } } -func (u *Updater) getLatestVersionNumber() (string, error) { - req, err := http.NewRequest("GET", constants.Links.RepoUrl+"/releases/latest", nil) +func executablePath() string { + path, err := os.Executable() if err != nil { - return "", err + return "" } - req.Header.Set("Accept", "application/json") - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return "", err + if resolvedPath, err := filepath.EvalSymlinks(path); err == nil { + return resolvedPath } - defer resp.Body.Close() - - dec := json.NewDecoder(resp.Body) - data := struct { - TagName string `json:"tag_name"` - }{} - if err := dec.Decode(&data); err != nil { - return "", err - } - - return data.TagName, nil + return path } -// RecordLastUpdateCheck records last time an update check was performed -func (u *Updater) RecordLastUpdateCheck() error { - return u.Config.UpdateAppState(func(state *config.AppState) { - state.LastUpdateCheck = time.Now().Unix() +func (u *Updater) Installation() Installation { + return u.installation +} + +// CurrentVersion returns nil for dev builds +func (u *Updater) CurrentVersion() *types.VersionNumber { + return u.currentVersion +} + +// Status is what lazygit knows about updates +type Status struct { + // The latest release that a check found, if it is newer than the running + // lazygit + AvailableVersion *types.VersionNumber + // The version that an update installed in place of the running lazygit. + // This lazygit, or another one running from the same executable, can have + // installed it. The new version takes effect when lazygit is restarted. + InstalledVersion *types.VersionNumber +} + +// ChecksEnabled returns whether lazygit checks for updates regularly. It +// doesn't for dev builds. +func (u *Updater) ChecksEnabled() bool { + return u.installation.Kind != InstallKindDevBuild +} + +// CheckForUpdateIfDue checks for an update if lazygit checks regularly, and +// the last successful check is long enough ago. +func (u *Updater) CheckForUpdateIfDue() error { + if !u.ChecksEnabled() { + return nil + } + + state := u.readAppState() + interval := time.Duration(u.UserConfig().Update.Days) * 24 * time.Hour + if u.now().Sub(time.Unix(state.Updates.LastCheck, 0)) < interval { + u.RefreshStatus() + return nil + } + + _, err := u.CheckForUpdate() + return err +} + +// CheckForUpdate returns the latest version if it is newer than the current +// one, or nil if it isn't. Don't call it for dev builds. +func (u *Updater) CheckForUpdate() (*types.VersionNumber, error) { + ctx, cancel := context.WithTimeout(context.Background(), checkTimeout) + defer cancel() + + latestVersion, err := fetchLatestVersion(ctx, u.httpClient, u.repoURL) + if err != nil { + return nil, err + } + + u.Log.Infof("Current version is %s, latest version is %s", u.currentVersion, latestVersion) + u.updateAppState(func(state *config.AppState) { + state.Updates.LastCheck = u.now().Unix() + if state.Updates.LatestVersion != latestVersion.String() { + state.Updates.LatestVersion = latestVersion.String() + state.Updates.LatestVersionFoundAt = u.now().Unix() + } }) + u.RefreshStatus() + + if !u.currentVersion.IsOlderThan(latestVersion) { + return nil, nil + } + return latestVersion, nil } -// expecting version to be of the form `v12.34.56` -func (u *Updater) majorVersionDiffers(oldVersion, newVersion string) bool { - if oldVersion == "unversioned" { - return false - } - oldVersion = strings.TrimPrefix(oldVersion, "v") - newVersion = strings.TrimPrefix(newVersion, "v") - return strings.Split(oldVersion, ".")[0] != strings.Split(newVersion, ".")[0] +// CheckCanInstall returns an error if we can't install an update in place +// because we don't have write access to the folder of the executable. Only call +// it for InstallKindRelease. +func (u *Updater) CheckCanInstall() error { + return checkCanReplaceExecutable(u.installation.ExecutablePath) } -func (u *Updater) currentVersion() string { - versionNumber := u.Config.GetVersion() - if versionNumber == "unversioned" { - return versionNumber +// Install downloads the given release and installs it in place of the running +// lazygit. Only call it for InstallKindRelease. +func (u *Updater) Install(version *types.VersionNumber) error { + if !u.installing.CompareAndSwap(false, true) { + return errors.New("an update is already in progress") } + defer u.installing.Store(false) - return fmt.Sprintf("v%s", u.Config.GetVersion()) -} + ctx, cancel := context.WithTimeout(context.Background(), installTimeout) + defer cancel() -func (u *Updater) checkForNewUpdate() (string, error) { - u.Log.Info("Checking for an updated version") - currentVersion := u.currentVersion() - if err := u.RecordLastUpdateCheck(); err != nil { - return "", err - } + url := assetURL(u.repoURL, version, u.goos, u.goarch) + u.Log.Infof("Installing %s", url) - newVersion, err := u.getLatestVersionNumber() - if err != nil { - return "", err - } - u.Log.Info("Current version is " + currentVersion) - u.Log.Info("New version is " + newVersion) - - if newVersion == currentVersion { - return "", errors.New(u.Tr.OnLatestVersionErr) - } - - if u.majorVersionDiffers(currentVersion, newVersion) { - errMessage := utils.ResolvePlaceholderString( - u.Tr.MajorVersionErr, map[string]string{ - "newVersion": newVersion, - "currentVersion": currentVersion, - }, - ) - return "", errors.New(errMessage) - } - - rawUrl := u.getBinaryUrl(newVersion) - - u.Log.Info("Checking for resource at url " + rawUrl) - if !u.verifyResourceFound(rawUrl) { - errMessage := utils.ResolvePlaceholderString( - u.Tr.CouldNotFindBinaryErr, map[string]string{ - "url": rawUrl, - }, - ) - - return "", errors.New(errMessage) - } - u.Log.Info("Verified resource is available, ready to update") - - return newVersion, nil -} - -// CheckForNewUpdate checks if there is an available update -func (u *Updater) CheckForNewUpdate(onFinish func(string, error) error, userRequested bool) { - if !userRequested && u.skipUpdateCheck() { - return - } - - newVersion, err := u.checkForNewUpdate() - if err = onFinish(newVersion, err); err != nil { - u.Log.Error(err) - } -} - -func (u *Updater) skipUpdateCheck() bool { - // will remove the check for windows after adding a manifest file asking for - // the required permissions - if runtime.GOOS == "windows" { - u.Log.Info("Updating is currently not supported for windows until we can fix permission issues") - return true - } - - if u.Config.GetVersion() == "unversioned" { - u.Log.Info("Current version is not built from an official release so we won't check for an update") - return true - } - - if u.Config.GetBuildSource() != "buildBinary" { - u.Log.Info("Binary is not built with the buildBinary flag so we won't check for an update") - return true - } - - userConfig := u.UserConfig() - if userConfig.Update.Method == "never" { - u.Log.Info("Update method is set to never so we won't check for an update") - return true - } - - currentTimestamp := time.Now().Unix() - appState, err := u.Config.ReadAppState() - if err != nil { - u.Log.Errorf("error when reading app state: %v", err) - } - lastUpdateCheck := appState.LastUpdateCheck - days := userConfig.Update.Days - - if (currentTimestamp-lastUpdateCheck)/(60*60*24) < days { - u.Log.Info("Last update was too recent so we won't check for an update") - return true - } - - return false -} - -func (u *Updater) mappedOs(os string) string { - osMap := map[string]string{ - "darwin": "Darwin", - "linux": "Linux", - "windows": "Windows", - } - result, found := osMap[os] - if found { - return result - } - return os -} - -func (u *Updater) mappedArch(arch string) string { - archMap := map[string]string{ - "386": "32-bit", - "amd64": "x86_64", - } - result, found := archMap[arch] - if found { - return result - } - return arch -} - -func (u *Updater) zipExtension() string { - if runtime.GOOS == "windows" { - return "zip" - } - - return "tar.gz" -} - -// example: https://github.com/jesseduffield/lazygit/releases/download/v0.1.73/lazygit_0.1.73_Darwin_x86_64.tar.gz -func (u *Updater) getBinaryUrl(newVersion string) string { - url := fmt.Sprintf( - "%s/releases/download/%s/lazygit_%s_%s_%s.%s", - constants.Links.RepoUrl, - newVersion, - newVersion[1:], - u.mappedOs(runtime.GOOS), - u.mappedArch(runtime.GOARCH), - u.zipExtension(), - ) - u.Log.Info("Url for latest release is " + url) - return url -} - -// Update downloads the latest binary and replaces the current binary with it -func (u *Updater) Update(newVersion string) error { - return u.update(newVersion) -} - -func (u *Updater) update(newVersion string) error { - rawUrl := u.getBinaryUrl(newVersion) - u.Log.Info("Updating with url " + rawUrl) - return u.downloadAndInstall(rawUrl) -} - -func (u *Updater) downloadAndInstall(rawUrl string) error { - configDir := u.Config.GetUserConfigDir() - u.Log.Info("Download directory is " + configDir) - - zipPath := filepath.Join(configDir, "temp_lazygit."+u.zipExtension()) - u.Log.Info("Temp path to tarball/zip file is " + zipPath) - - // remove existing zip file - if err := os.RemoveAll(zipPath); err != nil && !os.IsNotExist(err) { - return err - } - - // Create the zip file - out, err := os.Create(zipPath) - if err != nil { - return err - } - defer out.Close() - - // Get the data - resp, err := http.Get(rawUrl) - if err != nil { - return err - } - defer resp.Body.Close() - - // Check server response - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("error while trying to download latest lazygit: %s", resp.Status) - } - - // Write the body to file - _, err = io.Copy(out, resp.Body) + binary, err := downloadBinary(ctx, u.httpClient, url, u.goos) if err != nil { return err } - u.Log.Info("untarring tarball/unzipping zip file") - err = u.OSCommand.Cmd.New([]string{"tar", "-zxf", zipPath, "lazygit"}).Run() - if err != nil { + if err := u.replaceExecutable(binary); err != nil { return err } - // the `tar` terminal cannot store things in a new location without permission - // so it creates it in the current directory. As such our path is fairly simple. - // You won't see it because it's gitignored. - tempLazygitFilePath := "lazygit" - - u.Log.Infof("Path to temp binary is %s", tempLazygitFilePath) - - // get the path of the current binary - binaryPath, err := osext.Executable() - if err != nil { - return err - } - u.Log.Info("Binary path is " + binaryPath) - - // Verify the main file exists - if _, err := os.Stat(zipPath); err != nil { - return err - } - - // swap out the old binary for the new one - err = os.Rename(tempLazygitFilePath, binaryPath) - if err != nil { - return err - } - u.Log.Info("Update complete!") - + u.updateAppState(func(state *config.AppState) { + state.Updates.InstalledVersion = version.String() + state.Updates.InstalledPath = u.installation.ExecutablePath + }) + u.RefreshStatus() return nil } -func (u *Updater) verifyResourceFound(rawUrl string) bool { - resp, err := http.Head(rawUrl) +func (u *Updater) replaceExecutable(binary []byte) error { + u.replaceMutex.Lock() + defer u.replaceMutex.Unlock() + return replaceExecutable(u.installation.ExecutablePath, binary, u.goos) +} + +// RefreshStatus reads the status from the app state, where other lazygit +// instances can have changed it, and returns it. Don't call it on the UI +// thread, because it accesses the file system. +func (u *Updater) RefreshStatus() Status { + state := u.readAppState() + + status := u.statusFromAppState(state) + + u.statusMutex.Lock() + defer u.statusMutex.Unlock() + u.status = status + return status +} + +func (u *Updater) statusFromAppState(state *config.AppState) Status { + status := Status{ + AvailableVersion: u.newerVersion(state.Updates.LatestVersion), + } + if state.Updates.InstalledPath == u.installation.ExecutablePath { + status.InstalledVersion = u.newerVersion(state.Updates.InstalledVersion) + } + return status +} + +// Status returns the status as of the last refresh +func (u *Updater) Status() Status { + u.statusMutex.Lock() + defer u.statusMutex.Unlock() + return u.status +} + +// IsStartingUp returns whether lazygit started less than a minute ago +func (u *Updater) IsStartingUp() bool { + return u.now().Sub(u.startTime) < startupPeriod +} + +// RemindersEnabled returns whether lazygit reminds the user of available +// updates. With update.method set to never, it only shows the note in the +// bottom-right corner. +func (u *Updater) RemindersEnabled() bool { + return u.ChecksEnabled() && u.UserConfig().Update.Method != "never" +} + +// DueReminder returns the version to remind the user of, or nil if no reminder +// is due +func (u *Updater) DueReminder(reminder Reminder) *types.VersionNumber { + return u.dueReminder(u.readAppState(), reminder) +} + +// ClaimExitMessage returns the version to remind the user of in a message +// after lazygit exits, or nil if no reminder is due, and records that we print +// the message. We print it at most once a day. +func (u *Updater) ClaimExitMessage() *types.VersionNumber { + var version *types.VersionNumber + u.updateAppState(func(state *config.AppState) { + version = u.dueReminder(state, ReminderExitMessage) + if version != nil { + state.Updates.LastExitMessage = u.now().Unix() + } + }) + return version +} + +func (u *Updater) dueReminder(state *config.AppState, reminder Reminder) *types.VersionNumber { + if !u.RemindersEnabled() || u.IsInstalling() { + return nil + } + + status := u.statusFromAppState(state) + if status.AvailableVersion == nil || status.InstalledVersion != nil { + return nil + } + if state.Updates.SkippedVersion == state.Updates.LatestVersion { + return nil + } + if u.now().Sub(time.Unix(state.Updates.LastResponse, 0)) < reminderInterval { + return nil + } + if reminder == ReminderMenuAtStartup { + if state.Updates.RespondedVersion == state.Updates.LatestVersion || + u.now().Sub(time.Unix(state.Updates.LatestVersionFoundAt, 0)) < startupReminderDelay { + return nil + } + } + if reminder == ReminderExitMessage && + u.now().Sub(time.Unix(state.Updates.LastExitMessage, 0)) < reminderInterval { + return nil + } + return status.AvailableVersion +} + +// VersionToInstallInBackground returns the version that lazygit should install +// without asking the user, or nil if there's none. This is the case if the user +// config asks for it, and lazygit can update itself. +func (u *Updater) VersionToInstallInBackground() *types.VersionNumber { + if u.installation.Kind != InstallKindRelease || u.UserConfig().Update.Method != "background" { + return nil + } + + state := u.readAppState() + status := u.statusFromAppState(state) + if status.AvailableVersion == nil || status.InstalledVersion != nil || + state.Updates.SkippedVersion == state.Updates.LatestVersion { + return nil + } + if err := u.CheckCanInstall(); err != nil { + return nil + } + return status.AvailableVersion +} + +// RecordResponse records that the user responded to the update menu for the +// given version, in whatever way. lazygit doesn't show the menu again for a +// day, and the other lazygit instances close theirs. +func (u *Updater) RecordResponse(version *types.VersionNumber) { + u.updateAppState(func(state *config.AppState) { + state.Updates.LastResponse = u.now().Unix() + state.Updates.RespondedVersion = version.String() + }) +} + +// IsHandledAfter returns whether the user responded to the update menu in any +// lazygit instance after the given time, or the update got installed. A menu +// that was shown at that time is obsolete then. +func (u *Updater) IsHandledAfter(t time.Time) bool { + state := u.readAppState() + return state.Updates.LastResponse > t.Unix() || u.statusFromAppState(state).InstalledVersion != nil +} + +// SkipVersion keeps lazygit from reminding the user of the given version +func (u *Updater) SkipVersion(version *types.VersionNumber) { + u.updateAppState(func(state *config.AppState) { + state.Updates.SkippedVersion = version.String() + }) +} + +// newerVersion parses the given version and returns it if it is newer than the +// running lazygit, or nil otherwise +func (u *Updater) newerVersion(versionStr string) *types.VersionNumber { + if u.currentVersion == nil { + return nil + } + version, err := types.ParseVersionNumber(versionStr) + if err != nil || !u.currentVersion.IsOlderThan(version) { + return nil + } + return version +} + +func (u *Updater) readAppState() *config.AppState { + state, err := u.appState.ReadAppState() if err != nil { - return false + u.Log.Errorf("Error reading the app state: %v", err) + } + return state +} + +// Errors from saving the update state aren't worth bothering the user with; at +// worst, we check or remind again. +func (u *Updater) updateAppState(update func(state *config.AppState)) { + if err := u.appState.UpdateAppState(update); err != nil { + u.Log.Errorf("Error saving the app state: %v", err) + } +} + +func (u *Updater) IsInstalling() bool { + return u.installing.Load() +} + +// WaitForInstallToFinish waits until a running install is done replacing the +// executable, and keeps later installs from starting. Call it before exiting. +func (u *Updater) WaitForInstallToFinish() { + u.replaceMutex.Lock() +} + +// CleanUpAfterUpdate removes files that an earlier update left behind +func (u *Updater) CleanUpAfterUpdate() { + if u.installation.Kind == InstallKindRelease { + cleanUpAfterUpdate(u.installation.ExecutablePath) } - defer resp.Body.Close() - u.Log.Info("Received status code ", resp.StatusCode) - // OK (200) indicates that the resource is present. - return resp.StatusCode == http.StatusOK } diff --git a/pkg/updates/updates_test.go b/pkg/updates/updates_test.go new file mode 100644 index 000000000..0fd0d77ee --- /dev/null +++ b/pkg/updates/updates_test.go @@ -0,0 +1,529 @@ +package updates + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/jesseduffield/lazygit/pkg/common" + "github.com/jesseduffield/lazygit/pkg/config" + "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/stretchr/testify/assert" +) + +func TestCheckForUpdate(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"tag_name":"v0.67.0"}`)) + })) + defer server.Close() + + scenarios := []struct { + currentVersion string + expected *types.VersionNumber + }{ + {currentVersion: "0.66.2", expected: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}}, + {currentVersion: "0.67.0", expected: nil}, + {currentVersion: "0.67.1", expected: nil}, + } + + for _, s := range scenarios { + t.Run(s.currentVersion, func(t *testing.T) { + updater := newTestUpdater(t, server, s.currentVersion, Installation{Kind: InstallKindRelease}) + newVersion, err := updater.CheckForUpdate() + assert.NoError(t, err) + assert.Equal(t, s.expected, newVersion) + assert.Equal(t, s.expected, updater.Status().AvailableVersion) + + state := updater.readAppState() + assert.Equal(t, "v0.67.0", state.Updates.LatestVersion) + assert.WithinDuration(t, time.Now(), time.Unix(state.Updates.LastCheck, 0), time.Minute) + }) + } +} + +func TestCheckForUpdateIfDue(t *testing.T) { + requests := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + _, _ = w.Write([]byte(`{"tag_name":"v0.67.0"}`)) + })) + defer server.Close() + + now := time.Now() + scenarios := []struct { + name string + version string + method string + days int64 + lastCheck time.Time + latestVersion string + expectCheck bool + expectStatus *types.VersionNumber + }{ + { + name: "never checked", + version: "0.66.2", + method: "prompt", + days: 1, + expectCheck: true, + expectStatus: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, + { + name: "checked recently", + version: "0.66.2", + method: "prompt", + days: 1, + lastCheck: now.Add(-23 * time.Hour), + latestVersion: "v0.66.3", + expectCheck: false, + expectStatus: &types.VersionNumber{Major: 0, Minor: 66, Patch: 3}, + }, + { + name: "checked a day ago", + version: "0.66.2", + method: "prompt", + days: 1, + lastCheck: now.Add(-25 * time.Hour), + expectCheck: true, + expectStatus: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, + { + name: "checked two days ago, checking once a week", + version: "0.66.2", + method: "prompt", + days: 7, + lastCheck: now.Add(-48 * time.Hour), + latestVersion: "v0.66.2", + expectCheck: false, + expectStatus: nil, + }, + { + name: "update.method never", + version: "0.66.2", + method: "never", + days: 1, + expectCheck: true, + expectStatus: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, + { + name: "dev build", + version: "0123abcd", + method: "prompt", + days: 1, + expectCheck: false, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + requests = 0 + updater := newTestUpdater(t, server, "0.66.2", Installation{Kind: InstallKindRelease}) + updater.installation = DetectInstallation(BuildSourceRelease, s.version, "/home/user/.local/bin/lazygit") + updater.UserConfig().Update.Method = s.method + updater.UserConfig().Update.Days = s.days + if !s.lastCheck.IsZero() { + updater.appState.(*fakeAppStateStore).state.Updates.LastCheck = s.lastCheck.Unix() + } + updater.appState.(*fakeAppStateStore).state.Updates.LatestVersion = s.latestVersion + + assert.NoError(t, updater.CheckForUpdateIfDue()) + assert.Equal(t, s.expectCheck, requests == 1) + assert.Equal(t, s.expectStatus, updater.Status().AvailableVersion) + }) + } +} + +func TestRefreshStatus(t *testing.T) { + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/bin/lazygit"}) + state := updater.appState.(*fakeAppStateStore).state + + assert.Equal(t, Status{}, updater.RefreshStatus()) + + state.Updates.LatestVersion = "v0.66.2" + assert.Equal(t, Status{}, updater.RefreshStatus()) + + state.Updates.LatestVersion = "v0.67.0" + assert.Equal(t, Status{AvailableVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}}, updater.RefreshStatus()) + + state.Updates.InstalledVersion = "v0.67.0" + state.Updates.InstalledPath = "/other/lazygit" + assert.Equal(t, Status{AvailableVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}}, updater.RefreshStatus()) + + state.Updates.InstalledPath = "/bin/lazygit" + assert.Equal(t, Status{ + AvailableVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + InstalledVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, updater.RefreshStatus()) +} + +func TestInstall(t *testing.T) { + archive := makeTarGz(t, map[string]string{"LICENSE": "license", "lazygit": "new"}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/releases/download/v0.67.0/lazygit_0.67.0_linux_x86_64.tar.gz" { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write(archive) + })) + defer server.Close() + + dir := t.TempDir() + executablePath := filepath.Join(dir, "lazygit") + assert.NoError(t, os.WriteFile(executablePath, []byte("old"), 0o755)) + + updater := newTestUpdater(t, server, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: executablePath}) + assert.NoError(t, updater.CheckCanInstall()) + assert.Nil(t, updater.RefreshStatus().InstalledVersion) + + assert.NoError(t, updater.Install(&types.VersionNumber{Major: 0, Minor: 67, Patch: 0})) + assertFileContent(t, executablePath, "new") + assertDirContains(t, dir, "lazygit") + assert.Equal(t, &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, updater.Status().InstalledVersion) + + err := updater.Install(&types.VersionNumber{Major: 0, Minor: 68, Patch: 0}) + assert.ErrorContains(t, err, "lazygit_0.68.0_linux_x86_64.tar.gz returned 404 Not Found") + assertFileContent(t, executablePath, "new") + assert.Equal(t, &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, updater.RefreshStatus().InstalledVersion) + + // Another lazygit, running from a different executable, doesn't see the + // installed version + otherUpdater := newTestUpdater(t, server, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/other/lazygit"}) + otherUpdater.appState = updater.appState + assert.Nil(t, otherUpdater.RefreshStatus().InstalledVersion) + + // After a restart, the installed version is the running one + restartedUpdater := newTestUpdater(t, server, "0.67.0", Installation{Kind: InstallKindRelease, ExecutablePath: executablePath}) + restartedUpdater.appState = updater.appState + assert.Nil(t, restartedUpdater.RefreshStatus().InstalledVersion) +} + +func TestReminders(t *testing.T) { + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + hoursAgo := func(hours int) int64 { return now.Add(-time.Duration(hours) * time.Hour).Unix() } + v0670 := &types.VersionNumber{Major: 0, Minor: 67, Patch: 0} + + scenarios := []struct { + name string + state config.UpdatesState + expectWhenIdle *types.VersionNumber + expectAtStartup *types.VersionNumber + }{ + { + name: "no update", + state: config.UpdatesState{LatestVersion: "v0.66.2", LatestVersionFoundAt: hoursAgo(1000)}, + expectWhenIdle: nil, + expectAtStartup: nil, + }, + { + name: "update found recently", + state: config.UpdatesState{LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(1)}, + expectWhenIdle: v0670, + expectAtStartup: nil, + }, + { + name: "update found a week ago", + state: config.UpdatesState{LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(7 * 24)}, + expectWhenIdle: v0670, + expectAtStartup: v0670, + }, + { + name: "update found a week ago, responded to the menu for an older version", + state: config.UpdatesState{ + LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(7 * 24), + LastResponse: hoursAgo(25), RespondedVersion: "v0.66.3", + }, + expectWhenIdle: v0670, + expectAtStartup: v0670, + }, + { + name: "update found a week ago, responded to the menu already", + state: config.UpdatesState{ + LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(7 * 24), + LastResponse: hoursAgo(25), RespondedVersion: "v0.67.0", + }, + expectWhenIdle: v0670, + expectAtStartup: nil, + }, + { + name: "responded less than a day ago", + state: config.UpdatesState{ + LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(7 * 24), + LastResponse: hoursAgo(23), RespondedVersion: "v0.67.0", + }, + expectWhenIdle: nil, + expectAtStartup: nil, + }, + { + name: "version skipped", + state: config.UpdatesState{ + LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(7 * 24), + SkippedVersion: "v0.67.0", + }, + expectWhenIdle: nil, + expectAtStartup: nil, + }, + { + name: "older version skipped", + state: config.UpdatesState{ + LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(1), + SkippedVersion: "v0.66.3", + }, + expectWhenIdle: v0670, + expectAtStartup: nil, + }, + { + name: "update installed already", + state: config.UpdatesState{ + LatestVersion: "v0.67.0", LatestVersionFoundAt: hoursAgo(7 * 24), + InstalledVersion: "v0.67.0", InstalledPath: "/bin/lazygit", + }, + expectWhenIdle: nil, + expectAtStartup: nil, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/bin/lazygit"}) + updater.now = func() time.Time { return now } + updater.appState.(*fakeAppStateStore).state.Updates = s.state + + assert.Equal(t, s.expectWhenIdle, updater.DueReminder(ReminderMenuWhenIdle)) + assert.Equal(t, s.expectAtStartup, updater.DueReminder(ReminderMenuAtStartup)) + }) + } +} + +func TestRecordResponse(t *testing.T) { + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + v0670 := &types.VersionNumber{Major: 0, Minor: 67, Patch: 0} + + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/bin/lazygit"}) + updater.now = func() time.Time { return now } + state := updater.appState.(*fakeAppStateStore).state + state.Updates = config.UpdatesState{LatestVersion: "v0.67.0", LatestVersionFoundAt: now.Add(-time.Hour).Unix()} + + // Showing the menu doesn't change anything, so other lazygit instances + // show it too + assert.Equal(t, v0670, updater.DueReminder(ReminderMenuWhenIdle)) + assert.Equal(t, v0670, updater.DueReminder(ReminderMenuWhenIdle)) + + updater.RecordResponse(v0670) + assert.Equal(t, now.Unix(), state.Updates.LastResponse) + assert.Equal(t, "v0.67.0", state.Updates.RespondedVersion) + + now = now.Add(23 * time.Hour) + assert.Nil(t, updater.DueReminder(ReminderMenuWhenIdle)) + now = now.Add(2 * time.Hour) + assert.Equal(t, v0670, updater.DueReminder(ReminderMenuWhenIdle)) + + updater.SkipVersion(v0670) + assert.Nil(t, updater.DueReminder(ReminderMenuWhenIdle)) +} + +func TestIsHandledAfter(t *testing.T) { + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + shownAt := now + v0670 := &types.VersionNumber{Major: 0, Minor: 67, Patch: 0} + + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/bin/lazygit"}) + updater.now = func() time.Time { return now } + state := updater.appState.(*fakeAppStateStore).state + state.Updates = config.UpdatesState{ + LatestVersion: "v0.67.0", LastResponse: now.Add(-25 * time.Hour).Unix(), RespondedVersion: "v0.67.0", + } + + assert.False(t, updater.IsHandledAfter(shownAt)) + + // The user responds in another lazygit + now = now.Add(5 * time.Second) + updater.RecordResponse(v0670) + assert.True(t, updater.IsHandledAfter(shownAt)) + + // Another lazygit installs the update + state.Updates.LastResponse = 0 + assert.False(t, updater.IsHandledAfter(shownAt)) + state.Updates.InstalledVersion = "v0.67.0" + state.Updates.InstalledPath = "/bin/lazygit" + assert.True(t, updater.IsHandledAfter(shownAt)) +} + +func TestClaimExitMessage(t *testing.T) { + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + v0670 := &types.VersionNumber{Major: 0, Minor: 67, Patch: 0} + + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/bin/lazygit"}) + updater.now = func() time.Time { return now } + state := updater.appState.(*fakeAppStateStore).state + state.Updates = config.UpdatesState{LatestVersion: "v0.67.0", LatestVersionFoundAt: now.Add(-8 * 24 * time.Hour).Unix()} + + assert.Equal(t, v0670, updater.ClaimExitMessage()) + assert.Nil(t, updater.ClaimExitMessage()) + + // The exit message isn't a response to the menu, so the menu still + // appears + assert.Equal(t, v0670, updater.DueReminder(ReminderMenuWhenIdle)) + assert.Equal(t, v0670, updater.DueReminder(ReminderMenuAtStartup)) + + now = now.Add(25 * time.Hour) + assert.Equal(t, v0670, updater.ClaimExitMessage()) + + // After a response to the menu, there's no exit message for a day + now = now.Add(25 * time.Hour) + updater.RecordResponse(v0670) + assert.Nil(t, updater.ClaimExitMessage()) +} + +func TestRemindersAreOffWithUpdateMethodNever(t *testing.T) { + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/bin/lazygit"}) + updater.appState.(*fakeAppStateStore).state.Updates = config.UpdatesState{LatestVersion: "v0.67.0"} + updater.UserConfig().Update.Method = "never" + + assert.Nil(t, updater.DueReminder(ReminderMenuWhenIdle)) +} + +func TestVersionToInstallInBackground(t *testing.T) { + executablePath := filepath.Join(t.TempDir(), "lazygit") + assert.NoError(t, os.WriteFile(executablePath, []byte("old"), 0o755)) + v0670 := &types.VersionNumber{Major: 0, Minor: 67, Patch: 0} + + scenarios := []struct { + name string + kind InstallKind + method string + state config.UpdatesState + expected *types.VersionNumber + }{ + { + name: "update available", + kind: InstallKindRelease, + method: "background", + state: config.UpdatesState{LatestVersion: "v0.67.0"}, + expected: v0670, + }, + { + name: "prompt", + kind: InstallKindRelease, + method: "prompt", + state: config.UpdatesState{LatestVersion: "v0.67.0"}, + expected: nil, + }, + { + name: "installed with Homebrew", + kind: InstallKindHomebrew, + method: "background", + state: config.UpdatesState{LatestVersion: "v0.67.0"}, + expected: nil, + }, + { + name: "no update", + kind: InstallKindRelease, + method: "background", + state: config.UpdatesState{LatestVersion: "v0.66.2"}, + expected: nil, + }, + { + name: "installed already", + kind: InstallKindRelease, + method: "background", + state: config.UpdatesState{LatestVersion: "v0.67.0", InstalledVersion: "v0.67.0", InstalledPath: executablePath}, + expected: nil, + }, + { + name: "skipped", + kind: InstallKindRelease, + method: "background", + state: config.UpdatesState{LatestVersion: "v0.67.0", SkippedVersion: "v0.67.0"}, + expected: nil, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: s.kind, ExecutablePath: executablePath}) + updater.UserConfig().Update.Method = s.method + updater.appState.(*fakeAppStateStore).state.Updates = s.state + + assert.Equal(t, s.expected, updater.VersionToInstallInBackground()) + }) + } +} + +func TestIsStartingUp(t *testing.T) { + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease}) + now := updater.startTime + updater.now = func() time.Time { return now } + + assert.True(t, updater.IsStartingUp()) + now = now.Add(time.Minute) + assert.False(t, updater.IsStartingUp()) +} + +func TestCheckRecordsWhenItFirstFoundAVersion(t *testing.T) { + latest := "v0.67.0" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"tag_name":"` + latest + `"}`)) + })) + defer server.Close() + + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + updater := newTestUpdater(t, server, "0.66.2", Installation{Kind: InstallKindRelease}) + updater.now = func() time.Time { return now } + state := updater.appState.(*fakeAppStateStore).state + + _, err := updater.CheckForUpdate() + assert.NoError(t, err) + assert.Equal(t, now.Unix(), state.Updates.LatestVersionFoundAt) + + foundAt := now + now = now.Add(48 * time.Hour) + _, err = updater.CheckForUpdate() + assert.NoError(t, err) + assert.Equal(t, foundAt.Unix(), state.Updates.LatestVersionFoundAt) + assert.Equal(t, now.Unix(), state.Updates.LastCheck) + + latest = "v0.67.1" + _, err = updater.CheckForUpdate() + assert.NoError(t, err) + assert.Equal(t, now.Unix(), state.Updates.LatestVersionFoundAt) +} + +func newTestUpdater(t *testing.T, server *httptest.Server, currentVersion string, installation Installation) *Updater { + t.Helper() + + version, err := types.ParseVersionNumber(currentVersion) + assert.NoError(t, err) + + updater := &Updater{ + Common: common.NewDummyCommon(), + appState: &fakeAppStateStore{state: &config.AppState{}}, + installation: installation, + currentVersion: version, + goos: "linux", + goarch: "amd64", + startTime: time.Now(), + now: time.Now, + } + if server != nil { + updater.httpClient = server.Client() + updater.repoURL = server.URL + } + return updater +} + +type fakeAppStateStore struct { + state *config.AppState +} + +func (self *fakeAppStateStore) ReadAppState() (*config.AppState, error) { + state := *self.state + return &state, nil +} + +func (self *fakeAppStateStore) UpdateAppState(update func(state *config.AppState)) error { + update(self.state) + return nil +} diff --git a/pkg/utils/lines.go b/pkg/utils/lines.go index 598dede7f..73ae8fd25 100644 --- a/pkg/utils/lines.go +++ b/pkg/utils/lines.go @@ -109,11 +109,14 @@ const ( notInEscapeSequence escapeSequenceState = iota afterEscapeChar inCSISequence + inOSCSequence + afterEscapeCharInOSCSequence ) // Recognizes ANSI escape sequences while iterating over the characters of a -// string. Only CSI sequences (ESC [ ... final byte) are recognized; these are -// the color and style codes that lazygit puts into view content. +// string. It recognizes CSI sequences (ESC [ ... final byte), which are the +// color and style codes that lazygit puts into view content, and OSC sequences +// (ESC ] ... BEL or ESC \), which lazygit uses for hyperlinks. type escapeSequenceTracker struct { state escapeSequenceState } @@ -123,9 +126,12 @@ type escapeSequenceTracker struct { func (self *escapeSequenceTracker) consume(chr rune) bool { switch self.state { case afterEscapeChar: - if chr == '[' { + switch chr { + case '[': self.state = inCSISequence - } else { + case ']': + self.state = inOSCSequence + default: self.state = notInEscapeSequence } return true @@ -136,6 +142,18 @@ func (self *escapeSequenceTracker) consume(chr rune) bool { self.state = notInEscapeSequence } return true + case inOSCSequence: + switch chr { + case '\x07': + self.state = notInEscapeSequence + case '\x1b': + self.state = afterEscapeCharInOSCSequence + } + return true + case afterEscapeCharInOSCSequence: + // The backslash of the string terminator (ESC \) + self.state = notInEscapeSequence + return true default: if chr == '\x1b' { self.state = afterEscapeChar diff --git a/pkg/utils/lines_test.go b/pkg/utils/lines_test.go index da03f8767..376f5e687 100644 --- a/pkg/utils/lines_test.go +++ b/pkg/utils/lines_test.go @@ -487,3 +487,11 @@ func TestWrapViewLinesToWidth(t *testing.T) { }) } } + +func TestWrapViewLinesToWidthWithHyperlink(t *testing.T) { + text := "Hello \x1b]8;;https://example.com\x1b\\big\x1b]8;;\x1b\\ world" + wrappedLines, _, _ := WrapViewLinesToWidth(true, false, text, 9, 4) + assert.Equal(t, + []string{"Hello \x1b]8;;https://example.com\x1b\\big\x1b]8;;\x1b\\", "world"}, + wrappedLines) +} diff --git a/schema-master/config.json b/schema-master/config.json index 7fa89a274..2112976ba 100644 --- a/schema-master/config.json +++ b/schema-master/config.json @@ -4138,14 +4138,14 @@ "background", "never" ], - "description": "One of: 'prompt' (default) | 'background' | 'never'", + "description": "One of: 'prompt' (default) | 'background' | 'never'\n'prompt': check for updates regularly, and remind you when there is one.\n'background': like 'prompt', but if lazygit was installed from one of our release archives, install updates without asking.\n'never': check for updates, and show a note in the bottom-right corner when there is one, but don't remind you of it.", "default": "prompt" }, "days": { "type": "integer", "minimum": 0, "description": "Period in days between update checks", - "default": 14 + "default": 1 } }, "additionalProperties": false, diff --git a/vendor/github.com/kardianos/osext/LICENSE b/vendor/github.com/kardianos/osext/LICENSE deleted file mode 100644 index 744875676..000000000 --- a/vendor/github.com/kardianos/osext/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/kardianos/osext/README.md b/vendor/github.com/kardianos/osext/README.md deleted file mode 100644 index 15cbc3d95..000000000 --- a/vendor/github.com/kardianos/osext/README.md +++ /dev/null @@ -1,21 +0,0 @@ -### Extensions to the "os" package. - -[![GoDoc](https://godoc.org/github.com/kardianos/osext?status.svg)](https://godoc.org/github.com/kardianos/osext) - -## Find the current Executable and ExecutableFolder. - -As of go1.8 the Executable function may be found in `os`. The Executable function -in the std lib `os` package is used if available. - -There is sometimes utility in finding the current executable file -that is running. This can be used for upgrading the current executable -or finding resources located relative to the executable file. Both -working directory and the os.Args[0] value are arbitrary and cannot -be relied on; os.Args[0] can be "faked". - -Multi-platform and supports: - * Linux - * OS X - * Windows - * Plan 9 - * BSDs. diff --git a/vendor/github.com/kardianos/osext/osext.go b/vendor/github.com/kardianos/osext/osext.go deleted file mode 100644 index 17f380f0e..000000000 --- a/vendor/github.com/kardianos/osext/osext.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Extensions to the standard "os" package. -package osext // import "github.com/kardianos/osext" - -import "path/filepath" - -var cx, ce = executableClean() - -func executableClean() (string, error) { - p, err := executable() - return filepath.Clean(p), err -} - -// Executable returns an absolute path that can be used to -// re-invoke the current program. -// It may not be valid after the current program exits. -func Executable() (string, error) { - return cx, ce -} - -// Returns same path as Executable, returns just the folder -// path. Excludes the executable name and any trailing slash. -func ExecutableFolder() (string, error) { - p, err := Executable() - if err != nil { - return "", err - } - - return filepath.Dir(p), nil -} diff --git a/vendor/github.com/kardianos/osext/osext_go18.go b/vendor/github.com/kardianos/osext/osext_go18.go deleted file mode 100644 index 009d8a926..000000000 --- a/vendor/github.com/kardianos/osext/osext_go18.go +++ /dev/null @@ -1,9 +0,0 @@ -//+build go1.8,!openbsd - -package osext - -import "os" - -func executable() (string, error) { - return os.Executable() -} diff --git a/vendor/github.com/kardianos/osext/osext_plan9.go b/vendor/github.com/kardianos/osext/osext_plan9.go deleted file mode 100644 index 95e237137..000000000 --- a/vendor/github.com/kardianos/osext/osext_plan9.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//+build !go1.8 - -package osext - -import ( - "os" - "strconv" - "syscall" -) - -func executable() (string, error) { - f, err := os.Open("/proc/" + strconv.Itoa(os.Getpid()) + "/text") - if err != nil { - return "", err - } - defer f.Close() - return syscall.Fd2path(int(f.Fd())) -} diff --git a/vendor/github.com/kardianos/osext/osext_procfs.go b/vendor/github.com/kardianos/osext/osext_procfs.go deleted file mode 100644 index e1f16f885..000000000 --- a/vendor/github.com/kardianos/osext/osext_procfs.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.8,android !go1.8,linux !go1.8,netbsd !go1.8,solaris !go1.8,dragonfly - -package osext - -import ( - "errors" - "fmt" - "os" - "runtime" - "strings" -) - -func executable() (string, error) { - switch runtime.GOOS { - case "linux", "android": - const deletedTag = " (deleted)" - execpath, err := os.Readlink("/proc/self/exe") - if err != nil { - return execpath, err - } - execpath = strings.TrimSuffix(execpath, deletedTag) - execpath = strings.TrimPrefix(execpath, deletedTag) - return execpath, nil - case "netbsd": - return os.Readlink("/proc/curproc/exe") - case "dragonfly": - return os.Readlink("/proc/curproc/file") - case "solaris": - return os.Readlink(fmt.Sprintf("/proc/%d/path/a.out", os.Getpid())) - } - return "", errors.New("ExecPath not implemented for " + runtime.GOOS) -} diff --git a/vendor/github.com/kardianos/osext/osext_sysctl.go b/vendor/github.com/kardianos/osext/osext_sysctl.go deleted file mode 100644 index 33cee2522..000000000 --- a/vendor/github.com/kardianos/osext/osext_sysctl.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.8,darwin !go1.8,freebsd openbsd - -package osext - -import ( - "os" - "os/exec" - "path/filepath" - "runtime" - "syscall" - "unsafe" -) - -var initCwd, initCwdErr = os.Getwd() - -func executable() (string, error) { - var mib [4]int32 - switch runtime.GOOS { - case "freebsd": - mib = [4]int32{1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1} - case "darwin": - mib = [4]int32{1 /* CTL_KERN */, 38 /* KERN_PROCARGS */, int32(os.Getpid()), -1} - case "openbsd": - mib = [4]int32{1 /* CTL_KERN */, 55 /* KERN_PROC_ARGS */, int32(os.Getpid()), 1 /* KERN_PROC_ARGV */} - } - - n := uintptr(0) - // Get length. - _, _, errNum := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, 0, uintptr(unsafe.Pointer(&n)), 0, 0) - if errNum != 0 { - return "", errNum - } - if n == 0 { // This shouldn't happen. - return "", nil - } - buf := make([]byte, n) - _, _, errNum = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)), 0, 0) - if errNum != 0 { - return "", errNum - } - if n == 0 { // This shouldn't happen. - return "", nil - } - - var execPath string - switch runtime.GOOS { - case "openbsd": - // buf now contains **argv, with pointers to each of the C-style - // NULL terminated arguments. - var args []string - argv := uintptr(unsafe.Pointer(&buf[0])) - Loop: - for { - argp := *(**[1 << 20]byte)(unsafe.Pointer(argv)) - if argp == nil { - break - } - for i := 0; uintptr(i) < n; i++ { - // we don't want the full arguments list - if string(argp[i]) == " " { - break Loop - } - if argp[i] != 0 { - continue - } - args = append(args, string(argp[:i])) - n -= uintptr(i) - break - } - if n < unsafe.Sizeof(argv) { - break - } - argv += unsafe.Sizeof(argv) - n -= unsafe.Sizeof(argv) - } - execPath = args[0] - // There is no canonical way to get an executable path on - // OpenBSD, so check PATH in case we are called directly - if execPath[0] != '/' && execPath[0] != '.' { - execIsInPath, err := exec.LookPath(execPath) - if err == nil { - execPath = execIsInPath - } - } - default: - for i, v := range buf { - if v == 0 { - buf = buf[:i] - break - } - } - execPath = string(buf) - } - - var err error - // execPath will not be empty due to above checks. - // Try to get the absolute path if the execPath is not rooted. - if execPath[0] != '/' { - execPath, err = getAbs(execPath) - if err != nil { - return execPath, err - } - } - // For darwin KERN_PROCARGS may return the path to a symlink rather than the - // actual executable. - if runtime.GOOS == "darwin" { - if execPath, err = filepath.EvalSymlinks(execPath); err != nil { - return execPath, err - } - } - return execPath, nil -} - -func getAbs(execPath string) (string, error) { - if initCwdErr != nil { - return execPath, initCwdErr - } - // The execPath may begin with a "../" or a "./" so clean it first. - // Join the two paths, trailing and starting slashes undetermined, so use - // the generic Join function. - return filepath.Join(initCwd, filepath.Clean(execPath)), nil -} diff --git a/vendor/github.com/kardianos/osext/osext_windows.go b/vendor/github.com/kardianos/osext/osext_windows.go deleted file mode 100644 index 074b3b385..000000000 --- a/vendor/github.com/kardianos/osext/osext_windows.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//+build !go1.8 - -package osext - -import ( - "syscall" - "unicode/utf16" - "unsafe" -) - -var ( - kernel = syscall.MustLoadDLL("kernel32.dll") - getModuleFileNameProc = kernel.MustFindProc("GetModuleFileNameW") -) - -// GetModuleFileName() with hModule = NULL -func executable() (exePath string, err error) { - return getModuleFileName() -} - -func getModuleFileName() (string, error) { - var n uint32 - b := make([]uint16, syscall.MAX_PATH) - size := uint32(len(b)) - - r0, _, e1 := getModuleFileNameProc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size)) - n = uint32(r0) - if n == 0 { - return "", e1 - } - return string(utf16.Decode(b[0:n])), nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 3336d1044..549c22453 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -77,9 +77,6 @@ github.com/jesseduffield/generics/set ## explicit; go 1.18 github.com/jesseduffield/lazycore/pkg/boxlayout github.com/jesseduffield/lazycore/pkg/utils -# github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 -## explicit -github.com/kardianos/osext # github.com/karimkhaleel/jsonschema v0.0.0-20231001195015-d933f0d94ea3 ## explicit; go 1.18 github.com/karimkhaleel/jsonschema