Replace GetAppState and SaveAppState with ReadAppState and UpdateAppState

Each lazygit instance reads state.yml once at startup. Callers change
that copy and then save all of it. So an instance doesn't see what
other instances changed after it started, and when it saves, it
overwrites their changes.

To fix this, the following commits make ReadAppState read the file and
UpdateAppState apply the change to what it finds in the file. For this
to work, callers must express a change as an operation on the current
state: add a command to the front of the history, remove a history
entry by its value, move the current repo to the front of the recent
repos. The call sites already compute the new value from the current
one; move that code into the update function.

This commit still works on the in-memory copy, so it doesn't change
behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Stefan HallerandClaude Opus 5.5 committed 2026-11-15 08:10:58 +01:00
1 parent 9ff9479baf
commit 76064a302b
24 files changed
+112 -72

No files matched your search

+5 -1
View File
@@ -166,7 +166,11 @@ func isDirectoryAGitRepository(dir string) (bool, error) {
}
func openRecentRepo(app *App) bool {
for _, repoDir := range app.Config.GetAppState().RecentRepos {
appState, err := app.Config.ReadAppState()
if err != nil {
app.Log.Errorf("error when reading app state: %v", err)
}
for _, repoDir := range appState.RecentRepos {
if isRepo, _ := isDirectoryAGitRepository(repoDir); isRepo {
if err := os.Chdir(repoDir); err == nil {
// We're still in setup, before the gui exists, so we can't show the approval popup
+2 -2
View File
@@ -51,8 +51,8 @@ type AppConfigurer interface {
ReloadChangedUserConfigFiles() (error, bool)
GetTempDir() string
GetAppState() *AppState
SaveAppState() error
ReadAppState() (*AppState, error)
UpdateAppState(update func(state *AppState)) error
GetCachedGithubPullRequests(repoPath string) ([]CachedPullRequest, error)
SaveCachedGithubPullRequests(repoPath string, pullRequests []CachedPullRequest) error
}
+13 -5
View File
@@ -6,13 +6,21 @@ import (
"gopkg.in/yaml.v3"
)
// GetAppState returns the app state
func (c *AppConfig) GetAppState() *AppState {
return c.appState
// ReadAppState returns the app state. If it can't be read, it returns the
// defaults together with the error. Don't change the returned struct; use
// UpdateAppState for that.
func (c *AppConfig) ReadAppState() (*AppState, error) {
return c.appState, nil
}
// SaveAppState marshalls the AppState struct and writes it to the disk
func (c *AppConfig) SaveAppState() error {
// UpdateAppState calls update to change the app state, and saves it.
func (c *AppConfig) UpdateAppState(update func(state *AppState)) error {
update(c.appState)
return c.saveAppState()
}
// saveAppState marshalls the AppState struct and writes it to the disk
func (c *AppConfig) saveAppState() error {
marshalledAppState, err := yaml.Marshal(c.appState)
if err != nil {
return err
+1 -1
View File
@@ -285,7 +285,7 @@ func (self *ReposHelper) CreateRecentReposMenu() error {
return err
}
// Don't offer the repo we're in
recentRepoPaths := lo.Without(self.c.GetAppState().RecentRepos, currentRepo)
recentRepoPaths := lo.Without(self.c.ReadAppState().RecentRepos, currentRepo)
currentBranches := make([]string, len(recentRepoPaths))
+14 -22
View File
@@ -1,9 +1,9 @@
package controllers
import (
"slices"
"strings"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
@@ -22,35 +22,27 @@ func (self *ShellCommandAction) Call() error {
PreserveWhitespace: true,
HandleConfirm: func(command string) error {
if self.shouldSaveCommand(command) {
self.c.GetAppState().ShellCommandsHistory = utils.Limit(
lo.Uniq(append([]string{command}, self.c.GetAppState().ShellCommandsHistory...)),
1000,
)
self.c.UpdateAppState(func(state *config.AppState) {
state.ShellCommandsHistory = utils.Limit(
lo.Uniq(append([]string{command}, state.ShellCommandsHistory...)),
1000,
)
})
}
self.c.SaveAppStateAndLogError()
self.c.LogAction(self.c.Tr.Actions.CustomCommand)
return self.c.RunSubprocessAndRefresh(
self.c.OS().Cmd.NewShell(command, self.c.UserConfig().OS.ShellFunctionsFile),
)
},
HandleDeleteSuggestion: func(index int) error {
// index is the index in the _filtered_ list of suggestions, so we
// need to map it back to the full list. There's no really good way
// to do this, but fortunately we keep the items in the
// ShellCommandsHistory unique, which allows us to simply search
// for it by string.
// index is the index in the _filtered_ list of suggestions, not in
// the full list. We keep the items in the ShellCommandsHistory
// unique, so we can remove the item by its value.
item := self.c.Contexts().Suggestions.GetItems()[index].Value
fullIndex := lo.IndexOf(self.c.GetAppState().ShellCommandsHistory, item)
if fullIndex == -1 {
// Should never happen, but better be safe
return nil
}
self.c.GetAppState().ShellCommandsHistory = slices.Delete(
self.c.GetAppState().ShellCommandsHistory, fullIndex, fullIndex+1)
self.c.SaveAppStateAndLogError()
self.c.UpdateAppState(func(state *config.AppState) {
state.ShellCommandsHistory = lo.Without(state.ShellCommandsHistory, item)
})
self.c.Contexts().Suggestions.RefreshSuggestions()
return nil
},
@@ -61,7 +53,7 @@ func (self *ShellCommandAction) Call() error {
func (self *ShellCommandAction) GetShellCommandsHistorySuggestionsFunc() func(string) []*types.Suggestion {
return func(input string) []*types.Suggestion {
history := self.c.GetAppState().ShellCommandsHistory
history := self.c.ReadAppState().ShellCommandsHistory
return helpers.FilterFunc(history, self.c.UserConfig().Gui.UseFuzzySearch())(input)
}
+4 -2
View File
@@ -3,6 +3,7 @@ package gui
import (
"io"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/style"
@@ -23,8 +24,9 @@ func (gui *Gui) handleCreateExtrasMenuPanel() error {
}
show := !gui.c.State().GetShowExtrasWindow()
gui.c.State().SetShowExtrasWindow(show)
gui.c.GetAppState().HideCommandLog = !show
gui.c.SaveAppStateAndLogError()
gui.c.UpdateAppState(func(state *config.AppState) {
state.HideCommandLog = !show
})
return nil
},
},
+5 -4
View File
@@ -537,7 +537,7 @@ func (gui *Gui) onUserConfigLoaded() error {
// originally we could only hide the command log permanently via the config
// but now we do it via state. So we need to still support the config for the
// sake of backwards compatibility. We're making use of short circuiting here
gui.ShowExtrasWindow = userConfig.Gui.ShowCommandLog && !gui.c.GetAppState().HideCommandLog
gui.ShowExtrasWindow = userConfig.Gui.ShowCommandLog && !gui.c.ReadAppState().HideCommandLog
if userConfig.Gui.NerdFontsVersion != "" {
icons.SetNerdFontsVersion(userConfig.Gui.NerdFontsVersion)
@@ -1188,8 +1188,9 @@ func (gui *Gui) showIntroPopupMessage() {
gui.c.OnUIThread(func() error {
onConfirm := func() error {
gui.c.GetAppState().StartupPopupVersion = StartupPopupVersion
gui.c.SaveAppStateAndLogError()
gui.c.UpdateAppState(func(state *config.AppState) {
state.StartupPopupVersion = StartupPopupVersion
})
gui.waitForIntro.Done()
return nil
}
@@ -1222,7 +1223,7 @@ func (gui *Gui) showBreakingChangesMessage() {
}
last := &types.VersionNumber{}
lastVersionStr := gui.c.GetAppState().LastVersion
lastVersionStr := gui.c.ReadAppState().LastVersion
// If there's no saved last version, we show all release notes. This is for
// people upgrading from a version before we started to save lastVersion.
// First time new users won't see the release notes because we show them the
+8 -8
View File
@@ -85,16 +85,16 @@ func (self *guiCommon) ContextForKey(key types.ContextKey) types.Context {
return self.gui.State.ContextMgr.ContextForKey(key)
}
func (self *guiCommon) GetAppState() *config.AppState {
return self.gui.Config.GetAppState()
func (self *guiCommon) ReadAppState() *config.AppState {
appState, err := self.gui.Config.ReadAppState()
if err != nil {
self.gui.Log.Errorf("error when reading app state: %v", err)
}
return appState
}
func (self *guiCommon) SaveAppState() error {
return self.gui.Config.SaveAppState()
}
func (self *guiCommon) SaveAppStateAndLogError() {
if err := self.gui.Config.SaveAppState(); err != nil {
func (self *guiCommon) UpdateAppState(update func(state *config.AppState)) {
if err := self.gui.Config.UpdateAppState(update); err != nil {
self.gui.Log.Errorf("error when saving app state: %v", err)
}
}
+5 -3
View File
@@ -3,6 +3,7 @@ package gui
import (
"errors"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
@@ -311,7 +312,7 @@ func (gui *Gui) onRepoViewReset() error {
func (gui *Gui) onInitialViewsCreation() error {
if !gui.c.UserConfig().DisableStartupPopups {
storedPopupVersion := gui.c.GetAppState().StartupPopupVersion
storedPopupVersion := gui.c.ReadAppState().StartupPopupVersion
if storedPopupVersion < StartupPopupVersion {
gui.showIntroPopupMessage()
} else {
@@ -319,8 +320,9 @@ func (gui *Gui) onInitialViewsCreation() error {
}
}
gui.c.GetAppState().LastVersion = gui.Config.GetVersion()
gui.c.SaveAppStateAndLogError()
gui.c.UpdateAppState(func(state *config.AppState) {
state.LastVersion = gui.Config.GetVersion()
})
if gui.showRecentRepos {
if err := gui.helpers.Repos.CreateRecentReposMenu(); err != nil {
+5 -4
View File
@@ -3,6 +3,8 @@ package gui
import (
"os"
"path/filepath"
"github.com/jesseduffield/lazygit/pkg/config"
)
// updateRecentRepoList registers the fact that we opened lazygit in this repo,
@@ -16,16 +18,15 @@ func (gui *Gui) updateRecentRepoList() error {
return nil
}
recentRepos := gui.c.GetAppState().RecentRepos
currentRepo, err := os.Getwd()
if err != nil {
return err
}
recentRepos = newRecentReposList(recentRepos, currentRepo)
// TODO: migrate this file to use forward slashes on all OSes for consistency
// (windows uses backslashes at the moment)
gui.c.GetAppState().RecentRepos = recentRepos
gui.c.SaveAppStateAndLogError()
gui.c.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = newRecentReposList(state.RecentRepos, currentRepo)
})
return nil
}
+4 -3
View File
@@ -95,9 +95,10 @@ type IGuiCommon interface {
ContextForKey(key ContextKey) Context
GetConfig() config.AppConfigurer
GetAppState() *config.AppState
SaveAppState() error
SaveAppStateAndLogError()
// Reads state.yml. If it can't be read, logs the error and returns the defaults.
ReadAppState() *config.AppState
// Calls update to change state.yml, and logs any error.
UpdateAppState(update func(state *config.AppState))
// Runs the given function on the UI thread (this is for things like showing a popup asking a user for input).
// Only necessary to call if you're not already on the UI thread i.e. you're inside a goroutine.
@@ -13,7 +13,9 @@ var CustomCommandsInPerRepoConfig = NewIntegrationTest(NewIntegrationTestArgs{
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {
otherRepo, _ := filepath.Abs("../other")
cfg.GetAppState().RecentRepos = []string{otherRepo}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{otherRepo}
})
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
@@ -13,7 +13,9 @@ var SidePanelsInPerRepoConfig = NewIntegrationTest(NewIntegrationTestArgs{
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {
otherRepo, _ := filepath.Abs("../other")
cfg.GetAppState().RecentRepos = []string{otherRepo}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{otherRepo}
})
},
SetupRepo: func(shell *Shell) {
shell.CloneNonBare("other")
@@ -19,7 +19,9 @@ var DirenvApprovesEnvrc = NewIntegrationTest(NewIntegrationTestArgs{
},
SetupConfig: func(cfg *config.AppConfig) {
otherRepo, _ := filepath.Abs("../other")
cfg.GetAppState().RecentRepos = []string{otherRepo}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{otherRepo}
})
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: config.Keybinding{"X"},
@@ -23,7 +23,9 @@ var DirenvLoadedOnRepoSwitch = NewIntegrationTest(NewIntegrationTestArgs{
},
SetupConfig: func(cfg *config.AppConfig) {
otherRepo, _ := filepath.Abs("../other")
cfg.GetAppState().RecentRepos = []string{otherRepo}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{otherRepo}
})
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: config.Keybinding{"X"},
@@ -24,7 +24,9 @@ var DirenvUnloadsOnBlockedEnvrc = NewIntegrationTest(NewIntegrationTestArgs{
},
SetupConfig: func(cfg *config.AppConfig) {
otherRepo, _ := filepath.Abs("../other")
cfg.GetAppState().RecentRepos = []string{otherRepo}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{otherRepo}
})
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: config.Keybinding{"X"},
@@ -19,7 +19,9 @@ var FilterRecentRepos = NewIntegrationTest(NewIntegrationTestArgs{
current, _ := filepath.Abs(".")
other, _ := filepath.Abs("../other")
target, _ := filepath.Abs("../target")
cfg.GetAppState().RecentRepos = []string{current, other, target}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{current, other, target}
})
},
SetupRepo: func(shell *Shell) {
shell.CloneNonBare("other")
@@ -20,7 +20,9 @@ var RecentReposBranchColumn = NewIntegrationTest(NewIntegrationTestArgs{
onBranch, _ := filepath.Abs("../on-branch")
detached, _ := filepath.Abs("../detached")
submodule, _ := filepath.Abs("sub")
cfg.GetAppState().RecentRepos = []string{current, onBranch, detached, submodule}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{current, onBranch, detached, submodule}
})
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
@@ -18,7 +18,9 @@ var RecentReposColumnWidths = NewIntegrationTest(NewIntegrationTestArgs{
// the first entry is the repo we're in, so it isn't offered
current, _ := filepath.Abs(".")
target, _ := filepath.Abs("../other")
cfg.GetAppState().RecentRepos = []string{current, target}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{current, target}
})
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
@@ -20,7 +20,9 @@ var RecentReposReftableRepo = NewIntegrationTest(NewIntegrationTestArgs{
current, _ := filepath.Abs(".")
reftable, _ := filepath.Abs("../reftable")
unborn, _ := filepath.Abs("../reftable-unborn")
cfg.GetAppState().RecentRepos = []string{current, reftable, unborn}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{current, reftable, unborn}
})
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
@@ -19,7 +19,9 @@ var RecentReposWithLongNames = NewIntegrationTest(NewIntegrationTestArgs{
current, _ := filepath.Abs(".")
target, _ := filepath.Abs("../repo-with-a-name-that-is-far-too-long")
other, _ := filepath.Abs("../other")
cfg.GetAppState().RecentRepos = []string{current, target, other}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{current, target, other}
})
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
@@ -11,9 +11,11 @@ var KeybindingSuggestionsWhenSwitchingRepos = NewIntegrationTest(NewIntegrationT
Description: "Show correct keybinding suggestions after switching between repos",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
SetupConfig: func(cfg *config.AppConfig) {
otherRepo, _ := filepath.Abs("../other")
config.GetAppState().RecentRepos = []string{otherRepo}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{otherRepo}
})
},
SetupRepo: func(shell *Shell) {
shell.CloneNonBare("other")
@@ -11,9 +11,11 @@ var SwitchRepoMovesTheSelection = NewIntegrationTest(NewIntegrationTestArgs{
Description: "The selection follows the focus of the repo being switched to, rather than the one being left",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
SetupConfig: func(cfg *config.AppConfig) {
otherRepo, _ := filepath.Abs("../other")
config.GetAppState().RecentRepos = []string{otherRepo}
_ = cfg.UpdateAppState(func(state *config.AppState) {
state.RecentRepos = []string{otherRepo}
})
},
SetupRepo: func(shell *Shell) {
shell.CloneNonBare("other")
+8 -3
View File
@@ -70,8 +70,9 @@ func (u *Updater) getLatestVersionNumber() (string, error) {
// RecordLastUpdateCheck records last time an update check was performed
func (u *Updater) RecordLastUpdateCheck() error {
u.Config.GetAppState().LastUpdateCheck = time.Now().Unix()
return u.Config.SaveAppState()
return u.Config.UpdateAppState(func(state *config.AppState) {
state.LastUpdateCheck = time.Now().Unix()
})
}
// expecting version to be of the form `v12.34.56`
@@ -175,7 +176,11 @@ func (u *Updater) skipUpdateCheck() bool {
}
currentTimestamp := time.Now().Unix()
lastUpdateCheck := u.Config.GetAppState().LastUpdateCheck
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 {