history: Perform write process safe

This commit is contained in:
Jöran Karl 2025-01-09 21:26:47 +01:00
parent 6164050425
commit fe134b92d5

View File

@ -1,12 +1,16 @@
package info package info
import ( import (
"bytes"
"encoding/gob" "encoding/gob"
"errors"
"io/fs"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/zyedidia/micro/v2/internal/config" "github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util" "github.com/zyedidia/micro/v2/internal/util"
) )
@ -17,24 +21,23 @@ func (i *InfoBuf) LoadHistory() {
if config.GetGlobalOption("savehistory").(bool) { if config.GetGlobalOption("savehistory").(bool) {
file, err := os.Open(filepath.Join(config.ConfigDir, "buffers", "history")) file, err := os.Open(filepath.Join(config.ConfigDir, "buffers", "history"))
var decodedMap map[string][]string var decodedMap map[string][]string
if err == nil { if err != nil {
defer file.Close() if !errors.Is(err, fs.ErrNotExist) {
decoder := gob.NewDecoder(file) i.Error("Error loading history: ", err)
err = decoder.Decode(&decodedMap)
if err != nil {
i.Error("Error loading history:", err)
return
} }
return
}
defer file.Close()
err = gob.NewDecoder(file).Decode(&decodedMap)
if err != nil {
i.Error("Error decoding history: ", err)
return
} }
if decodedMap != nil { if decodedMap != nil {
i.History = decodedMap 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")) var buf bytes.Buffer
if err == nil { err := gob.NewEncoder(&buf).Encode(i.History)
defer file.Close() if err != nil {
encoder := gob.NewEncoder(file) screen.TermMessage("Error encoding history: ", err)
return
}
err = encoder.Encode(i.History) filename := filepath.Join(config.ConfigDir, "buffers", "history")
if err != nil { err = util.SafeWrite(filename, buf.Bytes(), true)
i.Error("Error saving history:", err) if err != nil {
return screen.TermMessage("Error saving history: ", err)
} return
} }
} }
} }