gfile.go 11 KB

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