-
Notifications
You must be signed in to change notification settings - Fork 20
/
helpers.go
264 lines (226 loc) · 6.27 KB
/
helpers.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package main
import (
"encoding/json"
"bufio"
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"strings"
"github.com/agnivade/levenshtein"
"gopkg.in/yaml.v2"
)
// DownloadFileToString downloads a file from a given URL and returns it's
// contents as a string if successful
func DownloadFileToString(url string) (string, error) {
var client http.Client
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
if appConf.GithubToken != "" {
req.Header.Add("Authorization", "token " + appConf.GithubToken)
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(bodyBytes), nil
} else if err == nil {
err = fmt.Errorf("HTTP code %v", resp.StatusCode)
}
return "", err
}
type GitHubFile struct {
Name string `json:"name"`
Path string `json:"path"`
Sha string `json:"sha"`
Size int `json:"size"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
GitURL string `json:"git_url"`
DownloadURL string `json:"download_url"`
Type string `json:"type"`
Links struct {
Self string `json:"self"`
Git string `json:"git"`
HTML string `json:"html"`
} `json:"_links"`
}
type GitHubFilesCollection struct {
Collection []GitHubFile
}
func findYAMLinRepo(repoURL string) []GitHubFile {
parts := strings.Split(repoURL, "/")
ApiUrl := ("https://api.github.com/repos/" + parts[3] + "/" + parts[4] + "/contents/")
// fmt.Println("generated api URL: ", ApiUrl)
// Get all files from repo
// repoFiles, err := DownloadFileToString("https://api.github.com/repos/atelierbram/base16-atelier-schemes/contents/")
repoFiles, err := DownloadFileToString(ApiUrl)
if err != nil {
fmt.Println("Failed to get schemes from: " + repoURL + " with error '" + err.Error() + "'")
return nil
}
keys := make([]GitHubFile, 0)
json.Unmarshal([]byte(repoFiles), &keys)
// Create a list of .yaml files
var colorSchemes []GitHubFile
for _, v := range keys {
re := regexp.MustCompile(".*ya?ml")
if re.MatchString(v.Name) {
colorSchemes = append(colorSchemes, v)
}
}
// fmt.Println("Found ", len(colorSchemes), "in repo ", repoFiles)
return colorSchemes
}
func LoadStringMap(path string) map[string]string {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
check(err)
yamlFile, err := ioutil.ReadAll(f)
check(err)
data := make(map[string]string)
err = yaml.Unmarshal(yamlFile, data)
check(err)
return data
}
func SaveStringMap(data map[string]string, path string) {
yamlData, err := yaml.Marshal(data)
check(err)
saveFile, err := os.Create(path)
defer saveFile.Close()
saveFile.Write(yamlData)
saveFile.Close()
fmt.Println("wrote to: ", saveFile.Name())
}
func FindMatchInMap(choices map[string]string, input string) string {
if len(choices) == 0 {
panic("cannot select from empty choices")
}
var match string
distance := 1000
for k := range choices {
tempDistance := levenshtein.ComputeDistance(input, k)
if tempDistance < distance {
match = k
distance = tempDistance
}
}
return match
}
func exe_cmd(cmd string) {
if len(cmd) == 0 {
return
}
parts := strings.Fields(cmd)
head := parts[0]
parts = parts[1:len(parts)]
out, err := exec.Command(head, parts...).Output()
fmt.Println("[HOOK]: Running: ", cmd)
if err != nil {
fmt.Printf("%s\n", err)
}
fmt.Printf("%s\n", out)
}
func WriteFile(path string, contents []byte) error {
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("could not open file %q: %w", path, err)
}
defer file.Close()
if _, err = file.Write(contents); err != nil {
return fmt.Errorf("could not write in file %q: %w", path, err)
}
if err = file.Sync(); err != nil {
return fmt.Errorf("could not flush file contents %q: %w", path, err)
}
return nil
}
func ReplaceMultiline(filepath, replaceContents, startMarker, endMarker string) error {
if startMarker == "" {
return fmt.Errorf("start marker regular expression cannot be empty if file mode is replace")
}
if endMarker == "" {
return fmt.Errorf("end marker regular expression cannot be empty if file mode is replace")
}
startMarkerRegex, err := regexp.Compile(startMarker)
if err != nil {
return fmt.Errorf("invalid start marker regular expression: %w", err)
}
endMarkerRegex, err := regexp.Compile(endMarker)
if err != nil {
return fmt.Errorf("invalid end marker regular expression: %w", err)
}
newContents, err := getReplacedContents(filepath, replaceContents, startMarkerRegex, endMarkerRegex)
if err != nil {
return fmt.Errorf("could not replace in file %q: %w", filepath, err)
}
return WriteFile(filepath, newContents)
}
func getReplacedContents(filepath, replaceContents string, startMarkerRegex, endMarkerRegex *regexp.Regexp) ([]byte, error) {
file, err := os.Open(filepath)
if err != nil {
return nil, fmt.Errorf("could not open %q: %w", filepath, err)
}
var buffer bytes.Buffer
var startFound, endFound bool
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Bytes()
if !startFound && startMarkerRegex.Match(line) {
startFound = true
buffer.Write(line)
buffer.WriteString("\n")
buffer.Write([]byte(replaceContents))
} else if !startFound {
buffer.Write(line)
buffer.WriteString("\n")
} else if !endFound && endMarkerRegex.Match(line) {
endFound = true
buffer.Write(line)
buffer.WriteString("\n")
} else if startFound && endFound {
buffer.Write(line)
buffer.WriteString("\n")
}
}
if err = scanner.Err(); err != nil {
return nil, fmt.Errorf("could not read file %q: %w", filepath, err)
}
if !startFound {
return nil, fmt.Errorf("could not find a line matching start_marker regex in %q", filepath)
}
if !endFound {
return nil, fmt.Errorf("could not find a line matching end_marker regex in %q", filepath)
}
return buffer.Bytes(), nil
}
func deepCompareFiles(file1, file2 string) bool {
sf, err := os.Open(file1)
if err != nil {
log.Fatal(err)
}
df, err := os.Open(file2)
if err != nil {
log.Fatal(err)
}
sscan := bufio.NewScanner(sf)
dscan := bufio.NewScanner(df)
for sscan.Scan() {
dscan.Scan()
if !bytes.Equal(sscan.Bytes(), dscan.Bytes()) {
return false
}
}
return true
}