❯ go-clikit
v0.10.0 pkg.go.dev ↗

packages › files › fsutil

fsutil

import "github.com/GSI-HPC/go-clikit/fsutil"

Write a file whole or not at all, change a shared file under a lock, and refuse a file that another user could have written.

since v0.10.0 imports: termtextrequires: golang.org/x/sys/unix decisions 26 · 37 · 47
The place of fsutil in go-clikit: the packages it imports, and the packages that import it.termtextprogressdisplaycliprogressprogresstestmcpprogresseventlogfanoutfanouttestclioutdoctorfsutilcobratreecobratreetestlocalwebsessionsselocalwebtestlaunchassetspagehtmx

fsutil writes, locks and checks the files of a program that several users, or several runs, share (decision 37).

~/.local/state/prog/a temporary filetemporary file ✓ syncedstate.json (new)rename(2)a reader opens state.json:old, or new, 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.
NameWhat it does
fsutil.WriteAtomica file replaced whole; a file that exists keeps its mode and group
fsutil.ExactModegives a file that exists exactly the mode too
fsutil.Lockan exclusive lock in a file beside the shared file
fsutil.Updatechanges a file under its lock; waits fsutil.DefaultLockWait
fsutil.EnsureDira private directory of the user’s
fsutil.CheckTrustedrefuses a file that a user other than this one or root could have written
fsutil.ErrUntrustedwhat 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))
 true
ExampleLock in fsutil/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.