-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (77 loc) · 2.08 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
err := entry()
if err != nil {
os.Exit(1)
}
}
func usage(program string) {
fmt.Printf("Usage: %s [SUBCOMMAND] [OPTIONS]\n", program)
fmt.Println("Subcommands:")
fmt.Println(" index <folder> index the <folder> and save the index to index.json file")
fmt.Println(" search <index-file> check how many documents are indexed in the file (searching is not implemented yet)")
fmt.Println(" serve <index-file> [address] start local HTTP server with Web Interface")
}
func entry() error {
args := os.Args
program := args[0]
if len(args) < 2 {
usage(program)
return fmt.Errorf("ERROR: no subcommand was provided")
}
subcommand := args[1]
switch subcommand {
case "index":
if len(args) < 3 {
usage(program)
return fmt.Errorf("ERROR: no directory is provided for %s subcommand", subcommand)
}
docs, err := NewDocumentsFromFolder(args[2])
if err != nil {
return err
}
err = docs.SaveToJson("index.json")
if err != nil {
return err
}
case "search":
if len(args) < 3 {
usage(program)
return fmt.Errorf("ERROR: no path to index is provided for %s subcommand", subcommand)
}
return checkIndex(args[2])
case "serve":
if len(args) < 3 {
usage(program)
return fmt.Errorf("ERROR: no path to index is provided for %s subcommand", subcommand)
}
docs, err := LoadDocumentsFromJson(args[2])
if err != nil {
return err
}
startServe(docs)
default:
usage(program)
return fmt.Errorf("ERROR: unknown subcommand %s", subcommand)
}
return nil
}
func checkIndex(indexPath string) error {
fmt.Printf("Reading %s index file...\n", indexPath)
content, err := os.ReadFile(indexPath)
if err != nil {
return fmt.Errorf("ERROR: could not open index file %s: %s", indexPath, err.Error())
}
var result map[string]interface{}
err = json.Unmarshal(content, &result)
if err != nil {
return fmt.Errorf("ERROR: could not parse index file %s: %s", indexPath, err.Error())
}
fmt.Printf("%s contains %d files\n", indexPath, len(result))
return nil
}