// Package atomicfile replaces small files so that a reader, a concurrent // writer or a crash never leaves a partly written file behind. package atomicfile import ( "encoding/json" "errors" "os" "path/filepath" ) // Write replaces path with data. The directory must exist. On failure the // previous file stays as it was and no temporary file is left. func Write(path string, data []byte, perm os.FileMode) error { f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.tmp") if err != nil { return err } _, err = f.Write(data) if err == nil { err = f.Chmod(perm) } if err == nil { err = f.Sync() } err = errors.Join(err, f.Close()) if err == nil { err = os.Rename(f.Name(), path) } if err != nil { return errors.Join(err, os.Remove(f.Name())) } return nil } // WriteJSON replaces path with v as indented JSON. func WriteJSON(path string, v any, perm os.FileMode) error { data, err := json.MarshalIndent(v, "", " ") if err != nil { return err } return Write(path, append(data, '\n'), perm) }