+func WriteTemp(dir, base string, data []byte, uid, gid int, mode fs.FileMode) (
+ string, error) {
+
+ fh, err := os.CreateTemp(dir, base)
+ if err != nil {
+ return "", err
+ }
+ tmpPath := fh.Name()
+
+ _, err = fh.Write(data)
+ if err != nil {
+ fh.Close()
+ os.Remove(tmpPath)
+ return "", err
+ }
+ // CreateTemp() creates the file with 0600
+ err = fh.Chown(uid, gid)
+ if err != nil {
+ fh.Close()
+ os.Remove(tmpPath)
+ return "", err
+ }
+ err = fh.Chmod(mode)
+ if err != nil {
+ fh.Close()
+ os.Remove(tmpPath)
+ return "", err
+ }
+ err = fh.Sync()
+ if err != nil {
+ fh.Close()
+ os.Remove(tmpPath)
+ return "", err
+ }
+ err = fh.Close()
+ if err != nil {
+ fh.Close()
+ os.Remove(tmpPath)
+ return "", err
+ }
+
+ return tmpPath, nil
+}
+
+// SyncPath syncs path, which should be a directory. To guarantee durability