util.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package memfile
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. )
  7. // SplitPaths splits the directory path into a slice of directory names.
  8. func SplitPaths(path string) []string {
  9. path = filepath.Clean(path)
  10. if path[len(path)-1] == filepath.Separator {
  11. path = path[:len(path)-1]
  12. }
  13. return strings.Split(path, string(filepath.Separator))
  14. }
  15. // Split splits the path into a slice of directory names and the file name.
  16. func Split(path string) ([]string, string) {
  17. path = filepath.Clean(path)
  18. pDir, pFile := filepath.Split(path)
  19. pDir = filepath.Dir(pDir)
  20. return strings.Split(pDir, string(filepath.Separator)), pFile
  21. }
  22. // CreateSubdirectory creates the necessary subdirectories within the provided MemoryDirectory.
  23. func CreateSubdirectory(d *MemoryDirectory, paths []string) *MemoryDirectory {
  24. currentDir := d
  25. for i := 0; i < len(paths); i++ {
  26. dirName := paths[i]
  27. if _, ok := currentDir.dirs[dirName]; !ok {
  28. currentDir.AddDirectory(NewMemoryDirectory(dirName))
  29. }
  30. currentDir = currentDir.dirs[dirName]
  31. }
  32. return currentDir
  33. }
  34. // FindSubdirectory searches through the provided path slice starting with the provided directory,
  35. // and returns the correct MemoryDirectory if it exists. If the directory does not exist, an error is
  36. // returned containing the path where the find failed.
  37. func FindSubdirectory(d *MemoryDirectory, paths []string) (*MemoryDirectory, error) {
  38. currentDir := d
  39. for i := 0; i < len(paths); i++ {
  40. dirName := paths[i]
  41. if _, ok := currentDir.dirs[dirName]; !ok {
  42. return nil, fmt.Errorf("directory %s not found", filepath.Join(paths[:i+1]...))
  43. }
  44. currentDir = currentDir.dirs[dirName]
  45. }
  46. return currentDir, nil
  47. }