fs.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package misc
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. )
  7. func isDirExists(dirPath string) bool {
  8. if _, err := os.ReadDir(dirPath); err != nil {
  9. return false
  10. }
  11. return true
  12. }
  13. func isDirNotEmpty(dirPath string) bool {
  14. if entries, err := os.ReadDir(dirPath); err != nil {
  15. return false
  16. } else {
  17. return len(entries) > 0
  18. }
  19. }
  20. func isFile(filePath string) bool {
  21. if stat, err := os.Stat(filePath); err != nil {
  22. return false
  23. } else {
  24. return !stat.IsDir()
  25. }
  26. }
  27. // TestDir tests if directory is exists and not empty
  28. func TestDir(dirPath string) error {
  29. switch {
  30. case !isDirExists(dirPath):
  31. return fmt.Errorf("directory %q is not exists and cannot be used", dirPath)
  32. case !isDirNotEmpty(dirPath):
  33. return fmt.Errorf("directory %q is empty and cannot be used", dirPath)
  34. default:
  35. return nil
  36. }
  37. }
  38. // TestFile test if file is exists
  39. func TestFile(filePath string) error {
  40. if err := TestDir(filepath.Dir(filePath)); err != nil {
  41. return err
  42. }
  43. if !isFile(filePath) {
  44. return fmt.Errorf("%q not a file or not exists", filePath)
  45. }
  46. return nil
  47. }