]> git.giacomolli.uk - onechat/blob - file.go
Reflow comments over the reflow width
[onechat] / file.go
1 package main
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "path/filepath"
8 )
9
10 // writeFileAtomic replaces the file at path with data through a temporary file
11 // and a rename. A reader or a crash of the process sees the old file or the new
12 // file, never a part of one.
13 func writeFileAtomic(path string, data []byte) error {
14 file, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
15 if err != nil {
16 return fmt.Errorf("create temporary file: %w", err)
17 }
18
19 _, err = file.Write(data)
20 err = errors.Join(err, file.Close())
21 if err == nil {
22 err = os.Rename(file.Name(), path)
23 }
24
25 if err != nil {
26 return errors.Join(fmt.Errorf("replace file: %w", err), os.Remove(file.Name()))
27 }
28
29 return nil
30 }