mirror of
https://github.com/jesseduffield/lazygit.git
synced 2026-11-21 04:46:29 +03:00
Rewrite the update check that u in the status panel starts
Checking for an update with `u` has several problems: - It offers to download and install the new version for any build that has a version, including builds from Homebrew or a Linux distribution. Overwriting those makes the package manager report the wrong version. - It only logs its errors, so the user never learns why nothing happens. This includes "You already have the latest version". For a build from a git checkout, the version is a commit hash; comparing it with the release version fails, and the user sees nothing at all. - Installing always fails on Windows. Rewrite it on top of the functions from the previous commits. Show the result of the check in all cases. If there's an update, show a menu that depends on how lazygit was installed. We only offer "Install now" for our release archives, and only if we can write to the folder of the executable. For package managers that we know, we show the command that updates lazygit. Otherwise we tell the user where to get the new version. Disable `u` for dev builds and say why. Installing replaces the executable with a rename, so quitting during an update can no longer leave a broken binary behind. Instead of asking for confirmation, wait for the rename to finish before exiting. Remove the check at startup for now. It never ran, because it checked for the build source "buildBinary" while .goreleaser.yml sets "binaryRelease". A later commit adds a new one. Use os.Executable instead of the osext package; os.Executable didn't exist yet when this code was written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1ac7b184fa
commit
89f269af58
26 files changed
+503
-749
No files matched your search
@@ -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
|
||||
|
||||
@@ -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=
|
||||
|
||||
+1
-4
@@ -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 {
|
||||
|
||||
@@ -245,6 +245,16 @@ type AppState struct {
|
||||
ShellCommandsHistory []string `yaml:"customcommandshistory"`
|
||||
|
||||
HideCommandLog bool
|
||||
|
||||
Updates UpdatesState
|
||||
}
|
||||
|
||||
// UpdatesState is what lazygit remembers about updates
|
||||
type UpdatesState struct {
|
||||
// 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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -2,7 +2,10 @@ package helpers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/constants"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/updates"
|
||||
@@ -21,82 +24,164 @@ func NewUpdateHelper(c *HelperCommon, updater *updates.Updater) *UpdateHelper {
|
||||
}
|
||||
}
|
||||
|
||||
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 newVersion == "" {
|
||||
return nil
|
||||
}
|
||||
if self.c.UserConfig().Update.Method == "background" {
|
||||
self.startUpdating(newVersion)
|
||||
return nil
|
||||
}
|
||||
return self.showUpdatePrompt(newVersion)
|
||||
}, false)
|
||||
func (self *UpdateHelper) OnStartup() {
|
||||
self.c.OnWorkerBackground(func(gocui.Task) error {
|
||||
self.updater.CleanUpAfterUpdate()
|
||||
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()},
|
||||
)}
|
||||
}
|
||||
|
||||
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.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.c.Menu(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()
|
||||
paragraphs := []string{utils.ResolvePlaceholderString(
|
||||
self.c.Tr.NewVersionAvailable,
|
||||
map[string]string{
|
||||
"newVersion": newVersion.String(),
|
||||
"currentVersion": self.updater.CurrentVersion().String(),
|
||||
},
|
||||
)
|
||||
)}
|
||||
items := []*types.MenuItem{}
|
||||
|
||||
self.c.Confirm(types.ConfirmOpts{
|
||||
Title: self.c.Tr.UpdateAvailableTitle,
|
||||
Prompt: message,
|
||||
HandleConfirm: func() error {
|
||||
self.startUpdating(newVersion)
|
||||
return nil
|
||||
},
|
||||
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.InstallKindHomebrew && 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.OpenReleaseNotes,
|
||||
OnPress: func() error { return self.c.OS().OpenLink(constants.Links.Releases) },
|
||||
})
|
||||
paragraphs = append(paragraphs, self.c.Tr.TurnOffUpdateChecks)
|
||||
|
||||
return nil
|
||||
return types.CreateMenuOptions{
|
||||
Title: self.c.Tr.UpdateAvailableTitle,
|
||||
Prompt: strings.Join(paragraphs, "\n\n"),
|
||||
Items: items,
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
func (self *UpdateHelper) updateInstalledMessage(version *types.VersionNumber) string {
|
||||
return utils.ResolvePlaceholderString(
|
||||
self.c.Tr.UpdateInstalled, map[string]string{"newVersion": version.String()},
|
||||
)
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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),
|
||||
@@ -213,7 +214,3 @@ func (self *StatusController) showDashboard() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (self *StatusController) handleCheckForUpdate() error {
|
||||
return self.c.Helpers().Update.CheckForUpdateInForeground()
|
||||
}
|
||||
+1
-3
@@ -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
|
||||
|
||||
+4
-10
@@ -152,8 +152,6 @@ type Gui struct {
|
||||
// for accessing the gui's state from outside this package
|
||||
stateAccessor *StateAccessor
|
||||
|
||||
Updating bool
|
||||
|
||||
c *helpers.HelperCommon
|
||||
helpers *helpers.Helpers
|
||||
|
||||
@@ -174,14 +172,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
|
||||
}
|
||||
@@ -1048,6 +1038,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{}) {
|
||||
|
||||
+1
-1
@@ -331,7 +331,7 @@ func (gui *Gui) onInitialViewsCreation() error {
|
||||
gui.showRecentRepos = false
|
||||
}
|
||||
|
||||
gui.helpers.Update.CheckForUpdateInBackground()
|
||||
gui.helpers.Update.OnStartup()
|
||||
|
||||
gui.waitForIntro.Done()
|
||||
|
||||
|
||||
@@ -436,9 +436,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
|
||||
|
||||
+39
-23
@@ -268,18 +268,26 @@ 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
|
||||
TurnOffUpdateChecks string
|
||||
InstallUpdateNow string
|
||||
CopyUpdateCommand string
|
||||
UpdateCommandCopiedToClipboard string
|
||||
OpenInstallationInstructions string
|
||||
OpenReleaseNotes string
|
||||
InstallingUpdateStatus string
|
||||
UpdateInstalled string
|
||||
UpdateInstallFailed string
|
||||
IntroPopupMessage string
|
||||
NonReloadableConfigWarningTitle string
|
||||
NonReloadableConfigWarning string
|
||||
@@ -1495,18 +1503,26 @@ 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. 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.",
|
||||
TurnOffUpdateChecks: "To turn off update checks, set update.method to never in your config file.",
|
||||
InstallUpdateNow: "Install now",
|
||||
CopyUpdateCommand: "Copy command",
|
||||
UpdateCommandCopiedToClipboard: "Command copied to clipboard",
|
||||
OpenInstallationInstructions: "Open installation instructions",
|
||||
OpenReleaseNotes: "Open 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}}",
|
||||
IntroPopupMessage: englishIntroPopupMessage,
|
||||
NonReloadableConfigWarningTitle: "Config changed",
|
||||
NonReloadableConfigWarning: englishNonReloadableConfigWarning,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
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.ExpectToast(
|
||||
Contains("Disabled: This is a development build (").
|
||||
Contains("), so lazygit can't check for updates."),
|
||||
)
|
||||
},
|
||||
})
|
||||
@@ -629,6 +629,7 @@ var tests = []*components.IntegrationTest{
|
||||
stash.StashStaged,
|
||||
stash.StashStagedPartialFile,
|
||||
stash.StashUnstaged,
|
||||
status.CheckForUpdateInDevBuild,
|
||||
status.ClickRepoNameToOpenReposMenu,
|
||||
status.ClickToFocus,
|
||||
status.ClickWorkingTreeStateToOpenRebaseOptionsMenu,
|
||||
|
||||
+150
-298
@@ -1,334 +1,186 @@
|
||||
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
|
||||
)
|
||||
|
||||
// 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
|
||||
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
if !u.currentVersion.IsOlderThan(latestVersion) {
|
||||
return nil, nil
|
||||
}
|
||||
return latestVersion, nil
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), installTimeout)
|
||||
defer cancel()
|
||||
|
||||
url := assetURL(u.repoURL, version, u.goos, u.goarch)
|
||||
u.Log.Infof("Installing %s", url)
|
||||
|
||||
binary, err := downloadBinary(ctx, u.httpClient, url, u.goos)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := u.replaceExecutable(binary); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = u.appState.UpdateAppState(func(state *config.AppState) {
|
||||
state.Updates.InstalledVersion = version.String()
|
||||
state.Updates.InstalledPath = u.installation.ExecutablePath
|
||||
})
|
||||
}
|
||||
|
||||
// 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]
|
||||
}
|
||||
|
||||
func (u *Updater) currentVersion() string {
|
||||
versionNumber := u.Config.GetVersion()
|
||||
if versionNumber == "unversioned" {
|
||||
return versionNumber
|
||||
}
|
||||
|
||||
return fmt.Sprintf("v%s", u.Config.GetVersion())
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
newVersion, err := u.getLatestVersionNumber()
|
||||
if err != nil {
|
||||
return "", err
|
||||
// The update is installed; only other lazygit instances won't know
|
||||
u.Log.Errorf("Error saving the app state: %v", 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)
|
||||
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 {
|
||||
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!")
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// InstalledVersion returns the version that an update installed in place of
|
||||
// the running lazygit, or nil if there's none. This lazygit, or another one
|
||||
// running from the same executable, can have installed it. The new version
|
||||
// takes effect when lazygit is restarted.
|
||||
func (u *Updater) InstalledVersion() *types.VersionNumber {
|
||||
state, err := u.appState.ReadAppState()
|
||||
if err != nil {
|
||||
return false
|
||||
u.Log.Errorf("Error reading the app state: %v", err)
|
||||
}
|
||||
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
|
||||
|
||||
if state.Updates.InstalledPath != u.installation.ExecutablePath {
|
||||
return nil
|
||||
}
|
||||
version, err := types.ParseVersionNumber(state.Updates.InstalledVersion)
|
||||
if err != nil || !u.currentVersion.IsOlderThan(version) {
|
||||
return nil
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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.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.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.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.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.InstalledVersion())
|
||||
}
|
||||
|
||||
func newTestUpdater(t *testing.T, server *httptest.Server, currentVersion string, installation Installation) *Updater {
|
||||
t.Helper()
|
||||
|
||||
version, err := types.ParseVersionNumber(currentVersion)
|
||||
assert.NoError(t, err)
|
||||
|
||||
return &Updater{
|
||||
Common: common.NewDummyCommon(),
|
||||
appState: &fakeAppStateStore{state: &config.AppState{}},
|
||||
installation: installation,
|
||||
currentVersion: version,
|
||||
httpClient: server.Client(),
|
||||
repoURL: server.URL,
|
||||
goos: "linux",
|
||||
goarch: "amd64",
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
-27
@@ -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.
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
### Extensions to the "os" package.
|
||||
|
||||
[](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.
|
||||
-33
@@ -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
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
//+build go1.8,!openbsd
|
||||
|
||||
package osext
|
||||
|
||||
import "os"
|
||||
|
||||
func executable() (string, error) {
|
||||
return os.Executable()
|
||||
}
|
||||
-22
@@ -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()))
|
||||
}
|
||||
-36
@@ -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)
|
||||
}
|
||||
-126
@@ -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
|
||||
}
|
||||
-36
@@ -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
|
||||
}
|
||||
Vendored
-3
@@ -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
|
||||
|
||||
Reference in new issue
Block a user