Skip to content

Commit fe134b9

Browse files
committed
history: Perform write process safe
1 parent 6164050 commit fe134b9

1 file changed

Lines changed: 26 additions & 21 deletions

File tree

internal/info/history.go

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
package info
22

33
import (
4+
"bytes"
45
"encoding/gob"
6+
"errors"
7+
"io/fs"
58
"os"
69
"path/filepath"
710
"strings"
811

912
"github.com/zyedidia/micro/v2/internal/config"
13+
"github.com/zyedidia/micro/v2/internal/screen"
1014
"github.com/zyedidia/micro/v2/internal/util"
1115
)
1216

@@ -17,24 +21,23 @@ func (i *InfoBuf) LoadHistory() {
1721
if config.GetGlobalOption("savehistory").(bool) {
1822
file, err := os.Open(filepath.Join(config.ConfigDir, "buffers", "history"))
1923
var decodedMap map[string][]string
20-
if err == nil {
21-
defer file.Close()
22-
decoder := gob.NewDecoder(file)
23-
err = decoder.Decode(&decodedMap)
24-
25-
if err != nil {
26-
i.Error("Error loading history:", err)
27-
return
24+
if err != nil {
25+
if !errors.Is(err, fs.ErrNotExist) {
26+
i.Error("Error loading history: ", err)
2827
}
28+
return
29+
}
30+
31+
defer file.Close()
32+
err = gob.NewDecoder(file).Decode(&decodedMap)
33+
if err != nil {
34+
i.Error("Error decoding history: ", err)
35+
return
2936
}
3037

3138
if decodedMap != nil {
3239
i.History = decodedMap
33-
} else {
34-
i.History = make(map[string][]string)
3540
}
36-
} else {
37-
i.History = make(map[string][]string)
3841
}
3942
}
4043

@@ -49,16 +52,18 @@ func (i *InfoBuf) SaveHistory() {
4952
}
5053
}
5154

52-
file, err := os.Create(filepath.Join(config.ConfigDir, "buffers", "history"))
53-
if err == nil {
54-
defer file.Close()
55-
encoder := gob.NewEncoder(file)
55+
var buf bytes.Buffer
56+
err := gob.NewEncoder(&buf).Encode(i.History)
57+
if err != nil {
58+
screen.TermMessage("Error encoding history: ", err)
59+
return
60+
}
5661

57-
err = encoder.Encode(i.History)
58-
if err != nil {
59-
i.Error("Error saving history:", err)
60-
return
61-
}
62+
filename := filepath.Join(config.ConfigDir, "buffers", "history")
63+
err = util.SafeWrite(filename, buf.Bytes(), true)
64+
if err != nil {
65+
screen.TermMessage("Error saving history: ", err)
66+
return
6267
}
6368
}
6469
}

0 commit comments

Comments
 (0)