Add osutil.AtomicWriter

This captures the common pattern of writing to a temp file and moving it
to it's real name only if everything went well. It reduces the amount of
code in some places where we do this, but maybe not as much as I
expected because the upgrade thing is still a special snowflake...
This commit is contained in:
Jakob Borg
2015-07-12 01:03:40 +10:00
parent a04b005e93
commit 44e3bec42e
5 changed files with 155 additions and 42 deletions

View File

@@ -12,7 +12,6 @@ import (
"net/http"
"os"
"strings"
"time"
"github.com/syncthing/syncthing/internal/osutil"
"github.com/syncthing/syncthing/internal/sync"
@@ -91,28 +90,20 @@ func newCsrfToken() string {
}
func saveCsrfTokens() {
name := locations[locCsrfTokens]
tmp := fmt.Sprintf("%s.tmp.%d", name, time.Now().UnixNano())
// We're ignoring errors in here. It's not super critical and there's
// nothing relevant we can do about them anyway...
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
name := locations[locCsrfTokens]
f, err := osutil.CreateAtomic(name, 0600)
if err != nil {
return
}
defer os.Remove(tmp)
for _, t := range csrfTokens {
_, err := fmt.Fprintln(f, t)
if err != nil {
return
}
fmt.Fprintln(f, t)
}
err = f.Close()
if err != nil {
return
}
osutil.Rename(tmp, name)
f.Close()
}
func loadCsrfTokens() {