forked from tsoding/snitch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
407 lines (329 loc) · 8.57 KB
/
Copy pathmain.go
File metadata and controls
407 lines (329 loc) · 8.57 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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package main
import (
"bufio"
"fmt"
"gopkg.in/go-ini/ini.v1"
"os"
"os/user"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
)
func yOrN(question string) (bool, error) {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s [y/n] ", question)
input, err := reader.ReadString('\n')
text := strings.TrimSpace(input)
for err == nil && text != "y" && text != "n" {
fmt.Printf("%s [y/n] ", question)
text, err = reader.ReadString('\n')
}
if err != nil || text == "n" {
return false, err
}
return true, err
}
func listSubcommand(project Project, filter func(todo Todo) bool) error {
return project.WalkTodosOfDir(".", func(todo Todo) error {
if filter(todo) {
fmt.Printf("%v\n", todo.LogString())
}
return nil
})
}
func reportSubcommand(project Project, creds GithubCredentials, repo string, prependBody string) error {
todosToReport := []Todo{}
err := project.WalkTodosOfDir(".", func(todo Todo) error {
if todo.ID == nil {
fmt.Printf("%v\n", todo.LogString())
fmt.Printf("Issue Title: %s\n", todo.Title)
for _, bodyLine := range todo.Body {
fmt.Printf(" %s\n", bodyLine)
}
yes, err := yOrN("Do you want to report this? ")
if yes {
todosToReport = append(todosToReport, todo)
}
return err
}
return nil
})
if err != nil {
return err
}
for _, todo := range todosToReport {
reportedTodo, err := todo.ReportTodo(creds, repo, prependBody+"\n"+strings.Join(todo.Body, "\n"))
if err != nil {
return err
}
fmt.Printf("[REPORTED] %v\n", reportedTodo.LogString())
err = reportedTodo.Update()
if err != nil {
return err
}
err = reportedTodo.GitCommit("Add")
if err != nil {
return err
}
}
return err
}
func purgeSubcommand(project Project, creds GithubCredentials, repo string) error {
todosToRemove := []Todo{}
err := project.WalkTodosOfDir(".", func(todo Todo) error {
if todo.ID == nil {
return nil
}
status, err := todo.RetrieveGithubStatus(creds, repo)
if err != nil {
return err
}
if status == "closed" {
fmt.Printf("[CLOSED] %v\n", todo.LogString())
fmt.Printf("Issue link: https://github.com/%s/issues/%s\n", repo, (*todo.ID)[1:])
yes, err := yOrN("This issue is closed. Do you want to remove the TODO?")
if yes {
todosToRemove = append(todosToRemove, todo)
}
if err != nil {
return err
}
} else {
fmt.Printf("[OPEN] %v\n", todo.LogString())
}
return err
})
sort.Slice(todosToRemove, func(i, j int) bool {
if todosToRemove[i].Filename == todosToRemove[j].Filename {
return todosToRemove[i].Line > todosToRemove[j].Line
}
return todosToRemove[i].Filename < todosToRemove[j].Filename
})
for _, todo := range todosToRemove {
err = todo.Remove()
if err != nil {
return err
}
fmt.Printf("[REMOVED] %v\n", todo)
err = todo.GitCommit("Remove")
if err != nil {
return err
}
}
return err
}
func usage() {
// FIXME(#9): implement a map for options instead of println'ing them all there
fmt.Printf("snitch [opt]\n" +
"\tlist [--unreported] [--reported]: lists all todos of a dir recursively\n" +
"\treport [--prepend-body <issue-body>]: reports all todos of a dir recursively as GitHub issues\n" +
"\tpurge: removes all of the reported TODOs that refer to closed issues\n")
}
func locateDotGit(dir string) (string, error) {
absDir, err := filepath.Abs(dir)
if err != nil {
return "", err
}
for absDir != "/" {
dotGit := path.Join(absDir, ".git")
if stat, err := os.Stat(dotGit); !os.IsNotExist(err) && stat.IsDir() {
return dotGit, nil
}
absDir = filepath.Dir(absDir)
}
return "", fmt.Errorf("Couldn't find .git. Maybe you are not inside of a git repo")
}
func repoFromConfig(configPath string) (string, error) {
cfg, err := ini.Load(configPath)
if err != nil {
return "", err
}
origin := cfg.Section("remote \"origin\"")
if origin == nil {
return "", fmt.Errorf("The git repo doesn't have any origin remote. " +
"Please use `git remote add' command to add one.")
}
url := origin.Key("url")
if url == nil {
return "", fmt.Errorf("The origin remote doesn't have any URL's " +
"associated with it.")
}
urlString := url.String()
githubRepoRegexp := regexp.MustCompile(
"github.com[:/]([-\\w]+)\\/([-\\w]+)(.git)?")
groups := githubRepoRegexp.FindStringSubmatch(urlString)
if groups != nil {
return groups[1] + "/" + groups[2], nil
}
return "", fmt.Errorf("%s does not match %v",
urlString, githubRepoRegexp)
}
func getGithubRepo(directory string) (string, error) {
dotGit, err := locateDotGit(directory)
if err != nil {
return "", err
}
return repoFromConfig(path.Join(dotGit, "config"))
}
func parseParams(args []string) (map[string]string, error) {
currentParam := ""
result := map[string]string{}
for _, arg := range args {
if strings.HasPrefix(arg, "--") { // Flag
if len(currentParam) != 0 {
result[currentParam] = ""
}
currentParam = arg[2:]
} else { // Value
if len(currentParam) == 0 {
return nil, fmt.Errorf("Value %v is not associated with any flag", arg)
}
result[currentParam] = arg
currentParam = ""
}
}
if len(currentParam) != 0 {
result[currentParam] = ""
}
return result, nil
}
func checkParams(params map[string]string, allowedParams []string) error {
for param := range params {
allowed := false
for _, allowedParam := range allowedParams {
if param == allowedParam {
allowed = true
break
}
}
if !allowed {
return fmt.Errorf("Unknown flag `%s'", param)
}
}
return nil
}
func locateProject(directory string) (string, error) {
dotGit, err := locateDotGit(directory)
if err != nil {
return "", err
}
// FIXME(#148): snitch is looking only for .snitch.yaml ignoring .snitch.yml
return path.Join(filepath.Dir(dotGit), ".snitch.yaml"), nil
}
func getGithubCredentials() (GithubCredentials, error) {
tokenEnvar := os.Getenv("GITHUB_PERSONAL_TOKEN")
xdgEnvar := os.Getenv("XDG_CONFIG_HOME")
usr, err := user.Current()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if len(tokenEnvar) != 0 {
return GithubCredentialsFromToken(tokenEnvar), nil
}
// custom XDG_CONFIG_HOME
if len(xdgEnvar) != 0 {
filePath := path.Join(xdgEnvar, "snitch/github.ini")
if _, err := os.Stat(filePath); err == nil {
return GithubCredentialsFromFile(filePath)
}
}
// default XDG_CONFIG_HOME
if len(xdgEnvar) == 0 {
filePath := path.Join(usr.HomeDir, ".config/snitch/github.ini")
if _, err := os.Stat(filePath); err == nil {
return GithubCredentialsFromFile(filePath)
}
}
filePath := path.Join(usr.HomeDir, ".snitch/github.ini")
if _, err := os.Stat(filePath); err == nil {
return GithubCredentialsFromFile(filePath)
}
return GithubCredentials{}, fmt.Errorf("GitHub token is missing")
}
func main() {
creds, err := getGithubCredentials()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
repo, err := getGithubRepo(".")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
projectPath, err := locateProject(".")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
project, err := NewProject(projectPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if len(os.Args) > 1 {
switch os.Args[1] {
case "list":
params, err := parseParams(os.Args[2:])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
err = checkParams(params, []string{"unreported", "reported"})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
_, unreported := params["unreported"]
_, reported := params["reported"]
err = listSubcommand(*project, func(todo Todo) bool {
filter := reported == unreported
if unreported {
filter = filter || todo.ID == nil
}
if reported {
filter = filter || todo.ID != nil
}
return filter
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
case "report":
params, err := parseParams(os.Args[2:])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
err = checkParams(params, []string{"prepend-body"})
if err != nil {
fmt.Fprintln(os.Stderr, err)
usage()
os.Exit(1)
}
prependBody, ok := params["prepend-body"]
if !ok {
prependBody = ""
}
fmt.Printf("Detected GitHub project: https://github.com/%s\n", repo)
if err = reportSubcommand(*project, creds, repo, prependBody); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
case "purge":
if err = purgeSubcommand(*project, creds, repo); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
default:
fmt.Fprintf(os.Stderr, "`%s` unknown command\n", os.Args[1])
os.Exit(1)
}
} else {
usage()
}
}