-
Notifications
You must be signed in to change notification settings - Fork 0
/
project
executable file
·2311 lines (2040 loc) · 75.9 KB
/
project
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 -S python3 -B
# For copyright and license terms, see COPYRIGHT.rst (top level of repository)
# Repository: https://github.com/C3S/collecting_society_docker
import os
import sys
import shutil
from fileinput import FileInput
import traceback
import subprocess
import argparse
from functools import wraps
import pprint
from subprocess import STDOUT as stdout
from pathlib import Path
import difflib
import re
import yaml
from collections.abc import Mapping
from collections import OrderedDict
from copy import deepcopy
# regex
env_re = re.compile(r'''^([^\s=]+)=(?:[\s"']*)(.+?)(?:[\s"']*)$''')
envsub_re = re.compile(r'\$\{([A-Z-_]*)\}')
commit_re = re.compile(r'\s*(\w*\.\.\w*)\s')
# lists
_contexts = [] # list of contexts
_messages = [] # list of messages added
_tasks = [] # list of tasks performed
_actions = [] # list of valid action names, autofilled
_commands = [] # list of valid command names, autofilled
_commitids = {} # dict of reponame: old commit id, new commit id
# --- tools -------------------------------------------------------------------
def get_root_dir():
"""Returns the root directory of the project."""
root = os.path.realpath(os.path.join(os.path.abspath(__file__), ".."))
assert os.path.exists(os.path.join(root, '.git'))
return root
def get_repo_name(path="."):
"""Returns the repository name of the project."""
return os.path.basename(os.path.abspath(path))
def get_repo_branch(path="."):
return subprocess.check_output(
('git', 'rev-parse', '--abbrev-ref', 'HEAD'),
stderr=subprocess.STDOUT).rstrip().decode('utf-8')
def replace_env_vars(dictionary, env):
"""Substitues placeholders in dictionary with environment variables."""
for key, val in dictionary.items():
if isinstance(val, Mapping):
replace_env_vars(val, env)
elif isinstance(val, list):
for i, item in enumerate(val):
if isinstance(item, str):
for (match) in envsub_re.findall(item):
dictionary[key][i] = dictionary[key][i].replace(
'${%s}' % match, env[match])
continue
replace_env_vars(item, env)
elif isinstance(val, str):
for (match) in envsub_re.findall(val):
dictionary[key] = dictionary[key].replace(
'${%s}' % match, env[match])
return dictionary
def get_dot_env(path="."):
"""Reads the shared environment file and parses it into a dictionary."""
path = os.path.join(path, ".env")
if not os.path.isfile(path):
shutil.copyfile('.env.example', '.env')
assert os.path.isfile(path)
env = {}
with open(path) as _file:
for line in _file:
match = env_re.match(line)
if match is not None:
env[match.group(1)] = match.group(2)
return replace_env_vars(env, env)
def get_project_yaml(path=".", env={}):
"""Reads the project yaml file and parses it into a dictionary."""
with open(os.path.join(path, "project.yml"), 'r') as _file:
# load yaml file
project = yaml.safe_load(_file)
replace_env_vars(project, env)
# environment preparation
for _e, environment in project.items():
for action in _actions:
if 'actions' not in environment:
environment['actions'] = {}
if action not in environment['actions']:
environment['actions'][action] = {}
if 'verbose' not in environment['actions'][action]:
environment['actions'][action]['verbose'] = False
# inherit configurations
project['staging'] = merge_dicts(
deepcopy(project['production']), project['staging'])
project['testing'] = merge_dicts(
deepcopy(project['staging']), project['testing'])
project['development'] = merge_dicts(
deepcopy(project['testing']), project['development'])
# environment validation
for _e, environment in project.items():
if not environment:
continue
# action groups
groups = environment.get('actions', {})
for _g, group in groups.items():
if not isinstance(group, list):
continue
# valid actions in action groups
for action in group:
assert action in _actions, (
"action `%s` in group `%s` not found.\n\n"
"yaml: %s/actions/%s\n"
"group: %s" % (action, _g, _e, action, group)
)
continue
# tasks
tasks = environment.get('tasks', {})
for _c, tasks in environment.get('tasks', {}).items():
for task in tasks or []:
# ensure task name
assert task.get('name'), (
"task has no name.\n\n"
"yaml: %s/tasks/%s\n"
"task: %s" % (_e, _c, task)
)
# ensure task action
assert task.get('actions'), (
"task has no action.\n\n"
"yaml: %s/tasks/%s\n"
"task: %s" % (_e, _c, task)
)
# ensure task actions are a list
actions = task.get('actions', [])
if isinstance(actions, str):
task['actions'] = [actions]
# substitue task groups
actions = []
for action in task['actions']:
islist = isinstance(groups.get(action), list)
if action in groups and islist:
actions += groups[action]
continue
actions.append(action)
task['actions'] = actions
# ensure task actions are valid
for action in task.get('actions', []):
assert action in _actions, (
"action `%s` of task with name `%s` not found.\n\n"
"yaml: %s/tasks/%s\n"
"task: %s" % (action, task['name'], _e, _c, task)
)
# batch tasks
if not task.get('batch'):
continue
for batch_task in task['batch']:
# ensure task name
assert batch_task.get('name'), (
"task has no name.\n\n"
"yaml: %s/tasks/%s\n"
"task: %s" % (_e, _c, batch_task)
)
# ensure task actions are valid
for action in batch_task.get('actions', []):
assert action in _actions, (
"action `%s` of batch task with name `%s` "
"in task with name %s not found.\n\n"
"yaml: %s/tasks/%s\n"
"task: %s\n"
"batch_task: %s" % (
action, batch_task['name'], task['name'],
_e, _c, task, batch_task)
)
return project
def merge_dicts(orig_dict, new_dict):
"""
Recursively merges dict-like objects.
Note:
If a value in new_dict is `{}`, the key is removed in orig_dict.
Lists of dicts
- are merged with key 'name' as identifier.
- can be inserted with the key 'before'/'after' and value name.
Args:
orig_dict (dict): Original dictionary to be merged with.
new_dict (dict): New dictionary to be merged.
Returns:
dict: Merged dict.
Examples:
>>> orig_dict = {
... 'A': {
... 'A1': 'A1',
... 'A2': 'A2'
... },
... 'B': 'B'
... 'C': [
... {'name': 'one', 'item': 'old'},
... {'name': 'three'},
... ]
... }
>>> new_dict = {
... 'A': {
... 'A2': 'XX'
... },
... 'B': {},
... 'C': [
... {'name': 'one', 'item': 'new'},
... {'name': 'two', 'after': 'one'},
... 'D': 'D'
... }
>>> print(cls.merge_dicts(orig_dict, new_dict))
{
'A': {
'A1': 'A1',
'A2': 'XX'
},
'C': [
{'name': 'one', 'item': 'new'},
{'name': 'two'},
{'name': 'three'},
],
'D': 'D',
}
"""
if not new_dict:
return isinstance(new_dict, Mapping) and new_dict or orig_dict
for key, val in new_dict.items():
# delete key if val == {}
if isinstance(val, Mapping) and not val:
orig_dict.pop(key, None)
# update with OrderedDict
if isinstance(val, OrderedDict):
r = merge_dicts(OrderedDict(orig_dict.get(key, {})), val)
orig_dict[key] = r
# update with Mapping
elif isinstance(val, Mapping):
r = merge_dicts(orig_dict.get(key, {}), val)
orig_dict[key] = r
# update with Lists of items having all the key 'name'
elif isinstance(val, list) and \
sum(['name' in v for v in val]) == len(val):
for new_item in val:
new = True
for i, orig_item in enumerate(orig_dict[key]):
if new_item['name'] == orig_item['name']:
new = False
orig_dict[key][i] = merge_dicts(orig_item, new_item)
if new:
insert = ''
if 'after' in new_item:
insert = 'after'
if 'before' in new_item:
insert = 'before'
if insert:
for i, orig_item in enumerate(orig_dict[key]):
if new_item[insert] == orig_item['name']:
break
if insert == 'after':
i += 1
new_item.pop('after', None)
new_item.pop('before', None)
orig_dict[key].insert(i, new_item)
else:
orig_dict[key].append(new_item)
# update with other objects
elif isinstance(orig_dict, Mapping):
orig_dict[key] = new_dict[key]
else:
orig_dict = {key: new_dict[key]}
return orig_dict
# --- templates ---------------------------------------------------------------
def color(text, status):
"""Colored output wrapper for stdout text."""
if _colorless:
return text
text = str(text)
if isinstance(status, str):
status = [status]
# start
for s in status:
s = s.lower()
if s.startswith("\033"):
text = s + text
if s in colors:
text = color(text, colors[s])
# stop
if text.startswith("\033") and not text.endswith("[0m"):
text += colors['clear']
return text
def color_git_status(output):
"""Colores git status output."""
_color = ''
clean = True
data = colors['clear']
for line in output.split("\n"):
if line.startswith(" ("):
_color = 'remove'
if 'reset' in line:
_color = 'add'
if not line.startswith("\t"):
data += color(line, 'dim') + "\n"
continue
clean = False
data += color(line, _color) + "\n"
return data.rstrip(), clean
def color_file_diff(output):
"""Colores file diff output."""
data = colors['clear']
for line in output.split("\n"):
if line.startswith('-'):
data += colors['remove']
elif line.startswith('+'):
data += colors['add']
elif line.startswith('@'):
data += colors['hunk']
else:
data += colors['dim']
data += line + colors['clear'] + "\n"
return data.rstrip()
def message(msg, offset=1, pad=10, data=True, add=True, output=True, end="\n"):
"""Prints a message."""
# default
default = {'level': "debug"}
if _tasks:
default['action'] = _tasks[-1]['action'].replace("_", " ")
default['title'] = _tasks[-1]['name']
msg = {**default, **msg}
# color
_color = msg.get("level", "dim")
# level
text = " " * offset
level = (msg['level'] + " | ").rjust(pad)
text += color(level, _color + "_level")
# title
if 'title' in msg:
title = msg['title']
if title == ".":
title = repo
text += color(title, _color + "_title") + " "
# action
action = ""
if 'action' in msg:
action = msg['action']
if msg['level'] == "error":
action = msg['action']
if 'description' in msg:
action = msg['action'] + " » "
text += color(action, _color + "_action")
# description
if 'description' in msg:
if msg['level'] == 'error':
_color = 'info'
text += color(msg["description"], [_color + "_description", 'italic'])
# data
if data and 'data' in msg and msg['data']:
raw = msg['data']
if isinstance(raw, (bytes, bytearray)):
raw = raw.strip().decode('utf-8')
lines = raw
if isinstance(raw, str):
lines = raw.rstrip().split("\n")
else:
lines = pprint.pformat(raw).split("\n")
data = ""
for line in lines:
data += "\n" + " " * offset + " ".ljust(pad) + line
text += color(data, _color + "_data")
text += "\n"
if action and not action.endswith(" ... "):
text += end
# process
if add:
_messages.append(msg)
if output and msg['level'] in levels['output']:
print(text, end="")
return text
def line(length=89, _color="title", end="\n", output=True):
"""Prints a division line."""
text = color("-" * length, _color)
# process
if output:
print(text, end=end)
return text
def header(output=True):
"""Prints the project configuration header."""
context = get_context()
# data
data = {
"project": env.get('PROJECT'),
"environment": environment,
"branch": branch,
"root": root,
"gituser": git_data,
}
# text
pad = 0
for key in data:
if len(key) > pad:
pad = len(key)
pad += 1
text = "\n"
for key, value in data.items():
value_color = 'dim'
if key in ['environment', 'branch'] and value not in environments:
value_color = 'warning'
text += (
color(" " + key.capitalize().ljust(pad), 'title') +
color(value + "\n", value_color)
)
separator = line(output=False)
text = "\n" + separator + "\n" + text + "\n" + separator + "\n\n"
# extended mode
extended = context['commands'].get('extended')
if not extended:
text = "\n"
# no output after restart
if _restarted:
text = ""
# process
if output:
print(text, end="")
return text
def title(string, _color="subtitle", output=True):
"""Prints a formatted title."""
text = color("> ", 'title') + color(string, _color) + "\n\n"
# process
if output:
print(text, end="")
return text
def footer(string="Success.", _color="success", output=True, summary=True):
"""Prints the result of the command and a summary of important messages."""
context = get_context()
# add user note
if not git_name or not git_email:
message({'level': "info", 'title': ".env", "action": "",
'description': "GIT_USER_NAME/EMAIL not set",
'data': "NOTE: commits will use `%s`" % git_data})
# add commit ids
if _command == "update" and _commitids:
pad = 0
for repo in _commitids:
if len(repo) > pad:
pad = len(repo)
data = ""
for repo, commitids in _commitids.items():
data += (repo + ": ").ljust(pad + 2)
old = commitids.get('old')
new = commitids.get('new')
if new == old:
new = False
if not new:
data += " " * 11 + old
else:
data += old + " -> " + new
data += "\n"
message({'level': "note", 'title': "project repos",
'action': "commit ids", 'data': data}, add=False)
# determine what to output
had_output = 0
has_summary = False
for msg in _messages:
if msg['level'] in levels['output']:
had_output += 1
if msg.get('data'):
had_output += str(msg['data']).count("\n") + 2
if msg['level'] in levels['summary']:
has_summary = True
if not had_output:
print(color(" All fine.", 'dim'))
if had_output < 50:
summary = False
# separator
text = line(output=False) + "\n\n"
# summary
if summary and has_summary:
text += title("Summary", _color='title', output=False)
for level in levels['summary']:
for msg in [m for m in _messages if m['level'] == level]:
text += message(
msg, data=msg['level'] == "note", add=False, output=False)
# title
text += title(string, _color=_color, output=False)
# extended mode
extended = context['commands'].get('extended')
if not extended:
text = ""
# process
if output:
print(text, end="")
return text
def debug(obj=None, title=""):
"""Prints objects for debugging."""
if not _debug:
return
pad = 12
# title
if title:
print(" " * pad + color(title, ['output', 'bold']))
# object
if not isinstance(obj, str):
obj = pprint.pformat(obj)
if not obj:
obj = color("output was empty", 'italic')
for line in obj.split("\n"):
print(" " * pad + color(line, 'output'))
print()
def error(msg):
"""Prints an error."""
_msg = {
'level': "error",
}
if _tasks:
_msg['title'] = "%s: `%s`" % (
_tasks[-1]['action'].replace("_", " "), _tasks[-1]['name'])
message({**_msg, **msg})
footer("Aborted.", _color="info", summary=False)
sys.exit(-1)
# --- execution ---------------------------------------------------------------
def execute(cmd, cwd=False, abort=True, reraise=False, msg={},
stop_batch_group=False, stop_action_group=False):
"""Executes a command via subprocess check_output."""
# print hint for the operation
context = get_context()
task = None
action = "command"
title = " ".join(cmd)
if _tasks:
task = _tasks[-1]
action = task['action'].replace("_", " ") or "command"
title = task['name'] or " ".join(cmd)
waiting = False
if msg or _debug:
message({'action': action + " ... ", 'title': title}, add=False)
waiting = 'debug' in levels['output']
output = ""
error_msg = {}
# execute command
try:
output = subprocess.check_output(
cmd, cwd=cwd or root, stderr=stdout
).rstrip().decode('utf-8')
if _debug:
debug(output, "$ " + " ".join(cmd))
except subprocess.CalledProcessError as err:
error_msg = {
'title': "$ " + cmd[0],
'action': len(cmd) > 1 and " ".join(cmd[1:]) or "",
'data': err.output,
}
if reraise:
raise err
if abort:
error(error_msg)
# add output to task
if context['task']:
context['task']['output'][" ".join(cmd)] = output
context['task']['result'][context['action']] = output
# stop batch groups
if task and stop_batch_group:
stopped = output
if callable(stop_batch_group):
stopped = stop_batch_group(output)
context['batch_group']['stopped'] = stopped
# stop action groups
if task and stop_action_group:
stopped = output
if callable(stop_action_group):
stopped = stop_action_group(output)
context['action_group']['stopped'] = stopped
# return if logging is disabled for this command
if not msg:
return output
# create message
_msg = {
'level': output and "warning" or "info",
'action': action,
'title': title,
'description': output and "not ok" or "ok",
'data': output and "$ " + " ".join(cmd) + "\n" + output,
}
msg = {**_msg, **msg, **error_msg}
# execute callback functions for messages dependent on the output
for key, value in msg.items():
if callable(value):
msg[key] = value(output)
# remove line, add and print message
if waiting and not _debug:
sys.stdout.write("\033[F")
message(msg)
return output
# --- actions -----------------------------------------------------------------
def action(func):
"""Action decorator, registers available functions, skips stopped tasks."""
current_action = func.__name__
# add action name to list of actions
_actions.append(current_action)
@wraps(func)
def wrapper(task, context={}, *args, **kwargs):
# get last context, if empty
if not context:
context = get_context()
# context might stell be empty, if action is used very early
if context:
# stop to process stopped action groups or batch groups
if context['batch_group'].get("stopped"):
return
if context['action_group'].get("stopped"):
return
# set the context
actions = project[environment]['actions']
if current_action not in actions:
actions[current_action] = {}
context['actions'] = actions[current_action]
context['action'] = current_action
if 'output' not in context['task']:
context['task']['output'] = {}
if 'result' not in context['task']:
context['task']['result'] = {}
# apply the action
try:
func(task, context, *args, **kwargs)
except Exception:
error({'data': traceback.format_exc()})
return wrapper
@action
def path_link(task, context={}):
"""Symlinks a file or folder."""
source = task['source']
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
# source path does not exist
if not os.path.exists(source):
message({'level': "info", 'description': "source path not found",
'data': "source: %s" % task['source']})
# new symlink, file does not exist
source_rel = os.path.relpath(source, os.path.dirname(target))
if not os.path.exists(target) and not os.path.islink(target):
os.symlink(source_rel, target)
message({'level': "info", 'description': "symlink created"})
return
# file exists, but is no symlink
if not os.path.islink(target):
error({'description': "target exists and is not a link"})
# symlink exists and points already to source
old_source = os.readlink(target)
if source_rel == old_source:
message({'description': "symlink exists"})
return
# symlink exists, but is changed
os.unlink(target)
os.symlink(source_rel, target)
message({'level': "warning", 'description': "symlink overwritten",
'data': "\n".join(["old source: `%s`" % old_source,
"new source: `%s`" % source_rel])})
@action
def file_create(task, context={}):
"""Creates a file."""
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
target = os.path.join(root, target)
target_folder = os.path.dirname(target)
# folder of file does not exist
if not os.path.isdir(target_folder):
error({'description': "folder does not exist", 'data': target_folder})
# file already exists
if os.path.exists(target):
message({'description': "file exists"})
return
# new file created
Path(target).touch()
message({'level': "info", 'description': "file created"})
@action
def file_copy(task, context={}):
"""Copies a file."""
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
source = task.get('source')
if not source:
source = target + ".example"
target = os.path.join(root, target)
source = os.path.join(root, source)
# source file to copy not found
if not os.path.exists(source):
error({'description': "source file not found"})
# file already exists
target_exists = os.path.exists(target)
if target_exists and not _reset:
message({'description': "file_exists"})
return
# file overwritten due to reset switch
if target_exists and _reset:
shutil.copyfile(source, target)
message({'level': "warning", 'description': "file overwritten"})
if task['name'] == ".env":
line_replace({
'name': ".env", 'after': "^ENVIRONMENT=",
'replace': environment})
line_replace({
'name': ".env", 'after': "^BRANCH=",
'replace': branch})
return
# new file copied
shutil.copyfile(source, target)
message({'level': "info", 'description': "file copied"})
@action
def file_diff(task, context={}):
"""Diffs example files, prints output and returns different filenames."""
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
source = task.get('source')
if not source:
source = target + ".example"
target = os.path.join(root, target)
source = os.path.join(root, source)
verbose = context['actions']['verbose']
# source or target not found
if not os.path.exists(source):
error({'description': "source path not found"})
if not os.path.exists(target):
error({'description': "target path not found"})
# create diff
with open(source, 'r') as source_file, open(target, 'r') as target_file:
# get diff
source_content = source_file.readlines()
target_content = target_file.readlines()
diff = difflib.unified_diff(
source_content, target_content,
fromfile=os.path.basename(source), tofile=task["name"])
try:
line = next(diff)
except StopIteration:
message({'description': 'file is identical'})
return
lines = [line] + [d for d in diff]
# filter diff
ignored = False
filtered = []
ignore = task.get('ignore')
if ignore:
if isinstance(ignore, list):
ignore = context['actions'].get('ignore', []) + task['ignore']
ignore = re.compile(r'(%s)' % "|".join(ignore))
task['ignore'] = ignore
for line in lines[2:]:
if not line[0] in ["+", "-"]:
continue
match = ignore.match(line[1:])
if match is not None:
ignored = True
continue
filtered.append(line)
if not verbose:
lines = lines[0:3] + filtered
# color diff
data = ""
if _ci:
data += "--8<-- (ignored lines stripped) --8<--\n"
data += "".join(filtered)
else:
data += color_file_diff("".join(lines))
# files contains only ignored differences
if ignored and not filtered:
msg = {'level': 'info',
'description': 'diff contains only ignored lines'}
if verbose:
msg['data'] = data
message(msg)
return
# differences found
message({'level': "warning", 'description': "differences found",
'data': data})
@action
def line_replace(task, context={}):
"""Replaces regex patterns in lines in files"""
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
target = os.path.join(root, target)
before = task.get('before', '') and '(?=%s)' % task.get('before')
after = task.get('after', '') and '(?<=%s)' % task.get('after')
regexp = after + task.get('regexp', '.*$') + before
replace = task.get('replace')
# replace pattern
linecount = 0
filecount = 0
try:
with FileInput(target, inplace=True, backup=".backup") as input:
for line in input:
newline, count = re.subn(regexp, replace, line)
if count:
linecount += 1
filecount += count
print(newline, end="")
except Exception:
shutil.copyfile(target + ".backup", target)
error({'description': "error in line replace",
'data': traceback.format_exc()})
if linecount:
message({'level': "debug", 'description': "lines replaced",
'data': "regexp: %s\n" % regexp +
"replace: %s\n" % replace +
"%s matches in %s lines" % (filecount, linecount)})
@action
def folder_create(task, context={}):
"""Creates a folder."""
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
target = os.path.join(root, target)
# folder already exists
if os.path.exists(target):
message({'description': "folder exists"})
return
# new folder created
os.makedirs(target)
message({'level': "info", 'description': "folder created"})
@action
def folder_copy(task, context={}):
"""Copies a folder."""
source = task['source']
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
# folder already exists
if os.path.exists(target) and not _reset:
message({'description': "folder exists"})
return
# folder overwritten due to reset switch
shutil.copytree(source, target)
if _reset:
shutil.copytree(source, target)
message({'level': "info", 'description': "folder copied"})
return
# new folder copied
shutil.copytree(source, target)
message({'level': "warning", 'description': "folder overwritten"})
@action
def git_clone(task, context={}):
"""Clones a repository."""
source = task['source']
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
# create containing path for repo
if context['actions']['create_folder']:
folder_create({'name': os.path.dirname(target)})
# choose ssh or https
if git_protocol == 'https' and "@" in source:
url = source.split("@", 1)[1]
source = "https://" + url.replace(":", "/")
# repo already exists
if os.path.exists(os.path.join(target, '.git')):
message({'description': "repo exists"})
return
# new repo cloned
execute(('git', 'clone', '--quiet', source, target))
@action
def git_origin(task, context={}):
"""Sets the origin of a repository."""
source = task['source']
target = task.get('target') or task['name']
targetpath = task.get('targetpath')
if targetpath:
target = os.path.join(targetpath, target)
# choose ssh or https
if git_protocol == 'https' and "@" in source:
url = source.split("@", 1)[1]
source = "https://" + url.replace(":", "/")
# origin already set
old_source = execute(('git', 'remote', 'get-url', 'origin'), cwd=target)
if source == old_source:
message({'description': "origin already set"})
return
# origin changed
msg = {
'level': "warning",
'description': "origin changed",
'data': "\n".join([
"old origin: `%s`" % old_source,
"new origin: `%s`" % source])}
execute(('git', 'remote', 'set-url', 'origin', source),
cwd=target, msg=msg)