diff --git a/pkg/config/app_state.go b/pkg/config/app_state.go index 136e7a2c2..7ec4966d8 100644 --- a/pkg/config/app_state.go +++ b/pkg/config/app_state.go @@ -1,6 +1,7 @@ package config import ( + "bytes" "os" "gopkg.in/yaml.v3" @@ -47,7 +48,15 @@ func (c *AppConfig) UpdateAppState(update func(state *AppState)) error { // If the file can't be parsed, we start from the defaults and replace it. appState, _ := parseAppState(content) update(appState) - return c.writeAppStateFile(appState) + + newContent, err := yaml.Marshal(appState) + if err != nil { + return err + } + if bytes.Equal(newContent, content) { + return nil + } + return c.writeAppStateFile(newContent) } func (c *AppConfig) readAppStateFile() ([]byte, error) { @@ -73,17 +82,12 @@ func parseAppState(content []byte) (*AppState, error) { return appState, nil } -func (c *AppConfig) writeAppStateFile(appState *AppState) error { +func (c *AppConfig) writeAppStateFile(content []byte) error { if c.appStatePath == "" { return nil } - content, err := yaml.Marshal(appState) - if err != nil { - return err - } - - err = os.WriteFile(c.appStatePath, content, 0o644) + err := os.WriteFile(c.appStatePath, content, 0o644) if err != nil && os.IsPermission(err) { // apparently when people have read-only permissions they prefer us to fail silently return nil diff --git a/pkg/config/app_state_test.go b/pkg/config/app_state_test.go index ca3b2e342..78d4af4cc 100644 --- a/pkg/config/app_state_test.go +++ b/pkg/config/app_state_test.go @@ -4,7 +4,9 @@ import ( "os" "path/filepath" "testing" + "time" + "github.com/samber/lo" "github.com/stretchr/testify/assert" ) @@ -79,3 +81,21 @@ func TestAppStateUpdateKeepsUpdatesOfOtherInstances(t *testing.T) { assert.NoError(t, err) assert.Equal(t, []string{"from B", "from A"}, appState.ShellCommandsHistory) } + +func TestAppStateUpdateSkipsWritingUnchangedState(t *testing.T) { + configDir := useTempConfigDir(t) + statePath := filepath.Join(configDir, stateFileName) + appConfig, err := newAppConfig(t) + assert.NoError(t, err) + assert.NoError(t, appConfig.UpdateAppState(addToHistory("ls"))) + past := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) + assert.NoError(t, os.Chtimes(statePath, past, past)) + + assert.NoError(t, appConfig.UpdateAppState(func(state *AppState) { + state.ShellCommandsHistory = lo.Uniq(append([]string{"ls"}, state.ShellCommandsHistory...)) + })) + + info, err := os.Stat(statePath) + assert.NoError(t, err) + assert.True(t, info.ModTime().Equal(past)) +}