github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/os/file.go (about)

     1  // Copyright 2009 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 os provides a platform-independent interface to operating system
     6  // functionality. The design is Unix-like, although the error handling is
     7  // Go-like; failing calls return values of type error rather than error numbers.
     8  // Often, more information is available within the error. For example,
     9  // if a call that takes a file name fails, such as Open or Stat, the error
    10  // will include the failing file name when printed and will be of type
    11  // *PathError, which may be unpacked for more information.
    12  //
    13  // The os interface is intended to be uniform across all operating systems.
    14  // Features not generally available appear in the system-specific package syscall.
    15  //
    16  // Here is a simple example, opening a file and reading some of it.
    17  //
    18  //	file, err := os.Open("file.go") // For read access.
    19  //	if err != nil {
    20  //		log.Fatal(err)
    21  //	}
    22  //
    23  // If the open fails, the error string will be self-explanatory, like
    24  //
    25  //	open file.go: no such file or directory
    26  //
    27  // The file's data can then be read into a slice of bytes. Read and
    28  // Write take their byte counts from the length of the argument slice.
    29  //
    30  //	data := make([]byte, 100)
    31  //	count, err := file.Read(data)
    32  //	if err != nil {
    33  //		log.Fatal(err)
    34  //	}
    35  //	fmt.Printf("read %d bytes: %q\n", count, data[:count])
    36  //
    37  // Note: The maximum number of concurrent operations on a File may be limited by
    38  // the OS or the system. The number should be high, but exceeding it may degrade
    39  // performance or cause other issues.
    40  package os
    41  
    42  import (
    43  	"errors"
    44  	"internal/poll"
    45  	"internal/testlog"
    46  	"io"
    47  	"io/fs"
    48  	"runtime"
    49  	"syscall"
    50  	"time"
    51  	"unsafe"
    52  )
    53  
    54  // Name returns the name of the file as presented to Open.
    55  func (f *File) Name() string { return f.name }
    56  
    57  // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
    58  // standard output, and standard error file descriptors.
    59  //
    60  // Note that the Go runtime writes to standard error for panics and crashes;
    61  // closing Stderr may cause those messages to go elsewhere, perhaps
    62  // to a file opened later.
    63  var (
    64  	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    65  	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    66  	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    67  )
    68  
    69  // Flags to OpenFile wrapping those of the underlying system. Not all
    70  // flags may be implemented on a given system.
    71  const (
    72  	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    73  	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    74  	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    75  	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    76  	// The remaining values may be or'ed in to control behavior.
    77  	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    78  	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    79  	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    80  	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    81  	O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
    82  )
    83  
    84  // Seek whence values.
    85  //
    86  // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.
    87  const (
    88  	SEEK_SET int = 0 // seek relative to the origin of the file
    89  	SEEK_CUR int = 1 // seek relative to the current offset
    90  	SEEK_END int = 2 // seek relative to the end
    91  )
    92  
    93  // LinkError records an error during a link or symlink or rename
    94  // system call and the paths that caused it.
    95  type LinkError struct {
    96  	Op  string
    97  	Old string
    98  	New string
    99  	Err error
   100  }
   101  
   102  func (e *LinkError) Error() string {
   103  	return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
   104  }
   105  
   106  func (e *LinkError) Unwrap() error {
   107  	return e.Err
   108  }
   109  
   110  // Read reads up to len(b) bytes from the File and stores them in b.
   111  // It returns the number of bytes read and any error encountered.
   112  // At end of file, Read returns 0, io.EOF.
   113  func (f *File) Read(b []byte) (n int, err error) {
   114  	if err := f.checkValid("read"); err != nil {
   115  		return 0, err
   116  	}
   117  	n, e := f.read(b)
   118  	return n, f.wrapErr("read", e)
   119  }
   120  
   121  // ReadAt reads len(b) bytes from the File starting at byte offset off.
   122  // It returns the number of bytes read and the error, if any.
   123  // ReadAt always returns a non-nil error when n < len(b).
   124  // At end of file, that error is io.EOF.
   125  func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
   126  	if err := f.checkValid("read"); err != nil {
   127  		return 0, err
   128  	}
   129  
   130  	if off < 0 {
   131  		return 0, &PathError{Op: "readat", Path: f.name, Err: errors.New("negative offset")}
   132  	}
   133  
   134  	for len(b) > 0 {
   135  		m, e := f.pread(b, off)
   136  		if e != nil {
   137  			err = f.wrapErr("read", e)
   138  			break
   139  		}
   140  		n += m
   141  		b = b[m:]
   142  		off += int64(m)
   143  	}
   144  	return
   145  }
   146  
   147  // ReadFrom implements io.ReaderFrom.
   148  func (f *File) ReadFrom(r io.Reader) (n int64, err error) {
   149  	if err := f.checkValid("write"); err != nil {
   150  		return 0, err
   151  	}
   152  	n, handled, e := f.readFrom(r)
   153  	if !handled {
   154  		return genericReadFrom(f, r) // without wrapping
   155  	}
   156  	return n, f.wrapErr("write", e)
   157  }
   158  
   159  func genericReadFrom(f *File, r io.Reader) (int64, error) {
   160  	return io.Copy(onlyWriter{f}, r)
   161  }
   162  
   163  type onlyWriter struct {
   164  	io.Writer
   165  }
   166  
   167  // Write writes len(b) bytes from b to the File.
   168  // It returns the number of bytes written and an error, if any.
   169  // Write returns a non-nil error when n != len(b).
   170  func (f *File) Write(b []byte) (n int, err error) {
   171  	if err := f.checkValid("write"); err != nil {
   172  		return 0, err
   173  	}
   174  	n, e := f.write(b)
   175  	if n < 0 {
   176  		n = 0
   177  	}
   178  	if n != len(b) {
   179  		err = io.ErrShortWrite
   180  	}
   181  
   182  	epipecheck(f, e)
   183  
   184  	if e != nil {
   185  		err = f.wrapErr("write", e)
   186  	}
   187  
   188  	return n, err
   189  }
   190  
   191  var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND")
   192  
   193  // WriteAt writes len(b) bytes to the File starting at byte offset off.
   194  // It returns the number of bytes written and an error, if any.
   195  // WriteAt returns a non-nil error when n != len(b).
   196  //
   197  // If file was opened with the O_APPEND flag, WriteAt returns an error.
   198  func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
   199  	if err := f.checkValid("write"); err != nil {
   200  		return 0, err
   201  	}
   202  	if f.appendMode {
   203  		return 0, errWriteAtInAppendMode
   204  	}
   205  
   206  	if off < 0 {
   207  		return 0, &PathError{Op: "writeat", Path: f.name, Err: errors.New("negative offset")}
   208  	}
   209  
   210  	for len(b) > 0 {
   211  		m, e := f.pwrite(b, off)
   212  		if e != nil {
   213  			err = f.wrapErr("write", e)
   214  			break
   215  		}
   216  		n += m
   217  		b = b[m:]
   218  		off += int64(m)
   219  	}
   220  	return
   221  }
   222  
   223  // Seek sets the offset for the next Read or Write on file to offset, interpreted
   224  // according to whence: 0 means relative to the origin of the file, 1 means
   225  // relative to the current offset, and 2 means relative to the end.
   226  // It returns the new offset and an error, if any.
   227  // The behavior of Seek on a file opened with O_APPEND is not specified.
   228  //
   229  // If f is a directory, the behavior of Seek varies by operating
   230  // system; you can seek to the beginning of the directory on Unix-like
   231  // operating systems, but not on Windows.
   232  func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
   233  	if err := f.checkValid("seek"); err != nil {
   234  		return 0, err
   235  	}
   236  	r, e := f.seek(offset, whence)
   237  	if e == nil && f.dirinfo != nil && r != 0 {
   238  		e = syscall.EISDIR
   239  	}
   240  	if e != nil {
   241  		return 0, f.wrapErr("seek", e)
   242  	}
   243  	return r, nil
   244  }
   245  
   246  // WriteString is like Write, but writes the contents of string s rather than
   247  // a slice of bytes.
   248  func (f *File) WriteString(s string) (n int, err error) {
   249  	b := unsafe.Slice(unsafe.StringData(s), len(s))
   250  	return f.Write(b)
   251  }
   252  
   253  // Mkdir creates a new directory with the specified name and permission
   254  // bits (before umask).
   255  // If there is an error, it will be of type *PathError.
   256  func Mkdir(name string, perm FileMode) error {
   257  	if runtime.GOOS == "windows" && isWindowsNulName(name) {
   258  		return &PathError{Op: "mkdir", Path: name, Err: syscall.ENOTDIR}
   259  	}
   260  	longName := fixLongPath(name)
   261  	e := ignoringEINTR(func() error {
   262  		return syscall.Mkdir(longName, syscallMode(perm))
   263  	})
   264  
   265  	if e != nil {
   266  		return &PathError{Op: "mkdir", Path: name, Err: e}
   267  	}
   268  
   269  	// mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
   270  	if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
   271  		e = setStickyBit(name)
   272  
   273  		if e != nil {
   274  			Remove(name)
   275  			return e
   276  		}
   277  	}
   278  
   279  	return nil
   280  }
   281  
   282  // setStickyBit adds ModeSticky to the permission bits of path, non atomic.
   283  func setStickyBit(name string) error {
   284  	fi, err := Stat(name)
   285  	if err != nil {
   286  		return err
   287  	}
   288  	return Chmod(name, fi.Mode()|ModeSticky)
   289  }
   290  
   291  // Chdir changes the current working directory to the named directory.
   292  // If there is an error, it will be of type *PathError.
   293  func Chdir(dir string) error {
   294  	if e := syscall.Chdir(dir); e != nil {
   295  		testlog.Open(dir) // observe likely non-existent directory
   296  		return &PathError{Op: "chdir", Path: dir, Err: e}
   297  	}
   298  	if log := testlog.Logger(); log != nil {
   299  		wd, err := Getwd()
   300  		if err == nil {
   301  			log.Chdir(wd)
   302  		}
   303  	}
   304  	return nil
   305  }
   306  
   307  // Open opens the named file for reading. If successful, methods on
   308  // the returned file can be used for reading; the associated file
   309  // descriptor has mode O_RDONLY.
   310  // If there is an error, it will be of type *PathError.
   311  func Open(name string) (*File, error) {
   312  	return OpenFile(name, O_RDONLY, 0)
   313  }
   314  
   315  // Create creates or truncates the named file. If the file already exists,
   316  // it is truncated. If the file does not exist, it is created with mode 0666
   317  // (before umask). If successful, methods on the returned File can
   318  // be used for I/O; the associated file descriptor has mode O_RDWR.
   319  // If there is an error, it will be of type *PathError.
   320  func Create(name string) (*File, error) {
   321  	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
   322  }
   323  
   324  // OpenFile is the generalized open call; most users will use Open
   325  // or Create instead. It opens the named file with specified flag
   326  // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
   327  // is passed, it is created with mode perm (before umask). If successful,
   328  // methods on the returned File can be used for I/O.
   329  // If there is an error, it will be of type *PathError.
   330  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   331  	testlog.Open(name)
   332  	f, err := openFileNolog(name, flag, perm)
   333  	if err != nil {
   334  		return nil, err
   335  	}
   336  	f.appendMode = flag&O_APPEND != 0
   337  
   338  	return f, nil
   339  }
   340  
   341  // lstat is overridden in tests.
   342  var lstat = Lstat
   343  
   344  // Rename renames (moves) oldpath to newpath.
   345  // If newpath already exists and is not a directory, Rename replaces it.
   346  // OS-specific restrictions may apply when oldpath and newpath are in different directories.
   347  // If there is an error, it will be of type *LinkError.
   348  func Rename(oldpath, newpath string) error {
   349  	return rename(oldpath, newpath)
   350  }
   351  
   352  // Many functions in package syscall return a count of -1 instead of 0.
   353  // Using fixCount(call()) instead of call() corrects the count.
   354  func fixCount(n int, err error) (int, error) {
   355  	if n < 0 {
   356  		n = 0
   357  	}
   358  	return n, err
   359  }
   360  
   361  // wrapErr wraps an error that occurred during an operation on an open file.
   362  // It passes io.EOF through unchanged, otherwise converts
   363  // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
   364  func (f *File) wrapErr(op string, err error) error {
   365  	if err == nil || err == io.EOF {
   366  		return err
   367  	}
   368  	if err == poll.ErrFileClosing {
   369  		err = ErrClosed
   370  	}
   371  	return &PathError{Op: op, Path: f.name, Err: err}
   372  }
   373  
   374  // TempDir returns the default directory to use for temporary files.
   375  //
   376  // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
   377  // On Windows, it uses GetTempPath, returning the first non-empty
   378  // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
   379  // On Plan 9, it returns /tmp.
   380  //
   381  // The directory is neither guaranteed to exist nor have accessible
   382  // permissions.
   383  func TempDir() string {
   384  	return tempDir()
   385  }
   386  
   387  // UserCacheDir returns the default root directory to use for user-specific
   388  // cached data. Users should create their own application-specific subdirectory
   389  // within this one and use that.
   390  //
   391  // On Unix systems, it returns $XDG_CACHE_HOME as specified by
   392  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   393  // non-empty, else $HOME/.cache.
   394  // On Darwin, it returns $HOME/Library/Caches.
   395  // On Windows, it returns %LocalAppData%.
   396  // On Plan 9, it returns $home/lib/cache.
   397  //
   398  // If the location cannot be determined (for example, $HOME is not defined),
   399  // then it will return an error.
   400  func UserCacheDir() (string, error) {
   401  	var dir string
   402  
   403  	switch runtime.GOOS {
   404  	case "windows":
   405  		dir = Getenv("LocalAppData")
   406  		if dir == "" {
   407  			return "", errors.New("%LocalAppData% is not defined")
   408  		}
   409  
   410  	case "darwin", "ios":
   411  		dir = Getenv("HOME")
   412  		if dir == "" {
   413  			return "", errors.New("$HOME is not defined")
   414  		}
   415  		dir += "/Library/Caches"
   416  
   417  	case "plan9":
   418  		dir = Getenv("home")
   419  		if dir == "" {
   420  			return "", errors.New("$home is not defined")
   421  		}
   422  		dir += "/lib/cache"
   423  
   424  	default: // Unix
   425  		dir = Getenv("XDG_CACHE_HOME")
   426  		if dir == "" {
   427  			dir = Getenv("HOME")
   428  			if dir == "" {
   429  				return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined")
   430  			}
   431  			dir += "/.cache"
   432  		}
   433  	}
   434  
   435  	return dir, nil
   436  }
   437  
   438  // UserConfigDir returns the default root directory to use for user-specific
   439  // configuration data. Users should create their own application-specific
   440  // subdirectory within this one and use that.
   441  //
   442  // On Unix systems, it returns $XDG_CONFIG_HOME as specified by
   443  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   444  // non-empty, else $HOME/.config.
   445  // On Darwin, it returns $HOME/Library/Application Support.
   446  // On Windows, it returns %AppData%.
   447  // On Plan 9, it returns $home/lib.
   448  //
   449  // If the location cannot be determined (for example, $HOME is not defined),
   450  // then it will return an error.
   451  func UserConfigDir() (string, error) {
   452  	var dir string
   453  
   454  	switch runtime.GOOS {
   455  	case "windows":
   456  		dir = Getenv("AppData")
   457  		if dir == "" {
   458  			return "", errors.New("%AppData% is not defined")
   459  		}
   460  
   461  	case "darwin", "ios":
   462  		dir = Getenv("HOME")
   463  		if dir == "" {
   464  			return "", errors.New("$HOME is not defined")
   465  		}
   466  		dir += "/Library/Application Support"
   467  
   468  	case "plan9":
   469  		dir = Getenv("home")
   470  		if dir == "" {
   471  			return "", errors.New("$home is not defined")
   472  		}
   473  		dir += "/lib"
   474  
   475  	default: // Unix
   476  		dir = Getenv("XDG_CONFIG_HOME")
   477  		if dir == "" {
   478  			dir = Getenv("HOME")
   479  			if dir == "" {
   480  				return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
   481  			}
   482  			dir += "/.config"
   483  		}
   484  	}
   485  
   486  	return dir, nil
   487  }
   488  
   489  // UserHomeDir returns the current user's home directory.
   490  //
   491  // On Unix, including macOS, it returns the $HOME environment variable.
   492  // On Windows, it returns %USERPROFILE%.
   493  // On Plan 9, it returns the $home environment variable.
   494  func UserHomeDir() (string, error) {
   495  	env, enverr := "HOME", "$HOME"
   496  	switch runtime.GOOS {
   497  	case "windows":
   498  		env, enverr = "USERPROFILE", "%userprofile%"
   499  	case "plan9":
   500  		env, enverr = "home", "$home"
   501  	}
   502  	if v := Getenv(env); v != "" {
   503  		return v, nil
   504  	}
   505  	// On some geese the home directory is not always defined.
   506  	switch runtime.GOOS {
   507  	case "android":
   508  		return "/sdcard", nil
   509  	case "ios":
   510  		return "/", nil
   511  	}
   512  	return "", errors.New(enverr + " is not defined")
   513  }
   514  
   515  // Chmod changes the mode of the named file to mode.
   516  // If the file is a symbolic link, it changes the mode of the link's target.
   517  // If there is an error, it will be of type *PathError.
   518  //
   519  // A different subset of the mode bits are used, depending on the
   520  // operating system.
   521  //
   522  // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
   523  // ModeSticky are used.
   524  //
   525  // On Windows, only the 0200 bit (owner writable) of mode is used; it
   526  // controls whether the file's read-only attribute is set or cleared.
   527  // The other bits are currently unused. For compatibility with Go 1.12
   528  // and earlier, use a non-zero mode. Use mode 0400 for a read-only
   529  // file and 0600 for a readable+writable file.
   530  //
   531  // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
   532  // and ModeTemporary are used.
   533  func Chmod(name string, mode FileMode) error { return chmod(name, mode) }
   534  
   535  // Chmod changes the mode of the file to mode.
   536  // If there is an error, it will be of type *PathError.
   537  func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) }
   538  
   539  // SetDeadline sets the read and write deadlines for a File.
   540  // It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
   541  //
   542  // Only some kinds of files support setting a deadline. Calls to SetDeadline
   543  // for files that do not support deadlines will return ErrNoDeadline.
   544  // On most systems ordinary files do not support deadlines, but pipes do.
   545  //
   546  // A deadline is an absolute time after which I/O operations fail with an
   547  // error instead of blocking. The deadline applies to all future and pending
   548  // I/O, not just the immediately following call to Read or Write.
   549  // After a deadline has been exceeded, the connection can be refreshed
   550  // by setting a deadline in the future.
   551  //
   552  // If the deadline is exceeded a call to Read or Write or to other I/O
   553  // methods will return an error that wraps ErrDeadlineExceeded.
   554  // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
   555  // That error implements the Timeout method, and calling the Timeout
   556  // method will return true, but there are other possible errors for which
   557  // the Timeout will return true even if the deadline has not been exceeded.
   558  //
   559  // An idle timeout can be implemented by repeatedly extending
   560  // the deadline after successful Read or Write calls.
   561  //
   562  // A zero value for t means I/O operations will not time out.
   563  func (f *File) SetDeadline(t time.Time) error {
   564  	return f.setDeadline(t)
   565  }
   566  
   567  // SetReadDeadline sets the deadline for future Read calls and any
   568  // currently-blocked Read call.
   569  // A zero value for t means Read will not time out.
   570  // Not all files support setting deadlines; see SetDeadline.
   571  func (f *File) SetReadDeadline(t time.Time) error {
   572  	return f.setReadDeadline(t)
   573  }
   574  
   575  // SetWriteDeadline sets the deadline for any future Write calls and any
   576  // currently-blocked Write call.
   577  // Even if Write times out, it may return n > 0, indicating that
   578  // some of the data was successfully written.
   579  // A zero value for t means Write will not time out.
   580  // Not all files support setting deadlines; see SetDeadline.
   581  func (f *File) SetWriteDeadline(t time.Time) error {
   582  	return f.setWriteDeadline(t)
   583  }
   584  
   585  // SyscallConn returns a raw file.
   586  // This implements the syscall.Conn interface.
   587  func (f *File) SyscallConn() (syscall.RawConn, error) {
   588  	if err := f.checkValid("SyscallConn"); err != nil {
   589  		return nil, err
   590  	}
   591  	return newRawConn(f)
   592  }
   593  
   594  // isWindowsNulName reports whether name is os.DevNull ('NUL') on Windows.
   595  // True is returned if name is 'NUL' whatever the case.
   596  func isWindowsNulName(name string) bool {
   597  	if len(name) != 3 {
   598  		return false
   599  	}
   600  	if name[0] != 'n' && name[0] != 'N' {
   601  		return false
   602  	}
   603  	if name[1] != 'u' && name[1] != 'U' {
   604  		return false
   605  	}
   606  	if name[2] != 'l' && name[2] != 'L' {
   607  		return false
   608  	}
   609  	return true
   610  }
   611  
   612  // DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.
   613  //
   614  // Note that DirFS("/prefix") only guarantees that the Open calls it makes to the
   615  // operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the
   616  // same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside
   617  // the /prefix tree, then using DirFS does not stop the access any more than using
   618  // os.Open does. Additionally, the root of the fs.FS returned for a relative path,
   619  // DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not
   620  // a general substitute for a chroot-style security mechanism when the directory tree
   621  // contains arbitrary content.
   622  //
   623  // The result implements fs.StatFS.
   624  func DirFS(dir string) fs.FS {
   625  	return dirFS(dir)
   626  }
   627  
   628  func containsAny(s, chars string) bool {
   629  	for i := 0; i < len(s); i++ {
   630  		for j := 0; j < len(chars); j++ {
   631  			if s[i] == chars[j] {
   632  				return true
   633  			}
   634  		}
   635  	}
   636  	return false
   637  }
   638  
   639  type dirFS string
   640  
   641  func (dir dirFS) Open(name string) (fs.File, error) {
   642  	if !fs.ValidPath(name) || runtime.GOOS == "windows" && containsAny(name, `\:`) {
   643  		return nil, &PathError{Op: "open", Path: name, Err: ErrInvalid}
   644  	}
   645  	f, err := Open(dir.join(name))
   646  	if err != nil {
   647  		if runtime.GOOS == "windows" {
   648  			// Undo the backslash conversion done by dir.join.
   649  			perr := err.(*PathError)
   650  			if containsAny(perr.Path, `\`) {
   651  				perr.Path = string(dir) + "/" + name
   652  			}
   653  		}
   654  		return nil, err // nil fs.File
   655  	}
   656  	return f, nil
   657  }
   658  
   659  func (dir dirFS) Stat(name string) (fs.FileInfo, error) {
   660  	if !fs.ValidPath(name) || runtime.GOOS == "windows" && containsAny(name, `\:`) {
   661  		return nil, &PathError{Op: "stat", Path: name, Err: ErrInvalid}
   662  	}
   663  	f, err := Stat(dir.join(name))
   664  	if err != nil {
   665  		return nil, err
   666  	}
   667  	return f, nil
   668  }
   669  
   670  // join returns the path for name in dir. We can't always use "/"
   671  // because that fails on Windows for UNC paths.
   672  func (dir dirFS) join(name string) string {
   673  	if runtime.GOOS == "windows" && containsAny(name, "/") {
   674  		buf := []byte(name)
   675  		for i, b := range buf {
   676  			if b == '/' {
   677  				buf[i] = '\\'
   678  			}
   679  		}
   680  		name = string(buf)
   681  	}
   682  	return string(dir) + string(PathSeparator) + name
   683  }
   684  
   685  // ReadFile reads the named file and returns the contents.
   686  // A successful call returns err == nil, not err == EOF.
   687  // Because ReadFile reads the whole file, it does not treat an EOF from Read
   688  // as an error to be reported.
   689  func ReadFile(name string) ([]byte, error) {
   690  	f, err := Open(name)
   691  	if err != nil {
   692  		return nil, err
   693  	}
   694  	defer f.Close()
   695  
   696  	var size int
   697  	if info, err := f.Stat(); err == nil {
   698  		size64 := info.Size()
   699  		if int64(int(size64)) == size64 {
   700  			size = int(size64)
   701  		}
   702  	}
   703  	size++ // one byte for final read at EOF
   704  
   705  	// If a file claims a small size, read at least 512 bytes.
   706  	// In particular, files in Linux's /proc claim size 0 but
   707  	// then do not work right if read in small pieces,
   708  	// so an initial read of 1 byte would not work correctly.
   709  	if size < 512 {
   710  		size = 512
   711  	}
   712  
   713  	data := make([]byte, 0, size)
   714  	for {
   715  		if len(data) >= cap(data) {
   716  			d := append(data[:cap(data)], 0)
   717  			data = d[:len(data)]
   718  		}
   719  		n, err := f.Read(data[len(data):cap(data)])
   720  		data = data[:len(data)+n]
   721  		if err != nil {
   722  			if err == io.EOF {
   723  				err = nil
   724  			}
   725  			return data, err
   726  		}
   727  	}
   728  }
   729  
   730  // WriteFile writes data to the named file, creating it if necessary.
   731  // If the file does not exist, WriteFile creates it with permissions perm (before umask);
   732  // otherwise WriteFile truncates it before writing, without changing permissions.
   733  func WriteFile(name string, data []byte, perm FileMode) error {
   734  	f, err := OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, perm)
   735  	if err != nil {
   736  		return err
   737  	}
   738  	_, err = f.Write(data)
   739  	if err1 := f.Close(); err1 != nil && err == nil {
   740  		err = err1
   741  	}
   742  	return err
   743  }