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 3f3170818d
commit f0684d83e9
5 changed files with 199 additions and 42 deletions

View File

@@ -13,7 +13,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
@@ -936,30 +935,17 @@ func (m *Model) SetIgnores(folder string, content []string) error {
return fmt.Errorf("Folder %s does not exist", folder)
}
fd, err := ioutil.TempFile(cfg.Path(), ".syncthing.stignore-"+folder)
fd, err := osutil.CreateAtomic(filepath.Join(cfg.Path(), ".stignore"), 0644)
if err != nil {
l.Warnln("Saving .stignore:", err)
return err
}
defer os.Remove(fd.Name())
for _, line := range content {
_, err = fmt.Fprintln(fd, line)
if err != nil {
l.Warnln("Saving .stignore:", err)
return err
}
fmt.Fprintln(fd, line)
}
err = fd.Close()
if err != nil {
l.Warnln("Saving .stignore:", err)
return err
}
file := filepath.Join(cfg.Path(), ".stignore")
err = osutil.Rename(fd.Name(), file)
if err != nil {
if err := fd.Close(); err != nil {
l.Warnln("Saving .stignore:", err)
return err
}