Browse Source

Add file scanning and searching

Gildas Chabot 4 years ago
parent
commit
fcebd04bc3
2 changed files with 66 additions and 0 deletions
  1. 46 0
      files.go
  2. 20 0
      files_test.go

+ 46 - 0
files.go

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

+ 20 - 0
files_test.go

@@ -0,0 +1,20 @@
1
+package movies
2
+
3
+import (
4
+	"fmt"
5
+	"os"
6
+	"testing"
7
+)
8
+
9
+func TestFileSource(t *testing.T) {
10
+	fs := &FileSource{ID: "dummy fs"}
11
+
12
+	if err := fs.Scan(os.Getenv("FILE_ROOT")); err != nil {
13
+		t.Fatal(err)
14
+	}
15
+
16
+	fmt.Println(len(fs.Files))
17
+	for _, res := range fs.Search("angie") {
18
+		fmt.Println(res)
19
+	}
20
+}