// Package writefile writes a file atomically, so an interrupted or failed write // cannot leave a truncated file where a previous good one was.
package writefile import ( ) // Write atomically writes data to name with mode 0o644. It writes to a temp file // in name's own directory and renames it over name: an interrupted write cannot // leave a partial file in place of the previous good one, and sharing the // directory keeps the rename a same-filesystem swap. The parent directory must // already exist (os.CreateTemp fails when it does not, so Write never creates // it), and a failed write removes the temp file rather than leaving it behind. func (, string) error { , := os.CreateTemp(filepath.Dir(), "."+filepath.Base()+".*.tmp") if != nil { return } := .Name() defer func() { _ = os.Remove() }() // no-op after a successful rename if , := .WriteString(); != nil { _ = .Close() return } if := .Close(); != nil { return } // CreateTemp creates the file 0o600; set the conventional 0o644. if := os.Chmod(, 0o644); != nil { return } return os.Rename(, ) }