forked from driusan/bug
/
BugApplication.go
450 lines (397 loc) · 11.8 KB
/
BugApplication.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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package main
import (
"fmt"
"github.com/driusan/bug/bugs"
"io/ioutil"
"log"
"os"
"os/exec"
"sort"
"strconv"
"strings"
)
type BugApplication struct{}
func (a BugApplication) Env() {
fmt.Printf("Settings used by this command:\n")
fmt.Printf("\nIssues directory:\t%s/issues/", bugs.GetRootDir())
fmt.Printf("\nEditor:\t%s", getEditor())
fmt.Printf("\n")
}
func listTags(files []os.FileInfo, args []string) {
hasTag := func(tags []string, tag string) bool {
for _, candidate := range tags {
if candidate == tag {
return true
}
}
return false
}
b := bugs.Bug{}
for idx, _ := range files {
b.LoadBug(bugs.Directory(bugs.GetRootDir() + "/issues/" + bugs.Directory(files[idx].Name())))
tags := b.StringTags()
for _, tag := range args {
if hasTag(tags, tag) {
fmt.Printf("Issue %d: %s (%s)\n", idx+1, b.Title, strings.Join(tags, ", "))
}
}
}
}
func (a BugApplication) List(args []string) {
issues, _ := ioutil.ReadDir(string(bugs.GetRootDir()) + "/issues")
// No parameters, print a list of all bugs
if len(args) == 0 {
for idx, issue := range issues {
var dir bugs.Directory = bugs.Directory(issue.Name())
fmt.Printf("Issue %d: %s\n", idx+1, dir.ToTitle())
}
return
}
// There were parameters, so show the full description of each
// of those issues
b := bugs.Bug{}
for i, length := 0, len(args); i < length; i += 1 {
idx, err := strconv.Atoi(args[i])
if err != nil {
listTags(issues, args)
return
}
if idx > len(issues) || idx < 1 {
fmt.Printf("Invalid issue number %d\n", idx)
continue
}
if err == nil {
b.LoadBug(bugs.Directory(bugs.GetRootDir() + "/issues/" + bugs.Directory(issues[idx-1].Name())))
b.ViewBug()
if i < length-1 {
fmt.Printf("\n--\n\n")
}
}
}
fmt.Printf("\n")
}
func (a BugApplication) Edit(args []string) {
issues, _ := ioutil.ReadDir(string(bugs.GetRootDir()) + "/issues")
// No parameters, print a list of all bugs
if len(args) == 1 {
idx, err := strconv.Atoi(args[0])
if idx > len(issues) || idx < 1 {
fmt.Printf("Invalid issue number %d\n", idx)
return
}
dir := bugs.Directory(bugs.GetRootDir()) + "/issues/" + bugs.Directory(issues[idx-1].Name())
cmd := exec.Command(getEditor(), string(dir)+"/Description")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
} else {
fmt.Printf("Usage: %s edit issuenum\n", os.Args[0])
fmt.Printf("\nNo issue number specified\n")
}
}
func (a BugApplication) Close(args []string) {
issues, _ := ioutil.ReadDir(string(bugs.GetRootDir()) + "/issues")
// No parameters, print a list of all bugs
if len(args) == 0 {
fmt.Printf("Usage: %s close IssueNumber\n\nMust provide an IssueNumber to close as parameter\n", os.Args[0])
return
}
// There were parameters, so show the full description of each
// of those issues
for i := 0; i < len(args); i += 1 {
idx, err := strconv.Atoi(args[i])
if idx > len(issues) || idx < 1 {
fmt.Printf("Invalid issue number %d\n", idx)
continue
}
if err == nil {
dir := bugs.GetRootDir() + "/issues/" + bugs.Directory(issues[idx-1].Name())
fmt.Printf("Removing %s\n", dir)
os.RemoveAll(string(dir))
}
}
}
func (a BugApplication) Purge() {
cmd := exec.Command("git", "clean", "-fd", string(bugs.GetRootDir())+"/issues")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}
func getAllTags() []string {
bugs := bugs.GetAllBugs()
// Put all the tags in a map, then iterate over
// the keys so that only unique tags are included
tagMap := make(map[string]int, 0)
for _, bug := range bugs {
for _, tag := range bug.Tags() {
tagMap[string(tag)] += 1
}
}
keys := make([]string, 0, len(tagMap))
for k := range tagMap {
keys = append(keys, k)
}
return keys
}
func (a BugApplication) Tag(Args []string) {
if len(Args) < 2 {
fmt.Printf("Usage: %s tag issuenum tagname [more tagnames]\n", os.Args[0])
fmt.Printf("\nBoth issue number and tagname to set are required.\n")
fmt.Printf("\nCurrently used tags in entire tree: %s\n", strings.Join(getAllTags(), ", "))
return
}
b, err := bugs.LoadBugByStringIndex(Args[0])
if err != nil {
fmt.Printf("Could not load bug: %s\n", err.Error())
return
}
for _, tag := range Args[1:] {
b.TagBug(bugs.Tag(tag))
}
}
func (a BugApplication) Create(Args []string) {
if len(Args) < 1 || (len(Args) < 2 && Args[0] == "-n") {
fmt.Printf("Usage: %s create [-n] Bug Description\n", os.Args[0])
fmt.Printf("\nNo Bug Description provided.\n")
return
}
var noDesc bool = false
if Args != nil && Args[0] == "-n" {
noDesc = true
Args = Args[1:]
}
var bug bugs.Bug
bug = bugs.Bug{
Title: strings.Join(Args, " "),
}
dir, _ := bug.GetDirectory()
fmt.Printf("Created issue: %s\n", bug.Title)
var mode os.FileMode
mode = 0775
os.Mkdir(string(dir), mode)
if noDesc {
txt := []byte("")
ioutil.WriteFile(string(dir)+"/Description", txt, 0644)
} else {
cmd := exec.Command(getEditor(), string(dir)+"/Description")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}
}
func (a BugApplication) fieldHandler(command string, args []string,
setCallback func(bugs.Bug, string) error, retrieveCallback func(bugs.Bug) string) {
if len(args) < 1 {
fmt.Printf("Usage: %s %s issuenum [set %s]\n", os.Args[0], command, command)
return
}
idx, err := strconv.Atoi(args[0])
if err != nil {
fmt.Printf("Invalid issue number. \"%s\" is not a number.\n\n", args[0])
fmt.Printf("Usage: %s %s issuenum [set %s]\n", os.Args[0], command, command)
return
}
b, err := bugs.LoadBugByIndex(idx)
if err != nil {
fmt.Printf("Invalid issue number %s\n", args[0])
return
}
if len(args) > 1 {
newValue := strings.Join(args[1:], " ")
err := setCallback(*b, newValue)
if err != nil {
fmt.Printf("Error setting %s: %s", command, err.Error())
}
} else {
val := retrieveCallback(*b)
if val == "" {
fmt.Printf("%s not defined\n", command)
} else {
fmt.Printf("%s\n", val)
}
}
}
func (a BugApplication) Priority(args []string) {
a.fieldHandler("priority", args, bugs.Bug.SetPriority, bugs.Bug.Priority)
}
func (a BugApplication) Status(args []string) {
a.fieldHandler("status", args, bugs.Bug.SetStatus, bugs.Bug.Status)
}
func (a BugApplication) Milestone(args []string) {
a.fieldHandler("milestone", args, bugs.Bug.SetMilestone, bugs.Bug.Milestone)
}
func (a BugApplication) Pwd() {
fmt.Printf("%s", bugs.GetRootDir()+"/issues")
}
// This will try and commit the $(bug pwd) directory
// transparently. It does the following steps:
//
// 1. "git stash create"
// 2. "git reset --mixed" (unstage the user's currently staged files)
// 3. "git add $(bug pwd)"
// 4. "git commit"
// 5a. "git reset --hard" (if there was any stash created,
// this is necessary for 5b to work.)
// 5b. "git stash apply --index" the stash from step 1
func (a BugApplication) Commit() {
type FileStatus struct {
IndexStatus string
WorkingDirStatus string
Filename string
}
statusOutput := func(dir bugs.Directory) []FileStatus {
cmd := exec.Command("git", "status", "--porcelain", "-z", string(dir))
output, err := cmd.Output()
if err != nil {
fmt.Printf("Could not check git status")
return nil
}
fileStatusLines := strings.Split(string(output), "\000")
var files []FileStatus
for _, line := range fileStatusLines {
if len(line) == 0 {
continue
}
files = append(files, FileStatus{
IndexStatus: line[0:1],
WorkingDirStatus: line[1:2],
Filename: line[2:],
})
}
return files
}
// Before doing anything, check git status to see if
// the index is in a state that's going to cause an
// error
sOutput := statusOutput(bugs.GetIssuesDir())
for _, file := range sOutput {
if file.IndexStatus == "D" {
fmt.Printf("You have manually staged changes in your issue directory which will conflict with %s commit.\n", os.Args[0])
return
}
}
sOutput = statusOutput(bugs.GetRootDir())
for _, file := range sOutput {
if file.IndexStatus == "A" {
fmt.Printf("You have a new file staged in your git index, which will cause conflicts with %s commit. Please either commit your changes or unstage %s.\n", os.Args[0], file.Filename)
return
}
}
cmd := exec.Command("git", "stash", "create")
output, err := cmd.Output()
if err != nil {
fmt.Printf("Could not execute git stash create")
return
}
var stashHash string = strings.Trim(string(output), "\n")
// Unstage everything, if there was anything stashed, so that
// we don't commit things that the user has staged that aren't
// issues
if stashHash != "" {
cmd = exec.Command("git", "reset", "--mixed")
err = cmd.Run()
if err != nil {
}
}
// Commit the issues directory
// git add $(bug pwd)
// git commit -m "Added new issues" -q
cmd = exec.Command("git", "add", "-A", string(bugs.GetRootDir())+"/issues")
err = cmd.Run()
if err != nil {
fmt.Printf("Could not add to index?\n")
}
cmd = exec.Command("git", "commit", "-m", "Added or removes issues with the tool \"bug\"", "-q")
err = cmd.Run()
if err != nil {
// If nothing was added commit will have an error,
// but we don't care it just means there's nothing
// to commit.
fmt.Printf("No new issues commited\n")
}
// There were changes that had been stashed, so we need
// to restore them with git stash apply.. first, we
// need to do a "git reset --hard" so that the dirty working
// tree doesn't cause an error. This isn't as scary as it
// sounds, since immediately after git reset --hard we apply
// a stash which has the exact same changes that we just threw
// away.
if stashHash != "" {
cmd = exec.Command("git", "reset", "--hard")
err = cmd.Run()
if err != nil {
fmt.Printf("Error resetting the git working tree\n")
fmt.Printf("The stash which should have your changes is: %s\n", stashHash)
}
cmd = exec.Command("git", "stash", "apply", "--index", stashHash)
err = cmd.Run()
if err != nil {
fmt.Printf("Error restoring the git working tree")
fmt.Printf("The stash which should have your changes is: %s\n", stashHash)
// If nothing was stashed, it's not the end of the world.
//fmt.Printf("Could not pop from stash\n")
}
}
}
type BugListByMilestone [](bugs.Bug)
func (a BugListByMilestone) Len() int { return len(a) }
func (a BugListByMilestone) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a BugListByMilestone) Less(i, j int) bool { return a[i].Milestone() < a[j].Milestone() }
func (a BugApplication) Roadmap() {
issues, _ := ioutil.ReadDir(string(bugs.GetRootDir()) + "/issues")
var bgs [](bugs.Bug)
for idx, _ := range issues {
b := bugs.Bug{}
b.LoadBug(bugs.Directory(bugs.GetRootDir() + "/issues/" + bugs.Directory(issues[idx].Name())))
bgs = append(bgs, b)
}
sort.Sort(BugListByMilestone(bgs))
fmt.Printf("# Roadmap for %s\n", bugs.GetRootDir().GetShortName().ToTitle())
milestone := ""
for i := len(bgs) - 1; i >= 0; i -= 1 {
b := bgs[i]
newMilestone := b.Milestone()
if milestone != newMilestone {
if newMilestone == "" {
fmt.Printf("\n## No milestone set:\n")
} else {
fmt.Printf("\n## %s:\n", newMilestone)
}
}
fmt.Printf("- %s\n", b.Title)
milestone = newMilestone
}
}
func (a BugApplication) Relabel(Args []string) {
if len(Args) < 2 {
fmt.Printf("Usage: %s relabel issuenum New Title\n", os.Args[0])
return
}
b, err := bugs.LoadBugByStringIndex(Args[0])
if err != nil {
fmt.Printf("Could not load bug: %s\n", err.Error())
return
}
currentDir, _ := b.GetDirectory()
newDir := bugs.GetRootDir() + "/issues/" + bugs.TitleToDir(strings.Join(Args[1:], " "))
fmt.Printf("Moving %s to %s\n", currentDir, newDir)
err = os.Rename(string(currentDir), string(newDir))
if err != nil {
fmt.Printf("Error moving directory\n")
}
}
func (a BugApplication) Version() {
fmt.Printf("%s version 0.1\n", os.Args[0])
}