Source file src/io/fs/fs.go

     1  // Copyright 2020 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 fs defines basic interfaces to a file system.
     6  // A file system can be provided by the host operating system
     7  // but also by other packages.
     8  //
     9  // # Path Names
    10  //
    11  // The interfaces in this package all operate on the same
    12  // path name syntax, regardless of the host operating system.
    13  //
    14  // Path names are UTF-8-encoded,
    15  // unrooted, slash-separated sequences of path elements, like “x/y/z”.
    16  // Path names must not contain an element that is “.” or “..” or the empty string,
    17  // except for the special case that the name "." may be used for the root directory.
    18  // Paths must not start or end with a slash: “/x” and “x/” are invalid.
    19  //
    20  // # Testing
    21  //
    22  // See the [testing/fstest] package for support with testing
    23  // implementations of file systems.
    24  package fs
    25  
    26  import (
    27  	"internal/oserror"
    28  	"time"
    29  	"unicode/utf8"
    30  )
    31  
    32  // An FS provides access to a hierarchical file system.
    33  //
    34  // The FS interface is the minimum implementation required of the file system.
    35  // A file system may implement additional interfaces,
    36  // such as [ReadFileFS], to provide additional or optimized functionality.
    37  //
    38  // [testing/fstest.TestFS] may be used to test implementations of an FS for
    39  // correctness.
    40  type FS interface {
    41  	// Open opens the named file.
    42  	// [File.Close] must be called to release any associated resources.
    43  	//
    44  	// When Open returns an error, it should be of type *PathError
    45  	// with the Op field set to "open", the Path field set to name,
    46  	// and the Err field describing the problem.
    47  	//
    48  	// Open should reject attempts to open names that do not satisfy
    49  	// ValidPath(name), returning a *PathError with Err set to
    50  	// ErrInvalid or ErrNotExist.
    51  	Open(name string) (File, error)
    52  }
    53  
    54  // ValidPath reports whether the given path name has the syntax required by [FS.Open].
    55  // Individual file system implementations may impose additional restrictions,
    56  // such as rejecting names not supported by the host operating system.
    57  //
    58  // Note that paths are slash-separated on all systems, even Windows.
    59  // Paths containing other characters such as backslash and colon
    60  // are accepted as valid, but those characters must never be
    61  // interpreted by an [FS] implementation as path element separators.
    62  // See the [Path Names] section for more details.
    63  //
    64  // [Path Names]: https://pkg.go.dev/io/fs#hdr-Path_Names
    65  func ValidPath(name string) bool {
    66  	if !utf8.ValidString(name) {
    67  		return false
    68  	}
    69  
    70  	if name == "." {
    71  		// special case
    72  		return true
    73  	}
    74  
    75  	// Iterate over elements in name, checking each.
    76  	for {
    77  		i := 0
    78  		for i < len(name) && name[i] != '/' {
    79  			i++
    80  		}
    81  		elem := name[:i]
    82  		if elem == "" || elem == "." || elem == ".." {
    83  			return false
    84  		}
    85  		if i == len(name) {
    86  			return true // reached clean ending
    87  		}
    88  		name = name[i+1:]
    89  	}
    90  }
    91  
    92  // A File provides access to a single file.
    93  // The File interface is the minimum implementation required of the file.
    94  // Directory files should also implement [ReadDirFile].
    95  // A file may implement [io.ReaderAt] or [io.Seeker] as optimizations.
    96  type File interface {
    97  	Stat() (FileInfo, error)
    98  	Read([]byte) (int, error)
    99  	Close() error
   100  }
   101  
   102  // A DirEntry is an entry read from a directory
   103  // (using the [ReadDir] function or a [ReadDirFile]'s ReadDir method).
   104  type DirEntry interface {
   105  	// Name returns the name of the file (or subdirectory) described by the entry.
   106  	// This name is only the final element of the path (the base name), not the entire path.
   107  	// For example, Name would return "hello.go" not "home/gopher/hello.go".
   108  	Name() string
   109  
   110  	// IsDir reports whether the entry describes a directory.
   111  	IsDir() bool
   112  
   113  	// Type returns the type bits for the entry.
   114  	// The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
   115  	Type() FileMode
   116  
   117  	// Info returns the FileInfo for the file or subdirectory described by the entry.
   118  	// The returned FileInfo may be from the time of the original directory read
   119  	// or from the time of the call to Info. If the file has been removed or renamed
   120  	// since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
   121  	// If the entry denotes a symbolic link, Info reports the information about the link itself,
   122  	// not the link's target.
   123  	Info() (FileInfo, error)
   124  }
   125  
   126  // A ReadDirFile is a directory file whose entries can be read with the ReadDir method.
   127  // Every directory file should implement this interface.
   128  // (It is permissible for any file to implement this interface,
   129  // but if so ReadDir should return an error for non-directories.)
   130  type ReadDirFile interface {
   131  	File
   132  
   133  	// ReadDir reads the contents of the directory and returns
   134  	// a slice of up to n DirEntry values in directory order.
   135  	// Subsequent calls on the same file will yield further DirEntry values.
   136  	//
   137  	// If n > 0, ReadDir returns at most n DirEntry structures.
   138  	// In this case, if ReadDir returns an empty slice, it will return
   139  	// a non-nil error explaining why.
   140  	// At the end of a directory, the error is io.EOF.
   141  	// (ReadDir must return io.EOF itself, not an error wrapping io.EOF.)
   142  	//
   143  	// If n <= 0, ReadDir returns all remaining DirEntry values from the directory
   144  	// in a single slice. In this case, if ReadDir succeeds (reads all the way
   145  	// to the end of the directory), it returns the slice and a nil error.
   146  	// If it encounters an error before the end of the directory,
   147  	// ReadDir returns the DirEntry list read until that point and a non-nil error.
   148  	//
   149  	// The caller owns the returned slice and may modify it. Subsequent calls
   150  	// to ReadDir must not modify a previously returned slice.
   151  	ReadDir(n int) ([]DirEntry, error)
   152  }
   153  
   154  // Generic file system errors.
   155  // Errors returned by file systems can be tested against these errors
   156  // using [errors.Is].
   157  var (
   158  	ErrInvalid    = errInvalid()    // "invalid argument"
   159  	ErrPermission = errPermission() // "permission denied"
   160  	ErrExist      = errExist()      // "file already exists"
   161  	ErrNotExist   = errNotExist()   // "file does not exist"
   162  )
   163  
   164  // ErrClosed is returned when operations are attempted on a file that
   165  // has already been closed, including when Close is called more than once.
   166  var ErrClosed = errClosed()
   167  
   168  func errInvalid() error    { return oserror.ErrInvalid }
   169  func errPermission() error { return oserror.ErrPermission }
   170  func errExist() error      { return oserror.ErrExist }
   171  func errNotExist() error   { return oserror.ErrNotExist }
   172  func errClosed() error     { return oserror.ErrClosed }
   173  
   174  // A FileInfo describes a file and is returned by [Stat].
   175  type FileInfo interface {
   176  	Name() string       // base name of the file
   177  	Size() int64        // length in bytes for regular files; system-dependent for others
   178  	Mode() FileMode     // file mode bits
   179  	ModTime() time.Time // modification time
   180  	IsDir() bool        // abbreviation for Mode().IsDir()
   181  	Sys() any           // underlying data source (can return nil)
   182  }
   183  
   184  // A FileMode represents a file's mode and permission bits.
   185  // The bits have the same definition on all systems, so that
   186  // information about files can be moved from one system
   187  // to another portably. Not all bits apply to all systems.
   188  // The only required bit is [ModeDir] for directories.
   189  type FileMode uint32
   190  
   191  // The defined file mode bits are the most significant bits of the [FileMode].
   192  // The nine least-significant bits are the standard Unix rwxrwxrwx permissions.
   193  // The values of these bits should be considered part of the public API and
   194  // may be used in wire protocols or disk representations: they must not be
   195  // changed, although new bits might be added.
   196  const (
   197  	// The single letters are the abbreviations
   198  	// used by the String method's formatting.
   199  	ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
   200  	ModeAppend                                     // a: append-only
   201  	ModeExclusive                                  // l: exclusive use
   202  	ModeTemporary                                  // T: temporary file; Plan 9 only
   203  	ModeSymlink                                    // L: symbolic link
   204  	ModeDevice                                     // D: device file
   205  	ModeNamedPipe                                  // p: named pipe (FIFO)
   206  	ModeSocket                                     // S: Unix domain socket
   207  	ModeSetuid                                     // u: setuid
   208  	ModeSetgid                                     // g: setgid
   209  	ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
   210  	ModeSticky                                     // t: sticky
   211  	ModeIrregular                                  // ?: non-regular file; nothing else is known about this file
   212  
   213  	// Mask for the type bits. For regular files, none will be set.
   214  	ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice | ModeCharDevice | ModeIrregular
   215  
   216  	ModePerm FileMode = 0777 // Unix permission bits
   217  )
   218  
   219  func (m FileMode) String() string {
   220  	const str = "dalTLDpSugct?"
   221  	var buf [32]byte // Mode is uint32.
   222  	w := 0
   223  	for i, c := range str {
   224  		if m&(1<<uint(32-1-i)) != 0 {
   225  			buf[w] = byte(c)
   226  			w++
   227  		}
   228  	}
   229  	if w == 0 {
   230  		buf[w] = '-'
   231  		w++
   232  	}
   233  	const rwx = "rwxrwxrwx"
   234  	for i, c := range rwx {
   235  		if m&(1<<uint(9-1-i)) != 0 {
   236  			buf[w] = byte(c)
   237  		} else {
   238  			buf[w] = '-'
   239  		}
   240  		w++
   241  	}
   242  	return string(buf[:w])
   243  }
   244  
   245  // IsDir reports whether m describes a directory.
   246  // That is, it tests for the [ModeDir] bit being set in m.
   247  func (m FileMode) IsDir() bool {
   248  	return m&ModeDir != 0
   249  }
   250  
   251  // IsRegular reports whether m describes a regular file.
   252  // That is, it tests that no mode type bits are set.
   253  func (m FileMode) IsRegular() bool {
   254  	return m&ModeType == 0
   255  }
   256  
   257  // Perm returns the Unix permission bits in m (m & [ModePerm]).
   258  func (m FileMode) Perm() FileMode {
   259  	return m & ModePerm
   260  }
   261  
   262  // Type returns type bits in m (m & [ModeType]).
   263  func (m FileMode) Type() FileMode {
   264  	return m & ModeType
   265  }
   266  
   267  // PathError records an error and the operation and file path that caused it.
   268  type PathError struct {
   269  	Op   string
   270  	Path string
   271  	Err  error
   272  }
   273  
   274  func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }
   275  
   276  func (e *PathError) Unwrap() error { return e.Err }
   277  
   278  // Timeout reports whether this error represents a timeout.
   279  func (e *PathError) Timeout() bool {
   280  	t, ok := e.Err.(interface{ Timeout() bool })
   281  	return ok && t.Timeout()
   282  }
   283  

View as plain text