gfile.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gfile provides easy-to-use operations for file system.
  7. package gfile
  8. import (
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/gogf/gf/v2/container/gtype"
  16. "github.com/gogf/gf/v2/errors/gerror"
  17. "github.com/gogf/gf/v2/text/gstr"
  18. "github.com/gogf/gf/v2/util/gconv"
  19. )
  20. const (
  21. // Separator for file system.
  22. // It here defines the separator as variable
  23. // to allow it modified by developer if necessary.
  24. Separator = string(filepath.Separator)
  25. // DefaultPermOpen is the default perm for file opening.
  26. DefaultPermOpen = os.FileMode(0666)
  27. // DefaultPermCopy is the default perm for file/folder copy.
  28. DefaultPermCopy = os.FileMode(0777)
  29. )
  30. var (
  31. // The absolute file path for main package.
  32. // It can be only checked and set once.
  33. mainPkgPath = gtype.NewString()
  34. // selfPath is the current running binary path.
  35. // As it is most commonly used, it is so defined as an internal package variable.
  36. selfPath = ""
  37. // Temporary directory of system.
  38. tempDir = "/tmp"
  39. )
  40. func init() {
  41. // Initialize internal package variable: tempDir.
  42. if runtime.GOOS == "windows" || Separator != "/" || !Exists(tempDir) {
  43. tempDir = os.TempDir()
  44. }
  45. // Initialize internal package variable: selfPath.
  46. selfPath, _ = exec.LookPath(os.Args[0])
  47. if selfPath != "" {
  48. selfPath, _ = filepath.Abs(selfPath)
  49. }
  50. if selfPath == "" {
  51. selfPath, _ = filepath.Abs(os.Args[0])
  52. }
  53. }
  54. // Mkdir creates directories recursively with given `path`.
  55. // The parameter `path` is suggested to be an absolute path instead of relative one.
  56. func Mkdir(path string) (err error) {
  57. if err = os.MkdirAll(path, os.ModePerm); err != nil {
  58. err = gerror.Wrapf(err, `os.MkdirAll failed for path "%s" with perm "%d"`, path, os.ModePerm)
  59. return err
  60. }
  61. return nil
  62. }
  63. // Create creates file with given `path` recursively.
  64. // The parameter `path` is suggested to be absolute path.
  65. func Create(path string) (*os.File, error) {
  66. dir := Dir(path)
  67. if !Exists(dir) {
  68. if err := Mkdir(dir); err != nil {
  69. return nil, err
  70. }
  71. }
  72. file, err := os.Create(path)
  73. if err != nil {
  74. err = gerror.Wrapf(err, `os.Create failed for name "%s"`, path)
  75. }
  76. return file, err
  77. }
  78. // Open opens file/directory READONLY.
  79. func Open(path string) (*os.File, error) {
  80. file, err := os.Open(path)
  81. if err != nil {
  82. err = gerror.Wrapf(err, `os.Open failed for name "%s"`, path)
  83. }
  84. return file, err
  85. }
  86. // OpenFile opens file/directory with custom `flag` and `perm`.
  87. // The parameter `flag` is like: O_RDONLY, O_RDWR, O_RDWR|O_CREATE|O_TRUNC, etc.
  88. func OpenFile(path string, flag int, perm os.FileMode) (*os.File, error) {
  89. file, err := os.OpenFile(path, flag, perm)
  90. if err != nil {
  91. err = gerror.Wrapf(err, `os.OpenFile failed with name "%s", flag "%d", perm "%d"`, path, flag, perm)
  92. }
  93. return file, err
  94. }
  95. // OpenWithFlag opens file/directory with default perm and custom `flag`.
  96. // The default `perm` is 0666.
  97. // The parameter `flag` is like: O_RDONLY, O_RDWR, O_RDWR|O_CREATE|O_TRUNC, etc.
  98. func OpenWithFlag(path string, flag int) (*os.File, error) {
  99. file, err := OpenFile(path, flag, DefaultPermOpen)
  100. if err != nil {
  101. return nil, err
  102. }
  103. return file, nil
  104. }
  105. // OpenWithFlagPerm opens file/directory with custom `flag` and `perm`.
  106. // The parameter `flag` is like: O_RDONLY, O_RDWR, O_RDWR|O_CREATE|O_TRUNC, etc.
  107. // The parameter `perm` is like: 0600, 0666, 0777, etc.
  108. func OpenWithFlagPerm(path string, flag int, perm os.FileMode) (*os.File, error) {
  109. file, err := OpenFile(path, flag, perm)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return file, nil
  114. }
  115. // Join joins string array paths with file separator of current system.
  116. func Join(paths ...string) string {
  117. var s string
  118. for _, path := range paths {
  119. if s != "" {
  120. s += Separator
  121. }
  122. s += gstr.TrimRight(path, Separator)
  123. }
  124. return s
  125. }
  126. // Exists checks whether given `path` exist.
  127. func Exists(path string) bool {
  128. if stat, err := os.Stat(path); stat != nil && !os.IsNotExist(err) {
  129. return true
  130. }
  131. return false
  132. }
  133. // IsDir checks whether given `path` a directory.
  134. // Note that it returns false if the `path` does not exist.
  135. func IsDir(path string) bool {
  136. s, err := os.Stat(path)
  137. if err != nil {
  138. return false
  139. }
  140. return s.IsDir()
  141. }
  142. // Pwd returns absolute path of current working directory.
  143. // Note that it returns an empty string if retrieving current
  144. // working directory failed.
  145. func Pwd() string {
  146. path, err := os.Getwd()
  147. if err != nil {
  148. return ""
  149. }
  150. return path
  151. }
  152. // Chdir changes the current working directory to the named directory.
  153. // If there is an error, it will be of type *PathError.
  154. func Chdir(dir string) (err error) {
  155. err = os.Chdir(dir)
  156. if err != nil {
  157. err = gerror.Wrapf(err, `os.Chdir failed with dir "%s"`, dir)
  158. }
  159. return
  160. }
  161. // IsFile checks whether given `path` a file, which means it's not a directory.
  162. // Note that it returns false if the `path` does not exist.
  163. func IsFile(path string) bool {
  164. s, err := Stat(path)
  165. if err != nil {
  166. return false
  167. }
  168. return !s.IsDir()
  169. }
  170. // Stat returns a FileInfo describing the named file.
  171. // If there is an error, it will be of type *PathError.
  172. func Stat(path string) (os.FileInfo, error) {
  173. info, err := os.Stat(path)
  174. if err != nil {
  175. err = gerror.Wrapf(err, `os.Stat failed for file "%s"`, path)
  176. }
  177. return info, err
  178. }
  179. // Move renames (moves) `src` to `dst` path.
  180. // If `dst` already exists and is not a directory, it'll be replaced.
  181. func Move(src string, dst string) (err error) {
  182. err = os.Rename(src, dst)
  183. if err != nil {
  184. err = gerror.Wrapf(err, `os.Rename failed from "%s" to "%s"`, src, dst)
  185. }
  186. return
  187. }
  188. // Rename is alias of Move.
  189. // See Move.
  190. func Rename(src string, dst string) error {
  191. return Move(src, dst)
  192. }
  193. // DirNames returns sub-file names of given directory `path`.
  194. // Note that the returned names are NOT absolute paths.
  195. func DirNames(path string) ([]string, error) {
  196. f, err := Open(path)
  197. if err != nil {
  198. return nil, err
  199. }
  200. list, err := f.Readdirnames(-1)
  201. _ = f.Close()
  202. if err != nil {
  203. err = gerror.Wrapf(err, `Read dir files failed from path "%s"`, path)
  204. return nil, err
  205. }
  206. return list, nil
  207. }
  208. // Glob returns the names of all files matching pattern or nil
  209. // if there is no matching file. The syntax of patterns is the same
  210. // as in Match. The pattern may describe hierarchical names such as
  211. // /usr/*/bin/ed (assuming the Separator is '/').
  212. //
  213. // Glob ignores file system errors such as I/O errors reading directories.
  214. // The only possible returned error is ErrBadPattern, when pattern
  215. // is malformed.
  216. func Glob(pattern string, onlyNames ...bool) ([]string, error) {
  217. list, err := filepath.Glob(pattern)
  218. if err != nil {
  219. err = gerror.Wrapf(err, `filepath.Glob failed for pattern "%s"`, pattern)
  220. return nil, err
  221. }
  222. if len(onlyNames) > 0 && onlyNames[0] && len(list) > 0 {
  223. array := make([]string, len(list))
  224. for k, v := range list {
  225. array[k] = Basename(v)
  226. }
  227. return array, nil
  228. }
  229. return list, nil
  230. }
  231. // Remove deletes all file/directory with `path` parameter.
  232. // If parameter `path` is directory, it deletes it recursively.
  233. //
  234. // It does nothing if given `path` does not exist or is empty.
  235. func Remove(path string) (err error) {
  236. // It does nothing if `path` is empty.
  237. if path == "" {
  238. return nil
  239. }
  240. if err = os.RemoveAll(path); err != nil {
  241. err = gerror.Wrapf(err, `os.RemoveAll failed for path "%s"`, path)
  242. }
  243. return
  244. }
  245. // IsReadable checks whether given `path` is readable.
  246. func IsReadable(path string) bool {
  247. result := true
  248. file, err := os.OpenFile(path, os.O_RDONLY, DefaultPermOpen)
  249. if err != nil {
  250. result = false
  251. }
  252. file.Close()
  253. return result
  254. }
  255. // IsWritable checks whether given `path` is writable.
  256. //
  257. // TODO improve performance; use golang.org/x/sys to cross-plat-form
  258. func IsWritable(path string) bool {
  259. result := true
  260. if IsDir(path) {
  261. // If it's a directory, create a temporary file to test whether it's writable.
  262. tmpFile := strings.TrimRight(path, Separator) + Separator + gconv.String(time.Now().UnixNano())
  263. if f, err := Create(tmpFile); err != nil || !Exists(tmpFile) {
  264. result = false
  265. } else {
  266. _ = f.Close()
  267. _ = Remove(tmpFile)
  268. }
  269. } else {
  270. // If it's a file, check if it can open it.
  271. file, err := os.OpenFile(path, os.O_WRONLY, DefaultPermOpen)
  272. if err != nil {
  273. result = false
  274. }
  275. _ = file.Close()
  276. }
  277. return result
  278. }
  279. // Chmod is alias of os.Chmod.
  280. // See os.Chmod.
  281. func Chmod(path string, mode os.FileMode) (err error) {
  282. err = os.Chmod(path, mode)
  283. if err != nil {
  284. err = gerror.Wrapf(err, `os.Chmod failed with path "%s" and mode "%s"`, path, mode)
  285. }
  286. return
  287. }
  288. // Abs returns an absolute representation of path.
  289. // If the path is not absolute it will be joined with the current
  290. // working directory to turn it into an absolute path. The absolute
  291. // path name for a given file is not guaranteed to be unique.
  292. // Abs calls Clean on the result.
  293. func Abs(path string) string {
  294. p, _ := filepath.Abs(path)
  295. return p
  296. }
  297. // RealPath converts the given `path` to its absolute path
  298. // and checks if the file path exists.
  299. // If the file does not exist, return an empty string.
  300. func RealPath(path string) string {
  301. p, err := filepath.Abs(path)
  302. if err != nil {
  303. return ""
  304. }
  305. if !Exists(p) {
  306. return ""
  307. }
  308. return p
  309. }
  310. // SelfPath returns absolute file path of current running process(binary).
  311. func SelfPath() string {
  312. return selfPath
  313. }
  314. // SelfName returns file name of current running process(binary).
  315. func SelfName() string {
  316. return Basename(SelfPath())
  317. }
  318. // SelfDir returns absolute directory path of current running process(binary).
  319. func SelfDir() string {
  320. return filepath.Dir(SelfPath())
  321. }
  322. // Basename returns the last element of path, which contains file extension.
  323. // Trailing path separators are removed before extracting the last element.
  324. // If the path is empty, Base returns ".".
  325. // If the path consists entirely of separators, Basename returns a single separator.
  326. // Example:
  327. // /var/www/file.js -> file.js
  328. // file.js -> file.js
  329. func Basename(path string) string {
  330. return filepath.Base(path)
  331. }
  332. // Name returns the last element of path without file extension.
  333. // Example:
  334. // /var/www/file.js -> file
  335. // file.js -> file
  336. func Name(path string) string {
  337. base := filepath.Base(path)
  338. if i := strings.LastIndexByte(base, '.'); i != -1 {
  339. return base[:i]
  340. }
  341. return base
  342. }
  343. // Dir returns all but the last element of path, typically the path's directory.
  344. // After dropping the final element, Dir calls Clean on the path and trailing
  345. // slashes are removed.
  346. // If the `path` is empty, Dir returns ".".
  347. // If the `path` is ".", Dir treats the path as current working directory.
  348. // If the `path` consists entirely of separators, Dir returns a single separator.
  349. // The returned path does not end in a separator unless it is the root directory.
  350. func Dir(path string) string {
  351. if path == "." {
  352. return filepath.Dir(RealPath(path))
  353. }
  354. return filepath.Dir(path)
  355. }
  356. // IsEmpty checks whether the given `path` is empty.
  357. // If `path` is a folder, it checks if there's any file under it.
  358. // If `path` is a file, it checks if the file size is zero.
  359. //
  360. // Note that it returns true if `path` does not exist.
  361. func IsEmpty(path string) bool {
  362. stat, err := Stat(path)
  363. if err != nil {
  364. return true
  365. }
  366. if stat.IsDir() {
  367. file, err := os.Open(path)
  368. if err != nil {
  369. return true
  370. }
  371. defer file.Close()
  372. names, err := file.Readdirnames(-1)
  373. if err != nil {
  374. return true
  375. }
  376. return len(names) == 0
  377. } else {
  378. return stat.Size() == 0
  379. }
  380. }
  381. // Ext returns the file name extension used by path.
  382. // The extension is the suffix beginning at the final dot
  383. // in the final element of path; it is empty if there is
  384. // no dot.
  385. // Note: the result contains symbol '.'.
  386. // Eg:
  387. // main.go => .go
  388. // api.json => .json
  389. func Ext(path string) string {
  390. ext := filepath.Ext(path)
  391. if p := strings.IndexByte(ext, '?'); p != -1 {
  392. ext = ext[0:p]
  393. }
  394. return ext
  395. }
  396. // ExtName is like function Ext, which returns the file name extension used by path,
  397. // but the result does not contain symbol '.'.
  398. // Eg:
  399. // main.go => go
  400. // api.json => json
  401. func ExtName(path string) string {
  402. return strings.TrimLeft(Ext(path), ".")
  403. }
  404. // Temp retrieves and returns the temporary directory of current system.
  405. // It returns "/tmp" is current in *nix system, or else it returns os.TempDir().
  406. //
  407. // The optional parameter `names` specifies the sub-folders/sub-files,
  408. // which will be joined with current system separator and returned with the path.
  409. func Temp(names ...string) string {
  410. path := tempDir
  411. for _, name := range names {
  412. path += Separator + name
  413. }
  414. return path
  415. }