2020-03-18 04:28:47 +00:00
|
|
|
// Copyright (c) 2019 Tailscale Inc & AUTHORS All rights reserved.
|
2020-02-05 22:16:58 +00:00
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// Package atomicfile contains code related to writing to filesystems
|
|
|
|
// atomically.
|
|
|
|
//
|
|
|
|
// This package should be considered internal; its API is not stable.
|
|
|
|
package atomicfile // import "tailscale.com/atomicfile"
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2020-07-15 00:35:10 +01:00
|
|
|
"path/filepath"
|
2020-07-15 20:31:40 +01:00
|
|
|
"runtime"
|
2020-02-05 22:16:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// WriteFile writes data to filename+some suffix, then renames it
|
2022-08-14 05:19:43 +01:00
|
|
|
// into filename. The perm argument is ignored on Windows.
|
2020-07-15 00:35:10 +01:00
|
|
|
func WriteFile(filename string, data []byte, perm os.FileMode) (err error) {
|
|
|
|
f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename)+".tmp")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-07-15 00:35:10 +01:00
|
|
|
tmpName := f.Name()
|
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
f.Close()
|
|
|
|
os.Remove(tmpName)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
if _, err := f.Write(data); err != nil {
|
|
|
|
return err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-07-15 20:31:40 +01:00
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
if err := f.Chmod(perm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-07-15 00:35:10 +01:00
|
|
|
}
|
|
|
|
if err := f.Sync(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := f.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return os.Rename(tmpName, filename)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|