2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
// 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 (
|
2023-03-31 20:16:02 +00:00
|
|
|
"fmt"
|
2020-02-05 22:16:58 +00:00
|
|
|
"os"
|
2020-07-14 23:35:10 +00:00
|
|
|
"path/filepath"
|
2020-07-15 19:31:40 +00:00
|
|
|
"runtime"
|
2020-02-05 22:16:58 +00:00
|
|
|
)
|
|
|
|
|
2023-03-31 20:16:02 +00:00
|
|
|
// WriteFile writes data to filename+some suffix, then renames it into filename.
|
|
|
|
// The perm argument is ignored on Windows. If the target filename already
|
|
|
|
// exists but is not a regular file, WriteFile returns an error.
|
2020-07-14 23:35:10 +00:00
|
|
|
func WriteFile(filename string, data []byte, perm os.FileMode) (err error) {
|
2023-03-31 20:16:02 +00:00
|
|
|
fi, err := os.Stat(filename)
|
|
|
|
if err == nil && !fi.Mode().IsRegular() {
|
|
|
|
return fmt.Errorf("%s already exists and is not a regular file", filename)
|
|
|
|
}
|
2022-09-15 12:06:59 +00:00
|
|
|
f, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename)+".tmp")
|
2020-07-14 23:35:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-07-14 23:35:10 +00: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 19:31:40 +00:00
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
if err := f.Chmod(perm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-07-14 23:35:10 +00: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
|
|
|
}
|