Skip to content

Commit

Permalink
Fix accidental concurrent preference writes (#2450)
Browse files Browse the repository at this point in the history
By syncing the File write we can be sure a second write puts the updated file after.

Fixes #2449
  • Loading branch information
andydotxyz committed Sep 9, 2021
1 parent 747a4e9 commit 2b45663
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
6 changes: 6 additions & 0 deletions app/preferences.go
Expand Up @@ -56,11 +56,17 @@ func (p *preferences) saveToFile(path string) error {
return err
}
}
defer file.Close()
encode := json.NewEncoder(file)

p.InMemoryPreferences.ReadValues(func(values map[string]interface{}) {
err = encode.Encode(&values)
})

err2 := file.Sync()
if err == nil {
err = err2
}
return err
}

Expand Down
20 changes: 20 additions & 0 deletions app/preferences_test.go
Expand Up @@ -40,6 +40,26 @@ func TestPreferences_Save(t *testing.T) {
assert.JSONEq(t, string(expected), string(content))
}

func TestPreferences_Save_OverwriteFast(t *testing.T) {
p := loadPreferences("dummy2")
p.WriteValues(func(val map[string]interface{}) {
val["key"] = "value"
})

path := filepath.Join(os.TempDir(), "fynePrefs2.json")
defer os.Remove(path)
p.saveToFile(path)

p.WriteValues(func(val map[string]interface{}) {
val["key2"] = "value2"
})
p.saveToFile(path)

p2 := loadPreferences("dummy")
p2.loadFromFile(path)
assert.Equal(t, "value2", p2.String("key2"))
}

func TestPreferences_Load(t *testing.T) {
p := loadPreferences("dummy")
p.loadFromFile(filepath.Join("testdata", "preferences.json"))
Expand Down

0 comments on commit 2b45663

Please sign in to comment.