files.go 996 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. if fs == nil {
  31. return nil
  32. }
  33. split := strings.Split(query, " ")
  34. var res []string
  35. for _, path := range fs.Files {
  36. if stringContainsAll(path, split) {
  37. res = append(res, path)
  38. }
  39. }
  40. return res
  41. }
  42. func stringContainsAll(path string, split []string) bool {
  43. path = strings.ToLower(path)
  44. for _, s := range split {
  45. if !strings.Contains(path, strings.ToLower(s)) {
  46. return false
  47. }
  48. }
  49. return true
  50. }