forked from reanahub/reana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.py
1767 lines (1544 loc) · 69.8 KB
/
cli.py
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
# -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2018, 2019, 2020 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Helper scripts for REANA developers. Run `reana-dev --help` for help."""
import datetime
import logging
import os
import subprocess
import sys
import time
import traceback
import click
from reana.k8s_utils import exec_into_component, get_external_url
REPO_LIST_DEMO = [
'reana-demo-helloworld',
'reana-demo-root6-roofit',
'reana-demo-worldpopulation',
'reana-demo-atlas-recast',
]
REPO_LIST_ALL = [
'docs.reana.io',
'reana',
'reana-client',
'reana-commons',
'reana-db',
'reana-demo-alice-lego-train-test-run',
'reana-demo-alice-pt-analysis',
'reana-demo-bsm-search',
'reana-demo-cdci-crab-pulsar-integral-verification',
'reana-demo-cdci-integral-data-reduction',
'reana-demo-cms-dimuon-mass-spectrum',
'reana-demo-cms-h4l',
'reana-demo-cms-reco',
'reana-demo-lhcb-d2pimumu',
'reana-env-aliphysics',
'reana-env-jupyter',
'reana-env-root6',
'reana-job-controller',
'pytest-reana',
'reana-message-broker',
'reana-server',
'reana-ui',
'reana-workflow-controller',
'reana-workflow-engine-cwl',
'reana-workflow-engine-serial',
'reana-workflow-engine-yadage',
'reana-workflow-monitor',
'www.reana.io',
] + REPO_LIST_DEMO
REPO_LIST_CLIENT = [
# shared utils
'pytest-reana',
'reana-commons',
# client
'reana-client',
]
REPO_LIST_CLUSTER = [
# shared utils
'pytest-reana',
'reana-commons',
'reana-db',
# cluster components
'reana-ui',
'reana-job-controller',
'reana-message-broker',
'reana-server',
'reana-workflow-controller',
'reana-workflow-engine-cwl',
'reana-workflow-engine-serial',
'reana-workflow-engine-yadage',
]
REPO_LIST_SHARED = [
'reana-db',
'reana-commons',
]
WORKFLOW_ENGINE_LIST_ALL = [
'cwl',
'serial',
'yadage'
]
COMPONENT_PODS = {
'reana-db': 'reana-db',
'reana-message-broker': 'reana-message-broker',
'reana-server': 'reana-server',
'reana-workflow-controller': 'reana-workflow-controller',
'reana-ui': 'reana-ui',
}
EXAMPLE_OUTPUT_FILENAMES = {
'reana-demo-helloworld': ('greetings.txt',),
'reana-demo-bsm-search': ('prefit.pdf', 'postfit.pdf'),
'reana-demo-alice-lego-train-test-run': ('plot.pdf',),
'reana-demo-alice-pt-analysis': ('plot_eta.pdf', 'plot_pt.pdf'),
'reana-demo-atlas-recast': ('pre.png', 'limit.png', 'limit_data.json'),
'reana-demo-cms-dimuon-mass-spectrum': ('DoubleMu.root',),
'*': ('plot.png',)
}
EXAMPLE_LOG_MESSAGES = {
'reana-demo-helloworld': (
'Parameters: inputfile=',
),
'reana-demo-root6-roofit': (
'gendata.C',
'RooChebychev::bkg',
'fitdata.C',
'MIGRAD MINIMIZATION HAS CONVERGED',
),
'reana-demo-worldpopulation': (
'Input Notebook',
'Output Notebook',
),
'reana-demo-atlas-recast': (
'MC channel Number',
'MIGRAD MINIMIZATION HAS CONVERGED',
),
'*': (
'job:',
)
}
EXAMPLE_PREFETCH_IMAGES = {
'reana-demo-helloworld': [
'python:2.7-slim', ],
'reana-demo-worldpopulation': [
'reanahub/reana-env-jupyter', ],
'reana-demo-root6-roofit': [
'reanahub/reana-env-root6', ],
'reana-demo-atlas-recast': [
'reanahub/reana-demo-atlas-recast-eventselection',
'reanahub/reana-demo-atlas-recast-statanalysis']
}
COMPONENTS_USING_SHARED_MODULE_COMMONS = [
'reana-job-controller',
'reana-server',
'reana-workflow-controller',
'reana-workflow-engine-cwl',
'reana-workflow-engine-serial',
'reana-workflow-engine-yadage',
]
COMPONENTS_USING_SHARED_MODULE_DB = [
'reana-job-controller',
'reana-server',
'reana-workflow-controller',
]
TIMECHECK = 5
TIMEOUT = 300
@click.group()
def cli(): # noqa: D301
"""Run REANA development and integration commands.
How to prepare your environment:
.. code-block:: console
\b
$ # prepare directory that will hold sources
$ mkdir -p ~/project/reana/src
$ cd ~/project/reana/src
$ # create new virtual environment
$ virtualenv ~/.virtualenvs/myreana
$ source ~/.virtualenvs/myreana/bin/activate
$ # install reana-dev developer helper script
$ pip install git+git://github.com/reanahub/reana.git#egg=reana
$ # run ssh-agent locally to simplify GitHub interaction
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa
How to fork and clone all REANA repositories:
.. code-block:: console
\b
$ reana-dev git-fork -c ALL
$ eval "$(reana-dev git-fork -c ALL)"
$ reana-dev git-clone -c ALL -u tiborsimko
How to install latest ``master`` REANA cluster and client CLI scripts:
.. code-block:: console
\b
$ reana-dev install-client
$ reana-dev install-cluster
How to compile and deploy latest ``master`` REANA cluster:
.. code-block:: console
\b
$ # install minikube and set docker environment
$ minikube start --vm-driver=virtualbox \\
--feature-gates="TTLAfterFinished=true"
$ eval $(minikube docker-env)
$ # option (a): cluster in production-like mode
$ reana-dev docker-build
$ helm install reana helm/reana
$ # option (b): cluster in developer-like debug-friendly mode
$ reana-dev docker-build -b DEBUG=1
$ helm install reana helm/reana --set debug.enabled=true
How to set up your shell environment variables:
.. code-block:: console
\b
$ eval $(reana-dev setup-environment)
How to run full REANA example using a given workflow engine:
.. code-block:: console
\b
$ reana-dev run-example -c reana-demo-root6-roofit -w serial
How to test one component pull request:
.. code-block:: console
\b
$ cd reana-workflow-controller
$ reana-dev git-checkout -b . 72 --fetch
$ reana-dev docker-build -c .
$ reana-dev kubectl-delete-pod -c .
How to test multiple component branches:
.. code-block:: console
\b
$ reana-dev git-checkout -b reana-server 72
$ reana-dev git-checkout -b reana-workflow-controller 98
$ reana-dev git-status
$ reana-dev docker-build
$ reana-dev kubectl-delete-pod -c reana-server
$ reana-dev kubectl-delete-pod -c reana-workflow-controller
How to test multiple component branches with commits to shared modules:
.. code-block:: console
\b
$ reana-dev git-checkout -b reana-commons 72
$ reana-dev git-checkout -b reana-db 73
$ reana-dev git-checkout -b reana-workflow-controller 98
$ reana-dev git-checkout -b reana-server 112
$ reana-dev git-submodule --update
$ reana-dev install-client
$ reana-dev install-cluster
$ reana-dev docker-build
$ helm delete helm/reana
$ minikube ssh 'sudo rm -rf /var/reana'
$ helm install reana helm/reana
$ eval $(reana-dev setup-environment)
$ reana-dev run-example -c r-d-helloworld
$ reana-dev git-submodule --delete
$ reana-dev git-status -s
How to release and push cluster component images:
.. code-block:: console
\b
$ reana-dev git-clean
$ reana-dev docker-build --no-cache
$ # we should now run one more test with non-cached ``latest``
$ # once it works, we can tag and push
$ reana-dev docker-build -t 0.3.0.dev20180625
$ reana-dev docker-push -t 0.3.0.dev20180625
$ # we should now publish stable helm charts for tag via chartpress
"""
pass
def shorten_component_name(component):
"""Return canonical short version of the component name.
Example: reana-workflow-controller -> r-w-controller
:param component: standard component name
:type component: str
:return: short component name
:rtype: str
"""
short_name = ''
parts = component.split('-')
for part in parts[:-1]:
short_name += part[0] + '-'
short_name += parts[-1]
return short_name
def find_standard_component_name(short_component_name):
"""Return standard component name corresponding to the short name.
Example: r-w-controller -> reana-workflow-controller
:param short_component_name: short component name
:type component: str
:return: standard component name
:rtype: str
:raise: exception in case more than one is found
"""
def _is_standard_name(component_name):
"""Detect whether the provided component name is already standard."""
prefixes = component_name.split('-')[:-1]
return all([len(n) > 1 for n in prefixes])
if _is_standard_name(short_component_name):
standard_component_name = short_component_name
else:
output = []
for component in REPO_LIST_ALL:
component_short_name = shorten_component_name(component)
if component_short_name == short_component_name:
output.append(component)
if len(output) == 1:
standard_component_name = output[0]
else:
raise Exception('Component name {0} cannot be uniquely '
'mapped.'.format(short_component_name))
return standard_component_name
def find_reana_srcdir():
"""Find directory where REANA sources are checked out.
Try to go up from the current directory until you find the first parent
directory where REANA cluster repositories are checked out.
:return: source code directory for given component
:rtype: str
:raise: exception in case it is not found
"""
# first, try current working directory:
srcdir = os.getcwd()
if os.path.exists(srcdir + os.sep + 'reana' + os.sep + '.git' +
os.sep + 'config'):
return srcdir
# second, try from the parent of git toplevel:
toplevel = subprocess.check_output(
'git rev-parse --show-toplevel', shell=True).decode().rstrip('\r\n')
srcdir = toplevel.rsplit(os.sep, 1)[0]
if os.path.exists(srcdir + os.sep + 'reana' + os.sep + '.git' +
os.sep + 'config'):
return srcdir
# fail if not found
raise Exception('Cannot find REANA component source directory '
'in {1}.'.format(srcdir))
def get_srcdir(component=''):
"""Return source code directory of the given REANA component.
:param component: standard component name
:type component: str
:return: source code directory for given component
:rtype: str
"""
reana_srcdir = find_reana_srcdir()
if component:
return reana_srcdir + os.sep + component
else:
return reana_srcdir
def get_current_branch(srcdir):
"""Return current Git branch name checked out in the given directory.
:param srcdir: source code directory
:type srcdir: str
:return: checkout out branch in the component source code directory
:rtype: str
"""
os.chdir(srcdir)
return subprocess.check_output(
'git branch 2>/dev/null | grep "^*" | colrm 1 2',
shell=True).decode().rstrip('\r\n')
def get_all_branches(srcdir):
"""Return all local and remote Git branch names in the given directory.
:param srcdir: source code directory
:type srcdir: str
:return: checkout out branch in the component source code directory
:rtype: str
"""
os.chdir(srcdir)
return subprocess.check_output(
'git branch -a 2>/dev/null',
shell=True).decode().split()
def get_current_commit(srcdir):
"""Return information about git commit checked out in the given directory.
:param srcdir: source code directory
:type srcdir: str
:return: commit information composed of brief SHA1 and subject
:rtype: str
"""
os.chdir(srcdir)
return subprocess.check_output(
'git log --pretty=format:"%h %s" -n 1',
shell=True).decode().rstrip('\r\n')
def select_components(components, exclude_components=None):
"""Return expanded and unified component name list based on input values.
:param components: A list of component name that may consist of:
* (1) standard component names such as
'reana-workflow-controller';
* (2) short component name such as 'r-w-controller';
* (3) special value '.' indicating component of the
current working directory;
* (4) special value 'CLUSTER' that will expand to
cover all REANA cluster components;
* (5) special value 'CLIENT' that will expand to
cover all REANA client components;
* (6) special value 'DEMO' that will expand
to include several runable REANA demo examples;
* (7) special value 'ALL' that will expand to include
all REANA repositories.
:param exclude_components: A list of components to exclude.
:type components: list
:type exclude_components: list
:return: Unique standard component names.
:rtype: list
"""
short_component_names = [shorten_component_name(name)
for name in REPO_LIST_ALL]
output = set([])
for component in components:
if component == 'ALL':
for repo in REPO_LIST_ALL:
output.add(repo)
elif component == 'DEMO':
for repo in REPO_LIST_DEMO:
output.add(repo)
elif component == 'CLIENT':
for repo in REPO_LIST_CLIENT:
output.add(repo)
elif component == 'CLUSTER':
for repo in REPO_LIST_CLUSTER:
output.add(repo)
elif component == '.':
cwd = os.path.basename(os.getcwd())
output.add(cwd)
elif component in REPO_LIST_ALL:
output.add(component)
elif component in short_component_names:
component_standard_name = find_standard_component_name(component)
output.add(component_standard_name)
else:
display_message('Ignoring unknown component {0}.'.format(
component))
if exclude_components:
output = exclude_components_from_selection(output, exclude_components)
return list(output)
def exclude_components_from_selection(selection, exclude_components):
"""Exclude list of components from list of selections.
:param selection: List of selected components in standard naming form.
:param exclude_components: List of components to exclude, either in short
or standard naming form.
:type selection: set
:type exclude_components: list
:return: Set of selected components without ``exclude_components``, all in
standard naming form.
:rtype: set
"""
st_exclude_components = \
[find_standard_component_name(c) for c in exclude_components]
non_existing_exclude_components = \
set(st_exclude_components).difference(selection)
if non_existing_exclude_components:
display_message('Unkown component(s) to exclude: {}'.format(
non_existing_exclude_components))
sys.exit(1)
click.secho(
'Excluding component(s) {}'.format(st_exclude_components), fg='yellow')
return selection.difference(st_exclude_components)
def select_workflow_engines(workflow_engines):
"""Return known workflow engine names that REANA supports.
:param workflow_engines: A list of workflow engine names such as 'cwl'.
:type components: list
:return: Unique workflow engine names.
:rtype: list
"""
output = set([])
for workflow_engine in workflow_engines:
if workflow_engine in WORKFLOW_ENGINE_LIST_ALL:
output.add(workflow_engine)
else:
display_message('Ignoring unknown workflow engine {0}.'.format(
workflow_engine))
return list(output)
def is_component_dockerised(component):
"""Return whether the component contains Dockerfile.
Useful to skip some docker-related commands for those components that are
not concerned, such as building Docker images for `reana-commons` that does
not provide any.
:param component: standard component name
:type component: str
:return: True/False whether the component is dockerisable
:rtype: bool
"""
if os.path.exists(get_srcdir(component) + os.sep + 'Dockerfile'):
return True
return False
def is_component_runnable_example(component):
"""Return whether the component contains reana.yaml.
Useful for safety check when using some run-example commands for those
components that are not REANA examples.
:param component: standard component name
:type component: str
:return: True/False whether the component is a REANA example
:rtype: bool
"""
if os.path.exists(get_srcdir(component) + os.sep + 'reana.yaml'):
return True
return False
def construct_workflow_name(example, workflow_engine):
"""Construct suitable workflow name for given REANA example.
:param example: REANA example (e.g. reana-demo-root6-roofit)
:param workflow_engine: workflow engine to use (cwl, serial, yadage)
:type example: str
:type workflow_engine: str
"""
output = '{0}-{1}'.format(example.replace('reana-demo-', ''),
workflow_engine)
return output
def run_command(cmd, component='', display=True, return_output=False):
"""Run given command in the given component source directory.
Exit in case of troubles.
:param cmd: shell command to run
:param component: standard component name
:param display: should we display command to run?
:param return_output: shall the output of the command be returned?
:type cmd: str
:type component: str
:type display: bool
:type return_output: bool
"""
now = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
if display:
click.secho('[{0}] '.format(now), bold=True, nl=False, fg='green')
click.secho('{0}: '.format(component), bold=True, nl=False,
fg='yellow')
click.secho('{0}'.format(cmd), bold=True)
if component:
os.chdir(get_srcdir(component))
try:
if return_output:
result = subprocess.check_output(cmd, shell=True)
return result.decode().rstrip('\r\n')
else:
subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError as err:
if display:
click.secho('[{0}] '.format(now), bold=True, nl=False, fg='green')
click.secho('{0}: '.format(component), bold=True, nl=False,
fg='yellow')
click.secho('{0}'.format(err), bold=True, fg='red')
sys.exit(err.returncode)
def display_message(msg, component=''):
"""Display message in a similar style as run_command().
:param msg: message to display
:param component: standard component name
:type msg: str
:type component: str
"""
now = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
click.secho('[{0}] '.format(now), bold=True, nl=False, fg='green')
click.secho('{0}: '.format(component), bold=True, nl=False, fg='yellow')
click.secho('{0}'.format(msg), bold=True)
def get_expected_output_filenames_for_example(example):
"""Return expected output file names for given example.
:param example: name of the component
:return: Tuple with output file name(s)
"""
try:
output = EXAMPLE_OUTPUT_FILENAMES[example]
except KeyError:
output = EXAMPLE_OUTPUT_FILENAMES['*']
return output
def get_expected_log_messages_for_example(example):
"""Return expected log messages for given example.
:param example: name of the component
:return: Tuple with output log messages(s)
"""
try:
output = EXAMPLE_LOG_MESSAGES[example]
except KeyError:
output = EXAMPLE_LOG_MESSAGES['*']
return output
def get_current_version(component, dirty=False):
"""Return the current version of a component.
:param component: standard component name
:param dirty: wheter the ``dirty`` flag is used when calling
``git describe``
:type component: str
:type dirty: bool
"""
cmd = 'git describe'
if dirty:
cmd += ' --dirty --always'
tag = run_command(cmd, component, return_output=True)
# Remove starting `v` we use for Python/Git versioning
return tag[1:]
@cli.command()
def version():
"""Show version."""
from reana.version import __version__
click.echo(__version__)
@cli.command()
def help():
"""Display usage help tips and tricks."""
click.echo(cli.__doc__)
@click.option('--component', '-c', multiple=True, default=['CLUSTER'],
help='Which components? [shortname|name|.|CLUSTER|ALL]')
@click.option('--browser', '-b', default='firefox',
help='Which browser to use? [firefox]')
@cli.command(name='git-fork')
def git_fork(component, browser): # noqa: D301
"""Display commands to fork REANA source code repositories on GitHub.
\b
:param components: The option ``component`` can be repeated. The value may
consist of:
* (1) standard component name such as
'reana-workflow-controller';
* (2) short component name such as 'r-w-controller';
* (3) special value '.' indicating component of the
current working directory;
* (4) special value 'CLUSTER' that will expand to
cover all REANA cluster components [default];
* (5) special value 'CLIENT' that will expand to
cover all REANA client components;
* (6) special value 'DEMO' that will expand
to include several runable REANA demo examples;
* (7) special value 'ALL' that will expand to include
all REANA repositories.
:param browser: The web browser to use. [default=firefox]
:type component: str
:type browser: str
"""
components = select_components(component)
if components:
click.echo('# Fork REANA repositories on GitHub using your browser.')
click.echo('# Run the following eval and then complete the fork'
' process in your browser.')
click.echo('#')
click.echo('# eval "$(reana-dev git-fork -b {0} {1})"'.format(
browser,
"".join([" -c {0}".format(c) for c in component])))
for component in components:
cmd = '{0} https://github.com/reanahub/{1}/fork;'.format(browser,
component)
click.echo(cmd)
click.echo('echo "Please continue the fork process in the opened'
' browser windows."')
@click.option('--user', '-u', default='anonymous',
help='GitHub user name [anonymous]')
@click.option('--component', '-c', multiple=True, default=['CLUSTER'],
help='Which components? [shortname|name|.|CLUSTER|ALL]')
@cli.command(name='git-clone')
def git_clone(user, component): # noqa: D301
"""Clone REANA source repositories from GitHub.
If the ``user`` argument is provided, the ``origin`` will be cloned from
the user repository on GitHub and the ``upstream`` will be set to
``reanahub`` organisation. Useful for setting up personal REANA development
environment,
If the ``user`` argument is not provided, the cloning will be done in
anonymous manner from ``reanahub`` organisation. Also, the clone will be
shallow to save disk space and CPU time. Useful for CI purposes.
\b
:param components: The option ``component`` can be repeated. The value may
consist of:
* (1) standard component name such as
'reana-workflow-controller';
* (2) short component name such as 'r-w-controller';
* (3) special value '.' indicating component of the
current working directory;
* (4) special value 'CLUSTER' that will expand to
cover all REANA cluster components [default];
* (5) special value 'CLIENT' that will expand to
cover all REANA client components;
* (6) special value 'DEMO' that will expand
to include several runable REANA demo examples;
* (7) special value 'ALL' that will expand to include
all REANA repositories.
:param user: The GitHub user name. [default=anonymous]
:type component: str
:type user: str
"""
components = select_components(component)
for component in components:
os.chdir(get_srcdir())
if os.path.exists('{0}/.git/config'.format(component)):
msg = 'Component seems already cloned. Skipping.'
display_message(msg, component)
elif user == 'anonymous':
cmd = 'git clone https://github.com/reanahub/{0} --depth 1'.format(
component)
run_command(cmd)
else:
cmd = 'git clone git@github.com:{0}/{1}'.format(user, component)
run_command(cmd)
for cmd in [
'git remote add upstream'
' "git@github.com:reanahub/{0}"'.format(component),
'git config --add remote.upstream.fetch'
' "+refs/pull/*/head:refs/remotes/upstream/pr/*"',
]:
run_command(cmd, component)
@click.option('--component', '-c', multiple=True, default=['CLUSTER'],
help='Which components? [shortname|name|.|CLUSTER|ALL]')
@click.option('--short', '-s', is_flag=True, default=False,
help="Show git status short format details?")
@cli.command(name='git-status')
def git_status(component, short): # noqa: D301
"""Report status of REANA source repositories.
\b
:param components: The option ``component`` can be repeated. The value may
consist of:
* (1) standard component name such as
'reana-workflow-controller';
* (2) short component name such as 'r-w-controller';
* (3) special value '.' indicating component of the
current working directory;
* (4) special value 'CLUSTER' that will expand to
cover all REANA cluster components [default];
* (5) special value 'CLIENT' that will expand to
cover all REANA client components;
* (6) special value 'DEMO' that will expand
to include several runable REANA demo examples;
* (7) special value 'ALL' that will expand to include
all REANA repositories.
:param verbose: Show git status details? [default=False]
:type component: str
"""
components = select_components(component)
for component in components:
# detect current branch and commit
branch = get_current_branch(get_srcdir(component))
commit = get_current_commit(get_srcdir(component))
# detect all local and remote branches
all_branches = get_all_branches(get_srcdir(component))
# detect branch to compare against
if branch == 'master': # master
branch_to_compare = 'upstream/master'
elif branch.startswith('pr-'): # other people's PR
branch_to_compare = 'upstream/' + branch.replace('pr-', 'pr/')
else:
branch_to_compare = 'origin/' + branch # my PR
if 'remotes/' + branch_to_compare not in all_branches:
branch_to_compare = 'origin/master' # local unpushed branch
# detect how far it is ahead/behind from pr/origin/upstream
report = ''
cmd = 'git rev-list --left-right --count {0}...{1}'.format(
branch_to_compare, branch)
behind, ahead = [
int(x) for x in run_command(cmd, display=False,
return_output=True).split()
]
if ahead or behind:
report += '('
if ahead:
report += '{0} AHEAD '.format(ahead)
if behind:
report += '{0} BEHIND '.format(behind)
report += branch_to_compare + ')'
# detect rebase needs for local branches and PRs
if branch_to_compare != 'upstream/master':
branch_to_compare = 'upstream/master'
cmd = 'git rev-list --left-right --count {0}...{1}'.format(
branch_to_compare, branch)
behind, ahead = [
int(x) for x in run_command(cmd, display=False,
return_output=True).split()
]
if behind:
report += '(STEMS FROM '
if behind:
report += '{0} BEHIND '.format(behind)
report += branch_to_compare + ')'
# print branch information
click.secho('{0}'.format(component), nl=False, bold=True)
click.secho(' @ ', nl=False, dim=True)
if branch == 'master':
click.secho('{0}'.format(branch), nl=False)
else:
click.secho('{0}'.format(branch), nl=False, fg='green')
if report:
click.secho(' {0}'.format(report), nl=False, fg='red')
click.secho(' @ ', nl=False, dim=True)
click.secho('{0}'.format(commit))
# optionally, display also short status
if short:
cmd = 'git status --short'
run_command(cmd, component, display=False)
@click.option('--component', '-c', multiple=True, default=['CLUSTER'],
help='Which components? [shortname|name|.|CLUSTER|ALL]')
@cli.command(name='git-clean')
def git_clean(component): # noqa: D301
"""Clean REANA source repository code tree.
Removes all non-source-controlled files in the component source code
repository. Useful to run before building container images.
\b
:param components: The option ``component`` can be repeated. The value may
consist of:
* (1) standard component name such as
'reana-workflow-controller';
* (2) short component name such as 'r-w-controller';
* (3) special value '.' indicating component of the
current working directory;
* (4) special value 'CLUSTER' that will expand to
cover all REANA cluster components [default];
* (5) special value 'CLIENT' that will expand to
cover all REANA client components;
* (6) special value 'DEMO' that will expand
to include several runable REANA demo examples;
* (7) special value 'ALL' that will expand to include
all REANA repositories.
:type component: str
"""
components = select_components(component)
for component in components:
for cmd in [
'git clean -d -ff -x',
]:
run_command(cmd, component)
@click.option('--update', is_flag=True,
help='Update shared modules everywhere?', default=False)
@click.option('--status', is_flag=True,
help='Show status of shared modules everywhere.', default=False)
@click.option('--delete', is_flag=True,
help='Delete shared modules everywhere?', default=False)
@cli.command(name='git-submodule')
def git_submodule(update=False, status=False, delete=False): # noqa: D301
"""Sync REANA shared modules across all the repositories.
Take currently checked-out reana-commons and reana-db modules and sync them
across REANA components. Useful for building container images with
not-yet-released shared modules.
The option ``--update`` propagates the shared modules across the code base
as necessary. Useful before running local docker image building.
The option ``--status`` shows the information about shared modules.
The option ``--delete`` removes the shared modules from everywhere. Useful
for clean up after testing.
"""
if update:
for component in COMPONENTS_USING_SHARED_MODULE_COMMONS:
for cmd in [
'rsync -az ../reana-commons modules',
]:
run_command(cmd, component)
for component in COMPONENTS_USING_SHARED_MODULE_DB:
for cmd in [
'rsync -az ../reana-db modules',
]:
run_command(cmd, component)
elif delete:
for component in set(COMPONENTS_USING_SHARED_MODULE_COMMONS +
COMPONENTS_USING_SHARED_MODULE_DB):
for cmd in [
'rm -rf ./modules/',
]:
run_command(cmd, component)
elif status:
for component in COMPONENTS_USING_SHARED_MODULE_COMMONS:
for cmd in [
'git status -s',
]:
run_command(cmd, component)
for component in COMPONENTS_USING_SHARED_MODULE_DB:
for cmd in [
'git status -s',
]:
run_command(cmd, component)
else:
click.echo('Unknown action. Please specify `--update`, `--status` '
' or `--delete`. Exiting.')
sys.exit(1)
@click.option('--component', '-c', multiple=True, default=['CLUSTER'],
help='Which components? [shortname|name|.|CLUSTER|ALL]')
@cli.command(name='git-branch')
def git_branch(component): # noqa: D301
"""Display information about locally checked-out branches.
\b
:param components: The option ``component`` can be repeated. The value may
consist of:
* (1) standard component name such as
'reana-workflow-controller';
* (2) short component name such as 'r-w-controller';
* (3) special value '.' indicating component of the