github.com/bir3/gocompiler@v0.9.2202/src/cmd/gocmd/lockedfile/wrapper.go (about) 1 package lockedfile 2 3 import ( 4 "io" 5 "io/fs" 6 7 "github.com/bir3/gocompiler/src/cmd/gocmd/internal/lockedfile" 8 ) 9 10 type File struct { 11 lf *lockedfile.File 12 } 13 14 func mapfile(f *lockedfile.File) *File { 15 if f != nil { 16 return &File{f} 17 } 18 return nil 19 } 20 21 // Open is like os.Open, but returns a read-locked file. 22 func Open(name string) (*File, error) { 23 f, err := lockedfile.Open(name) 24 return mapfile(f), err 25 } 26 27 // Create is like os.Create, but returns a write-locked file. 28 func Create(name string) (*File, error) { 29 f, err := lockedfile.Create(name) 30 return mapfile(f), err 31 } 32 33 // Close unlocks and closes the underlying file. 34 // 35 // Close may be called multiple times; all calls after the first will return a 36 // non-nil error. 37 func (f *File) Close() error { 38 return f.lf.Close() 39 } 40 41 // Write opens the named file (creating it with the given permissions if needed), 42 // then write-locks it and overwrites it with the given content. 43 func Write(name string, content io.Reader, perm fs.FileMode) (err error) { 44 return lockedfile.Write(name, content, perm) 45 } 46 47 // Transform invokes t with the result of reading the named file, with its lock 48 // still held. 49 // 50 // If t returns a nil error, Transform then writes the returned contents back to 51 // the file, making a best effort to preserve existing contents on error. 52 // 53 // t must not modify the slice passed to it. 54 func Transform(name string, t func([]byte) ([]byte, error)) (err error) { 55 return lockedfile.Transform(name, t) 56 }