github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/cmd/go/internal/lockedfile/lockedfile.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package lockedfile creates and manipulates files whose contents should only
     6  // change atomically.
     7  package lockedfile
     8  
     9  import (
    10  	"github.com/shogo82148/std/io"
    11  	"github.com/shogo82148/std/io/fs"
    12  )
    13  
    14  // A File is a locked *os.File.
    15  //
    16  // Closing the file releases the lock.
    17  //
    18  // If the program exits while a file is locked, the operating system releases
    19  // the lock but may not do so promptly: callers must ensure that all locked
    20  // files are closed before exiting.
    21  type File struct {
    22  	osFile
    23  	closed bool
    24  }
    25  
    26  // OpenFile is like os.OpenFile, but returns a locked file.
    27  // If flag includes os.O_WRONLY or os.O_RDWR, the file is write-locked;
    28  // otherwise, it is read-locked.
    29  func OpenFile(name string, flag int, perm fs.FileMode) (*File, error)
    30  
    31  // Open is like os.Open, but returns a read-locked file.
    32  func Open(name string) (*File, error)
    33  
    34  // Create is like os.Create, but returns a write-locked file.
    35  func Create(name string) (*File, error)
    36  
    37  // Edit creates the named file with mode 0666 (before umask),
    38  // but does not truncate existing contents.
    39  //
    40  // If Edit succeeds, methods on the returned File can be used for I/O.
    41  // The associated file descriptor has mode O_RDWR and the file is write-locked.
    42  func Edit(name string) (*File, error)
    43  
    44  // Close unlocks and closes the underlying file.
    45  //
    46  // Close may be called multiple times; all calls after the first will return a
    47  // non-nil error.
    48  func (f *File) Close() error
    49  
    50  // Read opens the named file with a read-lock and returns its contents.
    51  func Read(name string) ([]byte, error)
    52  
    53  // Write opens the named file (creating it with the given permissions if needed),
    54  // then write-locks it and overwrites it with the given content.
    55  func Write(name string, content io.Reader, perm fs.FileMode) (err error)
    56  
    57  // Transform invokes t with the result of reading the named file, with its lock
    58  // still held.
    59  //
    60  // If t returns a nil error, Transform then writes the returned contents back to
    61  // the file, making a best effort to preserve existing contents on error.
    62  //
    63  // t must not modify the slice passed to it.
    64  func Transform(name string, t func([]byte) ([]byte, error)) (err error)