file_util.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. }