file.go 22 KB

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