forked from Checkmk/checkmk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
werk
executable file
·952 lines (753 loc) · 26.3 KB
/
werk
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
import fcntl
import os
import struct
import subprocess
import sys
import termios
import time
import tty
from typing import Any, Callable, Dict, List, Optional, Set, Tuple # pylint: disable=unused-import
# 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_bggreen = '\033[42m'
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_bgred = ''
tty_bggreen = ''
tty_bgblue = ''
tty_bgmagenta = ''
tty_bgcyan = ''
tty_bgwhite = ''
tty_bold = ''
tty_underline = ''
tty_normal = ''
tty_ok = 'OK'
def tty_colors(codes):
return ""
grep_colors = [
tty_bold + tty_magenta,
tty_bold + tty_cyan,
tty_bold + tty_green,
]
def get_tty_size():
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 Exception:
pass
return (24, 99999)
def bail_out(text):
sys.stderr.write(text + "\n")
sys.exit(1)
g_base_dir = ""
def goto_werksdir():
global g_base_dir
g_base_dir = os.path.abspath('.')
while not os.path.exists(".werks") and os.path.abspath('.') != '/':
os.chdir("..")
try:
os.chdir(".werks")
except Exception:
sys.stderr.write("Cannot find directory .werks\n")
sys.exit(1)
g_last_werk = None # type: Optional[int]
def load_config():
global g_last_werk
exec (open("config").read(), globals(), globals())
try:
g_last_werk = int(open(".last").read())
except Exception:
g_last_werk = None
g_werks = {} # type: Dict[int, Dict[str, Any]]
def load_werks():
global g_werks
g_werks = {}
check_modified()
for entry in os.listdir("."):
try:
werkid = int(entry)
try:
g_werks[werkid] = load_werk(werkid)
except Exception:
sys.stderr.write("SKIPPING INVALID werk %d\n" % werkid)
except Exception:
continue
def save_last_werkid(wid):
try:
open(".last", "w").write("%d\n" % int(wid))
except Exception:
pass
def load_current_version():
for line in open("../defines.make"):
if line.startswith("VERSION"):
version = line.split("=", 1)[1].strip()
return version
bail_out("Failed to read VERSION from defines.make")
g_modified = set() # type: Set[int]
def check_modified():
global g_modified
g_modified = set([])
for line in os.popen("git status --porcelain"):
if line[0] in "AM" and ".werks/" in line:
try:
wid = line.rsplit("/", 1)[-1].strip()
g_modified.add(int(wid))
except Exception:
pass
def werk_is_modified(werkid):
return werkid in g_modified
def werk_exists(werkid):
return os.path.exists(str(werkid))
def load_werk(werkid):
werk = {
"id": werkid,
"state": "unknown",
"title": "unknown",
"component": "general",
"compatible": "compat",
"edition": "cre",
"knowledge": "undoc",
}
f = open(str(werkid))
for line in f:
line = line.strip()
if line == "":
break
header, value = line.split(":", 1)
werk[header.strip().lower()] = value.strip()
description = ""
for line in f:
description += line
werk["description"] = description
versions.add(werk["version"])
return werk
def save_werk(werk):
f = open(str(werk["id"]), "w")
f.write("Title: %s\n" % werk["title"])
for key, val in sorted(werk.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(werk["description"])
f.close()
git_add(werk)
save_last_werkid(werk["id"])
def change_werk_version(werk_id, new_version):
werk = g_werks[werk_id]
werk["version"] = new_version
save_werk(werk)
git_add(werk)
def git_add(werk):
os.system("git add %d" % werk["id"]) # nosec
def git_commit(werk, custom_files):
title = werk["title"]
for classid, _classname, prefix in classes:
if werk["class"] == classid:
if prefix:
title = "%s %s" % (prefix, title)
title = "%05d %s" % (werk['id'], title)
if custom_files:
files_to_commit = custom_files
default_files = [".werks"]
for entry in default_files:
files_to_commit.append("%s/%s" % (git_top_level(), entry))
os.chdir(g_base_dir)
cmd = "git commit %s -m %s" % (" ".join(files_to_commit),
quote_shell_string(title + "\n\n" + werk["description"]))
os.system(cmd) # nosec
else:
if something_in_git_index():
dash_a = ''
os.system("cd '%s' ; git add .werks" % git_top_level()) # nosec
else:
dash_a = '-a'
cmd = "git commit %s -m %s" % (dash_a,
quote_shell_string(title + "\n\n" + werk["description"]))
os.system(cmd) # nosec
def git_top_level():
info = subprocess.Popen(["git", "rev-parse", "--show-toplevel"], stdout=subprocess.PIPE)
return info.communicate()[0].split()[0]
def something_in_git_index():
for line in os.popen("git status --porcelain"):
if line[0] == 'M':
return True
return False
def quote_shell_string(s):
return "'" + s.replace("'", "'\"'\"'") + "'"
def next_werk_id():
my_werk_ids = get_werk_ids()
if not my_werk_ids:
bail_out(
'You have no werk IDS left. You can reserve 10 additional Werk IDS with "./werk ids 10".'
)
return my_werk_ids[0]
def add_comment(werk, title, comment):
werk["description"] += """
%s: %s
%s""" % (time.strftime("%F %T"), title, comment)
def usage():
sys.stdout.write("""Usage: werk COMMAND [ARGS...]
where COMMAND is one of:
ids [#] - Shows the number of reserved werk IDS. With a number
given as parameter the command will reserve new werk IDS.
list [-r] [STATE] - list werks (-r: reverse)
new - create a new werk
show [# #..] - show several werks, or 'all' for all, of leave out for last
delete #.. - delete werk(s)
grep [-v] KW1 KW2... - show werks containing all of the given keywords (-v: verbose)
edit [#] - open werk # in editor (or newest werk)
knowledge|knw ID STATE - change the knowlege state of a werk
blame [#] - show who worked on a werk
url # - show the online URL of werk #
""")
sys.exit(1)
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_werk(werk):
if werk_is_modified(werk["id"]):
bold = tty_bold + tty_cyan + "(*) "
else:
bold = ""
_lines, cols = get_tty_size()
title = werk["title"][:cols - 45]
sys.stdout.write(
"%s %-9s %s %s %3s %-13s %-6s %s%s%s %-8s %s%s%s\n" %
(format_werk_id(werk["id"]), time.strftime(
"%F", time.localtime(int(werk["date"]))), colored_class(werk["class"], 8),
format_knw_state(werk["knowledge"]) if werk["class"] == "feature" else " ",
werk["edition"], werk["component"], werk["compatible"], tty_bold, werk["level"],
tty_normal, werk["version"], bold, title, tty_normal))
def format_werk_id(werk_id):
return tty_bgwhite + tty_blue + ("#%05d" % int(werk_id)) + tty_normal
def format_knw_state(knw_state):
return {
"undoc": tty_bgblue + tty_white + tty_bold + "?D?" + tty_normal,
"todoc": tty_bgred + tty_white + tty_bold + "!D!" + tty_normal,
"doc": tty_bggreen + tty_white + tty_bold + " D " + tty_normal,
}.get(knw_state, knw_state)
def colored_class(classname, digits):
if classname == "fix":
return tty_bold + tty_red + ("%-" + str(digits) + "s") % classname + tty_normal
return ("%-" + str(digits) + "s") % classname
def show_werk(werk):
list_werk(werk)
sys.stdout.write("\n%s\n" % werk["description"])
def main_list(args, fmt):
werks = g_werks.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: (a['date'] > b['date']) - (a['date'] < b['date'])
reverse = False
for a in args:
if a == "current":
a = g_current_version
if a == '-r':
reverse = True
continue
hit = False
for tp, values in [("edition", editions), ("component", all_components()),
("level", levels), ("class", classes), ("version", versions),
("compatible", compatible), ("knowledge", knowledge)]:
for v in values:
if isinstance(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 edition, component, state, class, knowledge state or target version: %s" %
a)
# Filter
newwerks = []
for werk in werks:
skip = False
for tp, entries in filters.items():
if werk[tp] not in entries:
skip = True
break
if not skip:
newwerks.append(werk)
werks = newwerks
newwerks.sort(sort)
if reverse:
newwerks.reverse()
# Output
if fmt == "console":
for werk in werks:
list_werk(werk)
else:
output_csv(werks)
# CSV Table has the following columns:
# Component;ID;Title;Class;Effort
def output_csv(werks):
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 werk in werks:
if werk["component"] == name:
total_effort += werk_effort(werk)
line("", "%d. %s" % (nr, alias), "", total_effort)
nr += 1
for werk in werks:
if werk["component"] == name:
line(werk["id"], werk["title"], werk_class(werk), werk_effort(werk))
line("", werk["description"].replace("\n", " ").replace('"', "'"), "", "")
def werk_class(werk):
cl = werk["class"]
for entry in classes:
if entry == cl:
return cl
elif isinstance(entry, tuple) and entry[0] == cl:
return entry[1]
return cl
def werk_effort(werk):
return int(werk.get("effort", "0"))
def main_show(args):
ids = args
if len(ids) == 0:
if g_last_werk is None:
bail_out("No last werk known. Please specify id.")
ids = [g_last_werk]
elif ids[0] == 'all':
ids = [wid for (wid, _werk) in g_werks.items()]
for wid in ids:
if wid != ids[0]:
sys.stdout.write(
"-------------------------------------------------------------------------------\n")
try:
show_werk(g_werks[int(wid)])
except Exception:
sys.stderr.write("Skipping invalid werk id '%s'\n" % wid)
save_last_werkid(ids[-1])
def get_input(what, default=""):
sys.stdout.write("%s: " % what)
sys.stdout.flush()
value = sys.stdin.readline().strip()
if value == "":
return default
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):
next_index = 0
ctc = {}
texts = []
for choice in choices:
if isinstance(choice, tuple):
choice = choice[0]
added = False
# Find an identifying character for the input choice. In case all possible
# characters are already used start using unique numbers
for c in str(choice):
if c not in ".-_/" and c not in ctc:
ctc[c] = choice
texts.append(str(choice).replace(c, tty_bold + c + tty_normal, 1))
added = True
break
if not added:
ctc["%s" % next_index] = choice
texts.append("%s:%s" % ("%s%d%s" % (tty_bold, next_index, tty_normal), choice))
next_index += 1
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 get_edition_components(edition):
return components + edition_components.get(edition, [])
def all_components():
c = components
for ed_components in edition_components.values():
c += ed_components
return components
werk_notes = """
.---Werk----------------------------------------------------------------------.
| |
| Das Werk ist für den User/Admin gedacht!! |
| |
| Anhand des Titels soll der User sofort erkennen, ob er/sie betroffen ist. |
| In den Details soll beschrieben werden, was er/sie ggfs. tun muss. |
| Es dürfen auch gerne technische Details erläutert werden. |
| |
'-----------------------------------------------------------------------------'
"""
def main_new(args):
sys.stdout.write(tty_green + werk_notes + tty_normal)
werk = {}
werk["id"] = next_werk_id()
werk["date"] = int(time.time())
werk["version"] = g_current_version
werk["title"] = get_input("Title")
if werk["title"] == "":
sys.stderr.write("Cancelled.\n")
sys.exit(0)
werk["class"] = input_choice("Class", classes)
werk["edition"] = input_choice("Edition", editions)
werk["component"] = input_choice("Component", get_edition_components(werk["edition"]))
werk["level"] = input_choice("Level", levels)
werk["compatible"] = input_choice("Compatible", compatible)
if werk["class"] == "feature":
werk["knowledge"] = "undoc" # Don't ask. Developers must not deal with this
else:
werk["knowledge"] = "doc" # Bug and security fixes never get documented in user manual
werk["description"] = u"\n"
g_werks[werk["id"]] = werk
save_werk(werk)
invalidate_my_werkid(werk["id"])
edit_werk(werk["id"], args)
sys.stdout.write("Werk %s saved.\n" % format_werk_id(werk["id"]))
def get_werk_arg(args):
if len(args) == 0:
if g_last_werk is None:
bail_out("No last werk, please specify id.")
wid = g_last_werk
else:
if len(args) != 1:
usage()
wid = int(args[0])
werk = g_werks.get(wid)
if not werk:
bail_out("No such werk.\n")
save_last_werkid(wid)
return wid
def main_blame(args):
wid = get_werk_arg(args)
os.system("git blame %d" % wid) # nosec
def main_url(args):
wid = get_werk_arg(args)
sys.stdout.write(online_url % wid + "\n")
def main_delete(args):
if len(args) == 0:
if g_last_werk is None:
bail_out("Please specify the werks to delete.")
args = [g_last_werk]
for werk_id in args:
if not werk_exists(werk_id):
bail_out("There is no werk %s." % format_werk_id(werk_id))
if os.system("git rm -f %s" % werk_id) == 0: # nosec
sys.stdout.write("Deleted werk %s (%s).\n" %
(format_werk_id(werk_id), g_werks[int(werk_id)]["title"]))
my_ids = get_werk_ids()
my_ids.append(werk_id)
store_werk_ids(my_ids)
sys.stdout.write("You lucky bastard now own the werk ID %s.\n" %
format_werk_id(werk_id))
def grep(line, kw, n):
lc = kw.lower()
i = line.lower().find(lc)
if i == -1:
return None
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 werk in g_werks.values():
one_kw_didnt_match = False
title = werk["title"]
lines = werk["description"].split("\n")
bodylines = set([])
# *all* of the keywords must match in order for the
# werk 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:
werk["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_werk(werk)
if verbose:
for x in sorted(list(bodylines)):
sys.stdout.write(" %s\n" % lines[x])
def main_knowledge(args):
if len(args) != 2:
bail_out("Usage: werk knowledge ID undoc|todoc|doc")
werkid = args[0]
if not werk_exists(werkid):
bail_out("No such werk.")
werkid = int(werkid)
save_last_werkid(werkid)
knw_state = args[1]
if knw_state not in [c[0] for c in knowledge]:
bail_out("Invalid knowledge state. Allowed are %s." %
", ".join(["%s (%s)" % c for c in knowledge]))
werk = load_werk(werkid)
werk["knowledge"] = knw_state
save_werk(werk)
def main_edit(args):
if len(args) == 0:
werkid = int(g_last_werk)
if werkid is None:
bail_out("No last werk. Please specify id.")
else:
try:
werkid = int(args[0])
args = args[1:]
except Exception:
werkid = int(g_last_werk)
if werkid is None:
bail_out("No last werk. Please specify id.")
edit_werk(werkid, args, commit=False)
save_last_werkid(werkid)
def edit_werk(werkid, custom_files=None, commit=True):
if custom_files is None:
custom_files = []
if not os.path.exists(str(werkid)):
bail_out("No werk 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 os.system("bash -c '%s +11 %s'" % (editor, werkid)) == 0: # nosec
load_werks()
werk = g_werks[werkid]
git_add(g_werks[werkid])
if commit:
git_commit(werk, custom_files)
def main_commit(args):
if len(g_modified) == 0:
bail_out("No new or modified werk.")
else:
sys.stdout.write("Commiting:\n")
for wid in g_modified:
list_werk(g_werks[wid])
cmd = "git commit -m 'Updated werk entries %s' ." % (", ".join(
["#%05d" % wid for wid in g_modified]))
if os.system(cmd) == 0: # nosec
sys.stdout.write("--> Successfully committed %d werks.\n" % len(g_modified))
else:
bail_out("Cannot commit.")
def main_pick(args):
if len(args) == 0:
bail_out("Please specify at least one commit ID to cherry-pick.")
if args[0] == '-n':
no_commit = True
args = args[1:]
else:
no_commit = False
for commit_id in args:
werk_cherry_pick(commit_id, no_commit)
def werk_cherry_pick(commit_id, no_commit):
# Cherry-pick the commit in question from the other branch
os.system("git cherry-pick --no-commit '%s'" % commit_id) # nosec
# Find werks that have been cherry-picked and change their version
# to our current version
load_werks() # might have changed
for line in os.popen("git status --porcelain"): # nosec
# M .werks/103
# M werk
_status, filename = line.strip().split(None, 1)
if filename.startswith(".werks/") and filename[7].isdigit():
werk_id = int(filename[7:])
change_werk_version(werk_id, g_current_version)
sys.stdout.write("Changed version of werk %s to %s.\n" %
(format_werk_id(werk_id), g_current_version))
# Commit
if not no_commit:
os.system("git commit -C '%s'" % commit_id) # nosec
else:
sys.stdout.write("We don't commit yet. Here is the status:\n")
sys.stdout.write("Please commit with git commit -C '%s'\n\n" % commit_id)
os.system("git status")
def get_werk_ids():
try:
return eval(open('.my_ids', 'r').read())
except Exception:
return []
def invalidate_my_werkid(wid):
ids = get_werk_ids()
ids.remove(wid)
store_werk_ids(ids)
def store_werk_ids(l):
open('.my_ids', 'w').write(repr(l) + "\n")
def current_branch():
return [l for l in os.popen("git branch") if l.startswith("*")][0].split()[-1]
def main_fetch_ids(args):
if not args:
sys.stdout.write('You have %d reserved IDs.\n' % (len(get_werk_ids())))
sys.exit(0)
elif len(args) == 1:
num = int(args[0])
else:
usage()
if current_branch() != "master":
bail_out("It is not allowed to reserve IDs on any other branch than the master.")
# Get the start werk_id to reserve
try:
first_free = int(open('first_free').read().strip())
except (IOError, ValueError):
first_free = 0
new_first_free = first_free + num
# enterprise werks were between 8000 and 8749. Skip over this area for new
# reserved werk ids
if 8000 <= first_free < 8780 or 8000 <= new_first_free < 8780:
first_free = 8780
new_first_free = first_free + num
# cmk-omd werk were between 7500 and 7680. Skip over this area for new
# reserved werk ids
if 7500 <= first_free < 7680 or 7500 <= new_first_free < 7680:
first_free = 7680
new_first_free = first_free + num
# cma werks are between 9000 and 9999. Skip over this area for new
# reserved werk ids
if 9000 <= first_free < 10000 or 9000 <= new_first_free < 10000:
first_free = 10000
new_first_free = first_free + num
# Store the werk_ids to reserve
my_ids = get_werk_ids() + range(first_free, new_first_free)
store_werk_ids(my_ids)
# Store the new reserved werk ids
open('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 os.system("git commit -m 'Reserved %d Werk IDS' ." % num) == 0: # nosec
sys.stdout.write("--> Successfully committed reserved werk IDS. Please push it soon!\n")
else:
bail_out("Cannot commit.")
# _
# _ __ ___ __ _(_)_ __
# | '_ ` _ \ / _` | | '_ \
# | | | | | | (_| | | | | |
# |_| |_| |_|\__,_|_|_| |_|
#
# default config
editions = [] # type: List[Tuple[str,str]]
components = [] # type: List[Tuple[str,str]]
edition_components = {} # type: Dict[str, List[Tuple[str,str]]]
classes = [] # type: List[Tuple[str,str]]
levels = [] # type: List[Tuple[str,str]]
compatible = [] # type: List[Tuple[str,str]]
knowledge = [] # type: List[Tuple[str,str]]
online_url = ""
versions = set([]) # type: Set[str]
goto_werksdir()
load_config()
load_werks()
g_current_version = load_current_version()
if len(sys.argv) < 2:
usage()
cmd_arg = sys.argv[1]
commands = {
"list": lambda args: main_list(args, "console"),
"export": lambda args: main_list(args, "csv"),
"show": main_show,
"new": main_new,
"blame": main_blame,
"delete": main_delete,
"grep": main_grep,
"edit": main_edit,
"knowledge": main_knowledge,
"knw": main_knowledge,
"ids": main_fetch_ids,
"pick": main_pick,
"cherry-pick": main_pick,
"url": main_url,
}
hits = [] # type: List[Tuple[str,Callable[[List[str]], None]]]
for cmd_name, func in commands.items():
if cmd_name == cmd_arg:
hits = [(cmd_name, func)]
break
elif cmd_name.startswith(cmd_arg):
hits.append((cmd_name, func))
if len(hits) < 1:
usage()
elif len(hits) > 1:
sys.stderr.write("Command '%s' is ambigous. Possible are: %s\n" % \
(cmd_arg, ", ".join([ candidate for (candidate,_f) in hits])))
else:
hits[0][1](sys.argv[2:])