fsutil writes, locks and checks the files of a program that several
users, or several runs, share (decision 37).
- WriteAtomic writes a temporary file in the same directory.
- It syncs the file and closes it.
- It renames the file over the old one, and syncs the directory. A reader sees the old file or the new one, never a part.
It renames the file over the old one, and syncs the directory. A reader sees the old file or the new one, never a part.
| Name | What it does |
|---|---|
fsutil.WriteAtomic | a file replaced whole; a file that exists keeps its mode and group |
fsutil.ExactMode | gives a file that exists exactly the mode too |
fsutil.Lock | an exclusive lock in a file beside the shared file |
fsutil.Update | changes a file under its lock; waits fsutil.DefaultLockWait |
fsutil.EnsureDir | a private directory of the user’s |
fsutil.CheckTrusted | refuses a file that a user other than this one or root could have written |
fsutil.ErrUntrusted | what each refusal matches with errors.Is |
dir, _ := os.MkdirTemp("", "prog-")
defer func() { _ = os.RemoveAll(dir) }()
path := filepath.Join(dir, "inventory")
unlock, err := fsutil.Lock(context.Background(), path, fsutil.DefaultLockWait)
if err != nil {
fmt.Println(err)
return
}
defer unlock()
_, err = fsutil.Lock(context.Background(), path, 100*time.Millisecond) // another run
fmt.Println(errors.Is(err, context.DeadlineExceeded)) truefsutil/example_test.go. CI runs it and checks its output.Fixed interfaces#
The name and the mode of the lock file, and ErrUntrusted. The texts of the
errors are not fixed.