feat: use fileutil.SaveFile() to save file via tempfile

This commit is contained in:
Settel 2022-04-13 11:26:07 +02:00
parent a1681984a6
commit 4f8c55a8e3
4 changed files with 36 additions and 19 deletions

View File

@ -2,8 +2,8 @@ package application
import (
"encoding/json"
"os"
"path"
"sirlab.de/go/knowyt/fileutil"
"sirlab.de/go/knowyt/game"
)
@ -14,22 +14,8 @@ func (app *Application) saveGameState(gm *game.Game) error {
return errMarshal
}
dirName := path.Join(app.config.DataDir, "games", gm.GetId())
f, err := os.CreateTemp(dirName, "state.tmp-*.json")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(jsonString); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
fileName := path.Join(dirName, "state.json")
if err := os.Rename(f.Name(), fileName); err != nil {
filename := path.Join(app.config.DataDir, "games", gm.GetId(), "state.json")
if err := fileutil.SaveFile(filename, jsonString); err != nil {
return err
}

View File

@ -0,0 +1,29 @@
package fileutil
import (
"os"
"path"
)
func SaveFile(filename string, data []byte) error {
dirname := path.Dir(filename)
tmpFile, err := os.CreateTemp(dirname, "save-*.tmp")
if err != nil {
return err
}
defer os.Remove(tmpFile.Name())
if _, err := tmpFile.Write(data); err != nil {
return err
}
if err := tmpFile.Close(); err != nil {
return err
}
if err := os.Rename(tmpFile.Name(), filename); err != nil {
return err
}
return nil
}

View File

@ -5,6 +5,7 @@ import (
"fmt"
"os"
"sirlab.de/go/knowyt/engine"
"sirlab.de/go/knowyt/fileutil"
"sirlab.de/go/knowyt/quote"
"time"
)
@ -60,7 +61,7 @@ func (gm *Game) SaveGame() error {
if jsonBytes, err := json.Marshal(gmJson); err != nil {
return err
} else {
if err := os.WriteFile(gm.filename, jsonBytes, 0666); err != nil {
if err := fileutil.SaveFile(gm.filename, jsonBytes); err != nil {
return err
}
}

View File

@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path"
"sirlab.de/go/knowyt/fileutil"
"strings"
"time"
)
@ -62,7 +63,7 @@ func (usr *User) SaveUser() error {
if jsonBytes, err := json.Marshal(userJson); err != nil {
return err
} else {
if err := os.WriteFile(usr.filename, jsonBytes, 0666); err != nil {
if err := fileutil.SaveFile(usr.filename, jsonBytes); err != nil {
return err
}
}