gfile.go 12 KB

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