forked from wmbaum/check_mk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gb
executable file
·655 lines (546 loc) · 17.1 KB
/
gb
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
#!/usr/bin/python
import sys, os, time, termios, tty
# colored output, if stdout is a tty
if sys.stdout.isatty():
tty_red = '\033[31m'
tty_green = '\033[32m'
tty_yellow = '\033[33m'
tty_blue = '\033[34m'
tty_magenta = '\033[35m'
tty_cyan = '\033[36m'
tty_white = '\033[37m'
tty_bgred = '\033[41m'
tty_bgyellow = '\033[43m'
tty_bgblue = '\033[44m'
tty_bgmagenta = '\033[45m'
tty_bgcyan = '\033[46m'
tty_bgwhite = '\033[47m'
tty_bold = '\033[1m'
tty_underline = '\033[4m'
tty_normal = '\033[0m'
def tty_colors(codes):
return '\033[%sm' % (';'.join([str(c) for c in codes]))
else:
tty_red = ''
tty_green = ''
tty_yellow = ''
tty_blue = ''
tty_magenta = ''
tty_cyan = ''
tty_white = ''
tty_bgblue = ''
tty_bgmagenta = ''
tty_bgcyan = ''
tty_bold = ''
tty_underline = ''
tty_normal = ''
tty_ok = 'OK'
def tty_colors(c):
return ""
def get_tty_size():
import termios,struct,fcntl
try:
ws = struct.pack("HHHH", 0, 0, 0, 0)
ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)
lines, columns, x, y = struct.unpack("HHHH", ws)
if lines > 0 and columns > 0:
return lines, columns
except:
pass
return (24, 99999)
grep_colors = [
tty_bold + tty_magenta,
tty_bold + tty_cyan,
tty_bold + tty_green,
]
def bail_out(text):
sys.stderr.write(text + "\n")
sys.exit(1)
def goto_bugsdir():
base_dir = os.path.abspath('.')
while not os.path.exists(".bugs") and os.path.abspath('.') != '/':
os.chdir("..")
try:
os.chdir(".bugs")
except:
sys.stderr.write("Cannot find directory .bugs\n")
sys.exit(1)
def load_config():
global g_last_bug
execfile("config", globals(), globals())
try:
g_last_bug = int(file(".last").read())
except:
g_last_bug = None
def load_bugs():
global g_bugs
g_bugs = {}
check_modified()
for entry in os.listdir("."):
try:
bugid = int(entry)
try:
g_bugs[bugid] = load_bug(bugid)
except:
sys.stderr.write("SKIPPING INVALID BUG %d\n" % bugid)
except:
continue
def save_last_bugid(id):
try:
file(".last", "w").write("%d\n" % int(id))
except:
pass
def check_modified():
global g_modified
g_modified = set([])
for line in os.popen("git status --porcelain"):
if line[0] in "AM" and ".bugs/" in line:
try:
id = line.rsplit("/", 1)[-1].strip()
g_modified.add(int(id))
except:
pass
def bug_is_modified(bugid):
return bugid in g_modified
def load_bug(bugid):
bug = {
"id" : bugid,
"state" : "unknown",
"title" : "unknown",
"component" : "general",
"targetversion" : "future",
}
f = file(str(bugid))
for line in f:
line = line.strip()
if line == "":
break
header, value = line.split(":", 1)
bug[header.strip().lower()] = value.strip()
description = ""
for line in f:
description += line
bug["description"] = description
return bug
def save_bug(bug):
f = file(str(bug["id"]), "w")
f.write("Title: %s\n" % bug["title"])
for key, val in bug.items():
if key not in [ "title", "description", "id" ]:
f.write("%s%s: %s\n" % (key[0].upper(), key[1:], val))
f.write("\n")
f.write(bug["description"])
f.close()
git_add(bug)
save_last_bugid(bug["id"])
def git_add(bug):
os.system("git add %d" % bug["id"])
def next_bug_id():
my_bug_ids = get_bug_ids()
if not my_bug_ids:
bail_out('You have no bug IDS left. You can reserve 10 additional bug IDS with "gb ids 10".')
return my_bug_ids[0]
def add_comment(bug, title, comment):
bug["description"] += """
%s: %s
%s""" % (time.strftime("%F %T"), title, comment)
def usage():
sys.stdout.write("""Usage: gb COMMAND [ARGS...]
where COMMAND is one of:
ids [#] - Shows the number of reserved bug IDS. With a number
given as parameter the command will reserve new bug IDS.
list [-r] [STATE] - list bugs (-r: reverse)
new - create a new bug
show [# #..] - show several bugs, or 'all' for all, of leave out for last
resolve ID - change a bugs state
delete #.. - delete bug(s)
grep [-v] KW1 KW2... - show bugs containing all of the given keywords (-v: verbose)
edit [#] - open bug # in editor (or newest bug)
blame [#] - show who worked on a bug
commit - commit all changed and new bugs
""")
sys.exit(1)
def bug_state(bug):
state = bug["state"]
return "%s%-8s%s" % (tty_bold + states.get(state, ""), state, tty_normal)
def num_color(n, colors, inverse):
if inverse:
b = 40
else:
b = 30
c = colors[n-1]
return tty_colors([b + c, 1])
def list_bug(bug):
if bug_is_modified(bug["id"]):
bold = tty_bold + tty_cyan + "(*) "
else:
bold = ""
lines, cols = get_tty_size()
title = bug["title"][:cols - 45]
sys.stdout.write("#%04d %-8s %-9s %-10s %s%-8s%s %s%s%s\n" %
(int(bug["id"]),
bug_state(bug),
bug["class"], bug["component"], tty_bold,
bug["targetversion"], tty_normal, bold, title, tty_normal))
def show_bug(bug):
list_bug(bug)
sys.stdout.write("\n%s\n" % bug["description"])
def main_list(args, format):
bugs = g_bugs.values()
# arguments are tags from state, component and class. Multiple values
# in one class are orred. Multiple types are anded.
filters = {}
sort = lambda a,b: cmp(a['id'], b['id'])
reverse = False
for a in args:
if a == '-r':
reverse = True
continue
hit = False
for tp, values in [
( "component", components ),
( "state", states ),
( "class", classes ),
( "targetversion", targetversions),
]:
for v in values:
if type(v) == tuple:
v = v[0]
if v.startswith(a):
entries = filters.get(tp, [])
entries.append(v)
filters[tp] = entries
hit = True
break
if hit:
break
if not hit:
bail_out("No such component, state, class or target version: %s" % a)
# Filter
newbugs = []
for bug in bugs:
skip = False
for tp, entries in filters.items():
if bug[tp] not in entries:
skip = True
break
if not skip:
newbugs.append(bug)
bugs = newbugs
# Sort
if sort:
newbugs.sort(sort)
if reverse:
newbugs.reverse()
# Output
if format == "console":
for bug in bugs:
list_bug(bug)
else:
output_csv(bugs)
# CSV Table has the following columns:
# Component;ID;Title;Class;Effort
def output_csv(bugs):
def line(*l):
sys.stdout.write('"' + '";"'.join(map(str, l)) + '"\n')
nr = 1
for entry in components:
if len(entry) == 2:
name, alias = entry
else:
name = entry
alias = entry
line("", "", "", "", "")
total_effort = 0
for bug in bugs:
if bug["component"] == name:
total_effort += bug_effort(bug)
line("", "%d. %s" % (nr, alias), "", total_effort)
nr += 1
for bug in bugs:
if bug["component"] == name:
line(bug["id"], bug["title"], bug_class(bug), bug_effort(bug))
line("", bug["description"].replace("\n", " ").replace('"', "'"), "", "")
def bug_class(bug):
cl = bug["class"]
for entry in classes:
if entry == cl:
return cl
elif type(entry) == tuple and entry[0] == cl:
return entry[1]
return cl
def bug_effort(bug):
return int(bug.get("effort", "0"))
def main_show(args):
ids = args
if len(ids) == 0:
if g_last_bug == None:
bail_out("No last bug known. Please specify id.")
ids = [ g_last_bug ]
elif ids[0] == 'all':
ids = [ id for (id, bug) in g_bugs.items() ]
for id in ids:
if id != ids[0]:
sys.stdout.write("-------------------------------------------------------------------------------\n")
try:
show_bug(g_bugs[int(id)])
except:
sys.stderr.write("Skipping invalid bug id '%s'\n" % id)
save_last_bugid(ids[-1])
def get_input(what, default = ""):
sys.stdout.write("%s: " % what)
sys.stdout.flush()
value = sys.stdin.readline().strip()
if value == "":
return default
else:
return value
def get_long_input(what):
sys.stdout.write("Enter %s. End with CTRL-D.\n" % what)
usertext = sys.stdin.read()
# remove leading and trailing empty lines
while usertext.startswith("\n"):
usertext = usertext[1:]
while usertext.endswith("\n\n"):
usertext = usertext[:-1]
return usertext
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
if ord(ch) == 3:
raise KeyboardInterrupt()
return ch
def input_choice(what, choices):
ctc = {}
texts = []
for choice in choices:
if type(choice) == tuple:
choice = choice[0]
for c in choice:
if c not in ".-_/" and c not in ctc:
ctc[c] = choice
texts.append(choice.replace(c, tty_bold + c + tty_normal, 1))
break
while True:
sys.stdout.write("%s (%s): " % (what, ", ".join(texts)))
sys.stdout.flush()
c = getch()
if c in ctc:
sys.stdout.write(" %s%s%s\n" % (
tty_bold, ctc[c], tty_normal))
return ctc[c]
else:
sys.stdout.write("\n")
def main_new(args):
bug = {}
bug["id"] = next_bug_id()
bug["state"] = "open"
bug["date"] = time.strftime("%F %T")
bug["title"] = get_input("Title")
if bug["title"] == "":
sys.stderr.write("Cancelled.\n")
sys.exit(0)
bug["class"] = input_choice("Class", classes)
bug["component"] = input_choice("Component", components)
bug["targetversion"] = input_choice("Target Version", targetversions)
bug["description"] = get_long_input("description")
g_bugs[bug["id"]] = bug
save_bug(bug)
invalidate_my_bugid(bug["id"])
sys.stdout.write("Bug saved with id %d.\n" % bug["id"])
def main_blame(args):
if len(args) == 0:
if g_last_bug == None:
bail_out("No last bug, please specify id.")
id = g_last_bug
else:
if len(args) != 1:
usage()
id = int(args[0])
bug = g_bugs.get(id)
if not bug:
bail_out("No such bug.\n")
save_last_bugid(id)
os.system("git blame %d" % id)
def main_resolve(args):
if len(args) == 0:
if g_last_bug == None:
bail_out("No last bug, please specify id.")
id = g_last_bug
else:
if len(args) != 1:
usage()
id = int(args[0])
bug = g_bugs.get(id)
if not bug:
bail_out("No such bug.\n")
show_bug(bug)
state = input_choice("State", states.keys())
comment = get_long_input("comment")
add_comment(bug, "changed state %s -> %s" % (bug["state"], state), comment)
bug["state"] = state
save_bug(bug)
def main_delete(args):
for ids in args:
if 0 == os.system("git rm %s" % ids):
sys.stdout.write("Delete bug %s (%s)\n" % (ids, g_bugs[int(ids)]["descriptions"]))
def grep(line, kw, n):
lc = kw.lower()
i = line.lower().find(lc)
if i == -1:
return None
else:
col = grep_colors[n % len(grep_colors)]
return line[0:i] + col + line[i:i+len(kw)] + tty_normal + line[i+len(kw):]
def main_grep(args):
if '-v' in args:
verbose = True
args = [ a for a in args if a != '-v' ]
else:
verbose = False
if len(args) == 0:
usage()
for bug in g_bugs.values():
one_kw_didnt_match = False
title = bug["title"]
lines = bug["description"].split("\n")
bodylines = set([])
# *all* of the keywords must match in order for the
# bug to be displayed
i = 0
for kw in args:
i += 1
this_kw_matched = False
# look for keyword in title
match = grep(title, kw, i)
if match:
bug["title"] = match
title = match
this_kw_matched = True
# look for keyword in description
for j, line in enumerate(lines):
match = grep(line, kw, i)
if match:
bodylines.add(j)
lines[j] = match
this_kw_matched = True
if not this_kw_matched:
one_kw_didnt_match = True
if not one_kw_didnt_match:
list_bug(bug)
if verbose:
for x in sorted(list(bodylines)):
sys.stdout.write(" %s\n" % lines[x])
def main_edit(args):
if len(args) == 0:
ids = str(g_last_bug)
if ids == None:
bail_out("No last bug. Please specify id.")
else:
ids = args[0]
if not os.path.exists(ids):
bail_out("No bug with this id.")
editor = os.getenv("EDITOR")
if not editor:
for p in [ "/usr/bin/editor", "/usr/bin/vim", "/bin/vi" ]:
if os.path.exists(p):
editor = p
break
if not editor:
bail_out("No editor available (please set EDITOR).\n")
if 0 == os.system("%s %s" % (editor, ids)):
git_add(g_bugs[int(ids)])
save_last_bugid(int(ids))
def main_commit(args):
if len(g_modified) == 0:
bail_out("No new or modified bug.")
else:
sys.stdout.write("Commiting:\n")
for id in g_modified:
list_bug(g_bugs[id])
if 0 == os.system("git commit -m 'Updated bug entries %s' ." % (
", ".join(["#%04d" % id for id in g_modified]))):
sys.stdout.write("--> Successfully committed %d bugs.\n" % len(g_modified))
else:
bail_out("Cannot commit.")
def get_bug_ids():
try:
return eval(file('.my_ids', 'r').read())
except:
return []
def invalidate_my_bugid(id):
ids = get_bug_ids()
ids.remove(id)
store_bug_ids(ids)
def store_bug_ids(l):
file('.my_ids', 'w').write(repr(l) + "\n")
def main_fetch_ids(args):
if not args:
sys.stdout.write('You have %d reserved IDs.\n' % (len(get_bug_ids())))
sys.exit(0)
elif len(args) == 1:
num = int(args[0])
else:
usage()
# Get the start bug_id to reserve
try:
first_free = int(eval(file('first_free').read()))
except:
first_free = 0
new_first_free = first_free + num
# Store the bug_ids to reserve
my_ids = get_bug_ids() + range(first_free, first_free + num)
store_bug_ids(my_ids)
# Store the new reserved bug ids
file('first_free', 'w').write(str(new_first_free) + "\n")
sys.stdout.write('Reserved %d additional IDs now. You have %d reserved IDs now.\n' %
(num, len(my_ids)))
if 0 == os.system("git commit -m 'Reserved %d bug IDS' ." % num):
sys.stdout.write("--> Successfully committed reserved bug IDS. Please push it soon!\n")
else:
bail_out("Cannot commit.")
# _
# _ __ ___ __ _(_)_ __
# | '_ ` _ \ / _` | | '_ \
# | | | | | | (_| | | | | |
# |_| |_| |_|\__,_|_|_| |_|
#
goto_bugsdir()
load_config()
load_bugs()
if len(sys.argv) < 2:
usage()
cmd = sys.argv[1]
commands = {
"list" : lambda args: main_list(args, "console"),
"export" : lambda args: main_list(args, "csv"),
"show" : main_show,
"new" : main_new,
"resolve" : main_resolve,
"solve" : main_resolve,
"blame" : main_blame,
"delete" : main_delete,
"grep" : main_grep,
"edit" : main_edit,
"commit" : main_commit,
"ids" : main_fetch_ids,
}
hits = []
for name, func in commands.items():
if name == cmd:
hits = [ (name, func) ]
break
elif name.startswith(cmd):
hits.append((name, func))
if len(hits) < 1:
usage()
elif len(hits) > 1:
sys.stderr.write("Command '%s' is ambigous. Possible are: %s\n" % \
(cmd, ", ".join([ n for (n,f) in hits])))
else:
hits[0][1](sys.argv[2:])