-
Notifications
You must be signed in to change notification settings - Fork 1
/
scan.go
132 lines (112 loc) · 2.46 KB
/
scan.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"strings"
)
func scan(folder string) {
fmt.Printf("Found folders:\n\n")
repositories := recursiveScanFolder(folder)
filepath := getDotFilePath()
addNewSliceElementsToFile(filepath, repositories)
fmt.Printf("\n\nSuccessfully added\n\n")
}
func recursiveScanFolder(folder string) []string {
return scanGitFolders(make([]string, 0), folder)
}
func getDotFilePath() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
dotFile := usr.HomeDir + "/.gitlocalstats"
return dotFile
}
func addNewSliceElementsToFile(filepath string, newRepos []string) {
existingRepos := parseFileLinesToSlice(filepath)
repos := joinSlices(newRepos, existingRepos)
dumpStringsSliceToFile(repos, filepath)
}
func parseFileLinesToSlice(filepath string) []string {
f := openFile(filepath)
defer f.Close()
var lines []string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
if err != io.EOF {
panic(err)
}
}
return lines
}
func openFile(filepath string) *os.File {
f, err := os.OpenFile(filepath, os.O_APPEND|os.O_RDWR, 0755)
if err != nil {
if os.IsNotExist(err) {
_, err := os.Create(filepath)
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
return f
}
func joinSlices(new []string, existing []string) []string {
for _, i := range new {
if !sliceContains(existing, i) {
existing = append(existing, i)
}
}
return existing
}
func sliceContains(slice []string, value string) bool {
for _, v := range slice {
if v == value {
return true
}
}
return false
}
func dumpStringsSliceToFile(repos []string, filepath string) {
content := strings.Join(repos, "\n")
ioutil.WriteFile(filepath, []byte(content), 0755)
}
func scanGitFolders(folders []string, folder string) []string {
folder = strings.TrimSuffix(folder, "/")
f, err := os.Open(folder)
if err != nil {
log.Fatal(err)
}
files, err := f.ReadDir(-1)
f.Close()
if err != nil {
log.Fatal(err)
}
var path string
for _, file := range files {
if file.IsDir() {
path = folder + "/" + file.Name()
if file.Name() == ".git" {
path = strings.TrimSuffix(path, "/.git")
fmt.Println(path)
folders = append(folders, path)
continue
}
if file.Name() == "vendor" || file.Name() == "node_modules" {
continue
}
folders = scanGitFolders(folders, path)
}
}
return folders
}