file_util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package util
  2. import (
  3. "errors"
  4. "os"
  5. "os/user"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/chrislusf/seaweedfs/weed/glog"
  10. )
  11. func TestFolderWritable(folder string) (err error) {
  12. fileInfo, err := os.Stat(folder)
  13. if err != nil {
  14. return err
  15. }
  16. if !fileInfo.IsDir() {
  17. return errors.New("Not a valid folder!")
  18. }
  19. perm := fileInfo.Mode().Perm()
  20. glog.V(0).Infoln("Folder", folder, "Permission:", perm)
  21. if 0200&perm != 0 {
  22. return nil
  23. }
  24. return errors.New("Not writable!")
  25. }
  26. func GetFileSize(file *os.File) (size int64, err error) {
  27. var fi os.FileInfo
  28. if fi, err = file.Stat(); err == nil {
  29. size = fi.Size()
  30. }
  31. return
  32. }
  33. func FileExists(filename string) bool {
  34. _, err := os.Stat(filename)
  35. if os.IsNotExist(err) {
  36. return false
  37. }
  38. return true
  39. }
  40. func CheckFile(filename string) (exists, canRead, canWrite bool, modTime time.Time, fileSize int64) {
  41. exists = true
  42. fi, err := os.Stat(filename)
  43. if os.IsNotExist(err) {
  44. exists = false
  45. return
  46. }
  47. if err != nil {
  48. glog.Errorf("check %s: %v", filename, err)
  49. return
  50. }
  51. if fi.Mode()&0400 != 0 {
  52. canRead = true
  53. }
  54. if fi.Mode()&0200 != 0 {
  55. canWrite = true
  56. }
  57. modTime = fi.ModTime()
  58. fileSize = fi.Size()
  59. return
  60. }
  61. func ResolvePath(path string) string {
  62. if !strings.Contains(path, "~") {
  63. return path
  64. }
  65. usr, _ := user.Current()
  66. dir := usr.HomeDir
  67. if path == "~" {
  68. // In case of "~", which won't be caught by the "else if"
  69. path = dir
  70. } else if strings.HasPrefix(path, "~/") {
  71. // Use strings.HasPrefix so we don't match paths like
  72. // "/something/~/something/"
  73. path = filepath.Join(dir, path[2:])
  74. }
  75. return path
  76. }
  77. func FileNameBase(filename string) string {
  78. lastDotIndex := strings.LastIndex(filename, ".")
  79. if lastDotIndex < 0 {
  80. return filename
  81. }
  82. return filename[:lastDotIndex]
  83. }
  84. // Copied from os.WriteFile(), adding file sync.
  85. // see https://github.com/golang/go/issues/20599
  86. func WriteFile(name string, data []byte, perm os.FileMode) error {
  87. f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
  88. if err != nil {
  89. return err
  90. }
  91. _, err = f.Write(data)
  92. if err1 := f.Sync(); err1 != nil && err == nil {
  93. err = err1
  94. }
  95. if err1 := f.Close(); err1 != nil && err == nil {
  96. err = err1
  97. }
  98. return err
  99. }