-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
97 lines (83 loc) · 1.85 KB
/
main.go
File metadata and controls
97 lines (83 loc) · 1.85 KB
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
93
94
95
96
97
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
)
func main() {
var mut = &sync.Mutex{}
var wg sync.WaitGroup
allFiles := TraverseDir("test", 1)
srcMap := make(map[string]string)
index := make(map[string][]string)
wg.Add(len(allFiles))
for _, file := range allFiles {
go createSrcMap(file, srcMap, &wg, mut)
}
wg.Wait()
wg.Add(len(srcMap))
for fileName, srcCode := range srcMap {
go createIndex(fileName, srcCode, index, &wg, mut)
}
wg.Wait()
createJsonFile(index)
}
func TraverseDir(s string, depth int) []string {
dir, err := os.ReadDir(s)
// TODO handle error properly
if err != nil {
fmt.Println("Error reading directory/file:", err)
os.Exit(1)
}
var ds []string
for _, v := range dir {
fullpath := filepath.Join(s, v.Name())
if v.IsDir() {
ds = append(ds, TraverseDir(fullpath, 1)...)
depth--
if depth <= 0 {
return ds
}
} else {
ds = append(ds, fullpath)
}
}
return ds
}
func createSrcMap(file string, srcMap map[string]string, wg *sync.WaitGroup, mut *sync.Mutex) {
defer wg.Done()
bs, err := os.ReadFile(file)
if err != nil {
fmt.Println("Error reading file:", err)
os.Exit(1)
}
contents := string(bs)
mut.Lock()
srcMap[file] = contents
mut.Unlock()
}
func createIndex(fileName string, srcCode string, index map[string][]string, wg *sync.WaitGroup, mut *sync.Mutex) {
defer wg.Done()
keywords := strings.Fields(srcCode)
for _, word := range keywords {
mut.Lock()
value, ok := index[word]
if ok {
index[word] = append(value, fileName)
} else {
index[word] = []string{fileName}
}
mut.Unlock()
}
}
func createJsonFile(index map[string][]string) {
jsonbytes ,err := json.MarshalIndent(index, "", " ")
if err!=nil {
fmt.Println("Error converting map to json: ", err)
os.Exit(1)
}
os.WriteFile("jsonIndex.json",jsonbytes,os.ModeAppend)
}