From fe134b92d5ee841bef92a463778b65c54c398fd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6ran=20Karl?= <3951388+JoeKar@users.noreply.github.com> Date: Thu, 9 Jan 2025 21:26:47 +0100 Subject: [PATCH] history: Perform write process safe --- internal/info/history.go | 47 ++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/internal/info/history.go b/internal/info/history.go index a09a58cf..ec946957 100644 --- a/internal/info/history.go +++ b/internal/info/history.go @@ -1,12 +1,16 @@ package info import ( + "bytes" "encoding/gob" + "errors" + "io/fs" "os" "path/filepath" "strings" "github.com/zyedidia/micro/v2/internal/config" + "github.com/zyedidia/micro/v2/internal/screen" "github.com/zyedidia/micro/v2/internal/util" ) @@ -17,24 +21,23 @@ func (i *InfoBuf) LoadHistory() { if config.GetGlobalOption("savehistory").(bool) { file, err := os.Open(filepath.Join(config.ConfigDir, "buffers", "history")) var decodedMap map[string][]string - if err == nil { - defer file.Close() - decoder := gob.NewDecoder(file) - err = decoder.Decode(&decodedMap) - - if err != nil { - i.Error("Error loading history:", err) - return + if err != nil { + if !errors.Is(err, fs.ErrNotExist) { + i.Error("Error loading history: ", err) } + return + } + + defer file.Close() + err = gob.NewDecoder(file).Decode(&decodedMap) + if err != nil { + i.Error("Error decoding history: ", err) + return } if decodedMap != nil { i.History = decodedMap - } else { - i.History = make(map[string][]string) } - } else { - i.History = make(map[string][]string) } } @@ -49,16 +52,18 @@ func (i *InfoBuf) SaveHistory() { } } - file, err := os.Create(filepath.Join(config.ConfigDir, "buffers", "history")) - if err == nil { - defer file.Close() - encoder := gob.NewEncoder(file) + var buf bytes.Buffer + err := gob.NewEncoder(&buf).Encode(i.History) + if err != nil { + screen.TermMessage("Error encoding history: ", err) + return + } - err = encoder.Encode(i.History) - if err != nil { - i.Error("Error saving history:", err) - return - } + filename := filepath.Join(config.ConfigDir, "buffers", "history") + err = util.SafeWrite(filename, buf.Bytes(), true) + if err != nil { + screen.TermMessage("Error saving history: ", err) + return } } }