forked from Checkmk/checkmk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
werk
executable file
·1032 lines (826 loc) · 30.5 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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
"""Checkmk development script to manage werks
"""
import argparse
import fcntl
import os
import shutil
import struct
import subprocess
import sys
import termios
import time
import tty
from typing import Dict, List, NoReturn, Optional, Set, Tuple, Union
Werk = Dict[str, str]
RESERVED_IDS_FILE_PATH = f"{os.getenv('HOME')}/.cmk-werk-ids"
# 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 parse_arguments(argv: List[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest="command")
subparsers.required = True
# BLAME
parser_blame = subparsers.add_parser("blame", help="Show who worked on a werk")
parser_blame.add_argument(
"id",
nargs='?',
type=int,
help="werk ID",
default=None,
)
parser_blame.set_defaults(func=main_blame)
# DELETE
parser_delete = subparsers.add_parser("delete", help="delete werk(s)")
parser_delete.add_argument(
"id",
nargs='+',
type=int,
help="werk ID",
)
parser_delete.set_defaults(func=main_delete)
# EDIT
parser_edit = subparsers.add_parser("edit", help="open werk in editor")
parser_edit.add_argument(
"id",
nargs='?',
type=int,
help="werk ID (defaults to newest)",
)
parser_edit.set_defaults(func=main_edit)
# EXPORT
parser_export = subparsers.add_parser("export", help="List werks")
parser_export.add_argument(
"-r",
"--reverse",
action="store_true",
help="reverse order",
)
parser_export.add_argument(
"filter",
nargs="*",
help="filter for edition, component, state, class, knowledge state or target version",
)
parser_export.set_defaults(func=lambda args: main_list(args, "csv"))
# GREP
parser_grep = subparsers.add_parser(
"grep",
help="show werks containing all of the given keywords",
)
parser_grep.add_argument('-v', '--vebose', action='store_true')
parser_grep.add_argument(
"keywords",
nargs='+',
help="keywords to grep",
)
parser_grep.set_defaults(func=main_grep)
# IDS
parser_ids = subparsers.add_parser(
"ids",
help="Show the number of reserved werk IDs or reserve new werk IDs",
)
parser_ids.add_argument(
"count",
nargs='?',
type=int,
help="number of werks to reserve",
)
parser_ids.set_defaults(func=main_fetch_ids)
# KNOWNLEDGE
parser_knowledge = subparsers.add_parser(
"knowledge",
aliases=['knw'],
help="Change the knowlege state of a werk",
)
parser_knowledge.add_argument("id", type=int, help="werk ID")
parser_knowledge.add_argument(
"state",
choices=[c[0] for c in knowledge],
help=("knowlege state of werk. Allowed are %s." %
", ".join("%s (%s)" % c for c in knowledge)),
)
parser_knowledge.set_defaults(func=main_knowledge)
# LIST
parser_list = subparsers.add_parser("list", help="List werks")
parser_list.add_argument(
"-r",
"--reverse",
action="store_true",
help="reverse order",
)
parser_list.add_argument(
"filter",
nargs="*",
help="filter for edition, component, state, class, knowledge state or target version",
)
parser_list.set_defaults(func=lambda args: main_list(args, "console"))
# NEW
parser_new = subparsers.add_parser("new", help="Create a new werk")
parser_new.add_argument(
"custom_files",
nargs='*',
help="files passed to 'git commit'",
)
parser_new.set_defaults(func=main_new)
# PICK
parser_pick = subparsers.add_parser(
"pick",
aliases=["cherry-pick"],
help="Pick these werks",
)
parser_pick.add_argument(
"-n",
"--no-commit",
action="store_true",
help="do not commit at the end",
)
parser_pick.add_argument(
"commit",
nargs='+',
help="Pick these commits",
)
parser_pick.set_defaults(func=main_pick)
# SHOW
parser_show = subparsers.add_parser("show", help="Show several werks")
parser_show.add_argument(
"ids",
nargs='*',
help="Show these werks, or 'all' for all, of leave out for last",
)
parser_show.set_defaults(func=main_show)
# URL
parser_url = subparsers.add_parser("url", help="Show the online URL of a werk")
parser_url.add_argument("id", type=int, help="werk ID")
parser_url.set_defaults(func=main_url)
return parser.parse_args(argv)
def try_migrate_werk_ids():
if not os.path.isfile(RESERVED_IDS_FILE_PATH) and os.path.isfile(".my_ids"):
try:
# migration step to move '.my_ids' to RESERVED_IDS_FILE_PATH
dest = shutil.move(".my_ids", RESERVED_IDS_FILE_PATH)
sys.stdout.write(f'Moved ".my_ids" to {RESERVED_IDS_FILE_PATH}\n')
except Exception:
sys.stderr.write(f'Error: could not move ".my_ids" to {RESERVED_IDS_FILE_PATH}\n')
def get_tty_size() -> Tuple[int, int]:
try:
ws = bytearray(8)
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 OSError:
pass
return (24, 99999)
def bail_out(text: str) -> NoReturn:
sys.stderr.write(text + "\n")
sys.exit(1)
g_base_dir = ""
def goto_werksdir() -> None:
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: Optional[int] = None
def get_last_werk() -> int:
if g_last_werk is None:
bail_out("No last werk known. Please specify id.")
return g_last_werk
def load_config() -> None:
global g_last_werk
with open("config") as f_config:
exec(f_config.read(), globals(), globals())
try:
with open(".last") as f_last:
g_last_werk = int(f_last.read())
except Exception:
g_last_werk = None
g_werks: Dict[int, Werk] = {}
def load_werks() -> None:
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: int) -> None:
try:
with open(".last", "w") as f:
f.write("%d\n" % int(wid))
except OSError:
pass
def load_current_version() -> str:
with open("../defines.make") as f:
for line in f:
if line.startswith("VERSION"):
version = line.split("=", 1)[1].strip()
return version
bail_out("Failed to read VERSION from defines.make")
g_modified: Set[int] = set()
def check_modified() -> None:
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: int) -> bool:
return werkid in g_modified
def werk_exists(werkid: int) -> bool:
return os.path.exists(str(werkid))
def load_werk(werkid: int) -> Werk:
werk: Werk = {
"id": str(werkid),
"state": "unknown",
"title": "unknown",
"component": "general",
"compatible": "compat",
"edition": "cre",
"knowledge": "undoc",
}
with open(str(werkid)) as f:
for line in f:
line = line.strip()
if line == "":
break
header, value = line.split(":", 1)
werk[header.strip().lower()] = value.strip()
werk["description"] = f.read()
versions.add(werk["version"])
return werk
def save_werk(werk: Werk) -> None:
with open(werk["id"], "w") as f:
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"])
git_add(werk)
save_last_werkid(int(werk["id"]))
def change_werk_version(werk_id: int, new_version: str) -> None:
werk = g_werks[werk_id]
werk["version"] = new_version
save_werk(werk)
git_add(werk)
def git_add(werk: Werk) -> None:
os.system("git add %s" % werk["id"]) # nosec
def git_commit(werk: Werk, custom_files: List[str]) -> None:
title = werk["title"]
for classid, _classname, prefix in classes:
if werk["class"] == classid:
if prefix:
title = "%s %s" % (prefix, title)
title = "%s %s" % (werk['id'].rjust(5, '0'), 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() -> str:
info = subprocess.Popen(["git", "rev-parse", "--show-toplevel"], stdout=subprocess.PIPE)
return str(info.communicate()[0].split()[0])
def something_in_git_index() -> bool:
for line in os.popen("git status --porcelain"):
if line[0] == 'M':
return True
return False
def quote_shell_string(s: str) -> str:
return "'" + s.replace("'", "'\"'\"'") + "'"
def next_werk_id() -> int:
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: Werk, title: str, comment: str) -> None:
werk["description"] += """
%s: %s
%s""" % (time.strftime("%F %T"), title, comment)
def num_color(n: int, colors: List[int], inverse: bool) -> str:
if inverse:
b = 40
else:
b = 30
c = colors[n - 1]
return tty_colors([b + c, 1])
def list_werk(werk: Werk) -> None:
if werk_is_modified(int(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: Union[int, str]) -> str:
return tty_bgwhite + tty_blue + ("#%05d" % int(werk_id)) + tty_normal
def format_knw_state(knw_state: str) -> str:
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: str, digits: int) -> str:
if classname == "fix":
return tty_bold + tty_red + ("%-" + str(digits) + "s") % classname + tty_normal
return ("%-" + str(digits) + "s") % classname
def show_werk(werk: Werk) -> None:
list_werk(werk)
sys.stdout.write("\n%s\n" % werk["description"])
def main_list(args: argparse.Namespace, fmt: str) -> None:
# arguments are tags from state, component and class. Multiple values
# in one class are orred. Multiple types are anded.
filters: Dict[str, List] = {}
for a in args.filter:
if a == "current":
a = g_current_version
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: # type: ignore[attr-defined] # all of them are iterable.
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 g_werks.values():
skip = False
for tp, entries in filters.items():
if werk[tp] not in entries:
skip = True
break
if not skip:
newwerks.append(werk)
werks = sorted(newwerks, key=lambda w: int(w["date"]), reverse=args.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: List[Werk]) -> None:
def line(*l):
sys.stdout.write('"' + '";"'.join(map(str, l)) + '"\n')
nr = 1
for entry in components:
if isinstance(entry, tuple) and len(entry) == 2:
name, alias = entry
elif isinstance(entry, str): # TODO: Hmmm...
name, alias = entry, entry
else:
bail_out("invalid component %r" % (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: Werk) -> str:
cl = werk["class"]
for entry in classes:
# typing: why would this be? LH: Tuple[str, str, str], RH: str
if entry == cl: # type: ignore[comparison-overlap]
return cl
if isinstance(entry, tuple) and entry[0] == cl:
return entry[1]
return cl
def werk_effort(werk: Werk) -> int:
return int(werk.get("effort", "0"))
def main_show(args: argparse.Namespace) -> None:
if 'all' in args.ids:
ids = [wid for (wid, _werk) in g_werks.items()]
else:
ids = args.ids or [get_last_werk()]
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: str, default: str = "") -> str:
sys.stdout.write("%s: " % what)
sys.stdout.flush()
value = sys.stdin.readline().strip()
if value == "":
return default
return value
def get_long_input(what):
# type (str) -> str
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() -> str:
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: str, choices: Union[List[str], List[Tuple[str, str]], List[Tuple[str, str,
str]]]) -> str:
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]
sys.stdout.write("\n")
def get_edition_components(edition: str) -> List[Tuple[str, str]]:
return components + edition_components.get(edition, [])
def all_components() -> List[Tuple[str, str]]:
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: argparse.Namespace) -> None:
sys.stdout.write(tty_green + werk_notes + tty_normal)
werk: Werk = {}
werk["id"] = str(next_werk_id())
werk["date"] = str(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[int(werk["id"])] = werk
save_werk(werk)
invalidate_my_werkid(int(werk["id"]))
edit_werk(int(werk["id"]), args.custom_files)
sys.stdout.write("Werk %s saved.\n" % format_werk_id(werk["id"]))
def get_werk_arg(arg: Optional[Union[str, int]]) -> int:
wid = get_last_werk() if arg is None else int(arg)
werk = g_werks.get(wid)
if not werk:
bail_out("No such werk.\n")
save_last_werkid(wid)
return wid
def main_blame(args: argparse.Namespace) -> None:
wid = get_werk_arg(args.id)
os.system("git blame %d" % wid) # nosec
def main_url(args: argparse.Namespace) -> None:
wid = get_werk_arg(args.id)
sys.stdout.write(online_url % wid + "\n")
def main_delete(args: argparse.Namespace) -> None:
werks = args.ids or [get_last_werk()]
for werk_id in werks:
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: str, kw: str, n: int) -> Optional[str]:
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: argparse.Namespace) -> None:
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.keywords:
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 args.verbose:
for x in sorted(list(bodylines)):
sys.stdout.write(" %s\n" % lines[x])
def main_knowledge(args: argparse.Namespace) -> None:
if not werk_exists(args.id):
bail_out("No such werk.")
save_last_werkid(args.id)
werk = load_werk(args.id)
werk["knowledge"] = args.state
save_werk(werk)
def main_edit(args: argparse.Namespace) -> None:
werkid = args.id or get_last_werk()
edit_werk(werkid, None, commit=False) # custom files are pointless if commit=False
save_last_werkid(werkid)
def edit_werk(werkid: int, custom_files: Optional[List[str]] = None, commit: bool = True) -> None:
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_pick(args: argparse.Namespace) -> None:
for commit_id in args.commit:
werk_cherry_pick(commit_id, args.no_commit)
def werk_cherry_pick(commit_id: str, no_commit: bool) -> None:
# First get the werk_id
result = subprocess.run(
["git", "diff-tree", "--no-commit-id", "--name-only", "-r", commit_id],
capture_output=True,
check=True,
)
werk_id = None
for line in result.stdout.splitlines():
filename = line.decode('utf-8')
if filename.startswith(".werks/") and filename[7:].isdigit():
werk_id = int(filename[7:])
if werk_id is not None:
if os.path.exists(str(werk_id)):
bail_out(f"Trying to pick werk {werk_id}, but werk already present. Aborted.")
# Cherry-pick the commit in question from the other branch
cmd = ["git", "cherry-pick"]
if no_commit:
cmd.append("--no-commit")
cmd.append(commit_id)
pick = subprocess.run(cmd, check=False)
# Find werks that have been cherry-picked and change their version
# to our current version
load_werks() # might have changed
if werk_id is not None:
# Change the werk's version before checking the pick return code.
# Otherwise the dev may forget to change the version
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))
if pick.returncode:
# Exit with the result of the pick. This may be a merge conflict, so
# other tools may need to know about this.
sys.exit(pick.returncode)
# Commit
if werk_id is not None:
# This allows for picking regular commits as well
if not no_commit:
subprocess.run(["git", "add", str(werk_id)], check=True)
subprocess.run(["git", "commit", "--no-edit", "--amend"], check=True)
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)
subprocess.run(["git", "status"], check=True)
def get_werk_ids() -> List[int]:
try:
with open(RESERVED_IDS_FILE_PATH, 'r') as f:
return eval(f.read())
except Exception:
return []
def invalidate_my_werkid(wid: int) -> None:
ids = get_werk_ids()
ids.remove(wid)
store_werk_ids(ids)
if not ids:
sys.stdout.write(f"\n{tty_red}This was your last reserved ID.{tty_normal}\n\n")
def store_werk_ids(l: List[int]) -> None:
with open(RESERVED_IDS_FILE_PATH, 'w') as f:
f.write(repr(l) + "\n")
sys.stdout.write(f'Werk IDs stored in the file: {RESERVED_IDS_FILE_PATH}\n')
def current_branch() -> str:
return [l for l in os.popen("git branch") if l.startswith("*")][0].split()[-1]
def main_fetch_ids(args: argparse.Namespace) -> None:
if args.count is None:
sys.stdout.write('You have %d reserved IDs.\n' % (len(get_werk_ids())))
sys.exit(0)
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:
with open('first_free') as f:
first_free = int(f.read().strip())
except (IOError, ValueError):
first_free = 0
new_first_free = first_free + args.count
# 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 + args.count
# 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 + args.count
# 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 + args.count
# Store the werk_ids to reserve
my_ids = get_werk_ids() + list(range(first_free, new_first_free))
store_werk_ids(my_ids)
# Store the new reserved werk ids
with open('first_free', 'w') as f:
f.write(str(new_first_free) + "\n")
sys.stdout.write('Reserved %d additional IDs now. You have %d reserved IDs now.\n' %
(args.count, len(my_ids)))
if os.system("git commit -m 'Reserved %d Werk IDS' ." % args.count) == 0: # nosec