path.go 1006 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package inout
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. )
  8. type Folder struct {
  9. Nume string
  10. Fisiere []File
  11. Subfoldere []Folder
  12. }
  13. type File struct {
  14. Nume string
  15. Path string
  16. }
  17. func SafeDir(path string) error {
  18. path = filepath.Clean(path)
  19. if strings.HasPrefix(path, "..") || filepath.IsAbs(path) {
  20. return fmt.Errorf("Invalid Path")
  21. }
  22. return nil
  23. }
  24. func GetFolderStructure(path string, f *Folder) error {
  25. entries, err := os.ReadDir(path)
  26. if err != nil {
  27. return err
  28. }
  29. if filepath.Clean(path) != "notes_folder" {
  30. f.Nume = filepath.Base(path)
  31. } else {
  32. f.Nume = "notes_folder"
  33. }
  34. for _, entry := range entries {
  35. if entry.IsDir() {
  36. sub := Folder{}
  37. err = GetFolderStructure(filepath.Join(path, entry.Name()), &sub)
  38. if err != nil {
  39. return err
  40. }
  41. f.Subfoldere = append(f.Subfoldere, sub)
  42. } else {
  43. fisier := File{
  44. Nume: entry.Name(),
  45. Path: filepath.Join(path, entry.Name()),
  46. }
  47. f.Fisiere = append(f.Fisiere, fisier)
  48. }
  49. }
  50. return nil
  51. }