files.go 963 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package movies
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. )
  8. type FileSource struct {
  9. ID string
  10. Files []string
  11. }
  12. func (fs *FileSource) Scan(root string) error {
  13. var files []string
  14. if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
  15. if err != nil {
  16. return err
  17. }
  18. if info.IsDir() {
  19. return nil
  20. }
  21. files = append(files, path)
  22. return nil
  23. }); err != nil {
  24. return fmt.Errorf("error while walking directory %q: %w", root, err)
  25. }
  26. fs.Files = files
  27. return nil
  28. }
  29. func (fs *FileSource) Search(query string) []string {
  30. split := strings.Split(query, " ")
  31. var res []string
  32. for _, path := range fs.Files {
  33. if stringContainsAll(path, split) {
  34. res = append(res, path)
  35. }
  36. }
  37. return res
  38. }
  39. func stringContainsAll(path string, split []string) bool {
  40. path = strings.ToLower(path)
  41. for _, s := range split {
  42. if !strings.Contains(path, strings.ToLower(s)) {
  43. return false
  44. }
  45. }
  46. return true
  47. }