]> ruderich.org/simon Gitweb - nsscash/nsscash.git/blobdiff - state.go
Use github.com/google/renameio for atomic file updates
[nsscash/nsscash.git] / state.go
index 9b67d9a038d14f3b5e9708c0ffd3e5ca5a9a4895..43fc598b1814bc17a92821587a40ed35b697c87a 100644 (file)
--- a/state.go
+++ b/state.go
@@ -1,6 +1,6 @@
 // Read and write the state file used to keep data over multiple runs
 
-// Copyright (C) 2019  Simon Ruderich
+// Copyright (C) 2019-2020  Simon Ruderich
 //
 // This program is free software: you can redistribute it and/or modify
 // it under the terms of the GNU Affero General Public License as published by
@@ -23,6 +23,8 @@ import (
        "os"
        "path/filepath"
        "time"
+
+       "github.com/google/renameio"
 )
 
 type State struct {
@@ -68,26 +70,15 @@ func WriteState(path string, state *State) error {
                return err
        }
 
-       // Write the file in an atomic fashion by creating a temporary file
-       // and renaming it over the target file
-
-       dir := filepath.Dir(path)
-       name := filepath.Base(path)
-
-       f, err := ioutil.TempFile(dir, "tmp-"+name+"-")
+       f, err := renameio.TempFile(filepath.Dir(path), path)
        if err != nil {
                return err
        }
-       defer os.Remove(f.Name())
-       defer f.Close()
+       defer f.Cleanup()
 
        _, err = f.Write(x)
        if err != nil {
                return err
        }
-       err = f.Sync()
-       if err != nil {
-               return err
-       }
-       return os.Rename(f.Name(), path)
+       return f.CloseAtomicallyReplace()
 }