-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathproject.py
executable file
·2043 lines (1663 loc) · 88.4 KB
/
project.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
#!/usr/bin/env python3
"""
This script provides useful utilities for working with JUDO project source code.
To install make sure you are in the base JUDO project directory.
1a. Install with pyenv.
Install pyenv in Linux (https://github.com/pyenv/pyenv-installer)
curl https://pyenv.run | bash
exec $SHELL
Install on macOS (https://github.com/pyenv/pyenv)
brew update
brew install pyenv
Install on Windows: https://github.com/pyenv-win/pyenv-win#installation
Add virtual environment:
pyenv virtualenv 3.7.3 judo-ng
pyenv local judo-ng
After installation, it is activated, nothing to do.
1b. Install without pyenv
Install python and dependencies (linux):
sudo apt install python3
sudo apt install python3-venv
sudo apt install python-pip
sudo apt install graphviz
Create virtual environment (to not change global python version and libraries) and install dependencies
python3 -m venv .pyenv
Later, when interacting with the script, make sure you activated the environment with:
source .pyenv/bin/activate
2. Install requirements
pip install wheel
pip install -r requirements.txt
Those features that use the remote repository need a GitHub token for authentication,
visit https://github.com/settings/tokens to create one. Scope to select: repo - Full control of private repositories.
If there is any problem with dependencies, try:
pip install -r requirements.txt --upgrade --force-reinstall
A very important output of the script is the project-meta.yml file.
This contains the relations between the modules and is used to update pom.xml files etc.
Try it:
./project.py -sg
will create an SVG file showing the dependencies between the projects.
== Project dependencies
The project dependencies defined as a DAG (Directed Acyclic Graph)
With this tool operations can be performed in the whole graph and some part of it.
When you want to define nodes where the processing start of, use -sm switch,
and define what is the target project with the -tm switches. The logic
will calculate all projects between.
== Update project-meta.yml to contain the latest version in the remote repository
./project.py -fv -gh <YOUR_GITHUB_TOKEN_HERE>
The -fv option will check the latest release of all the modules and update the project-meta.yml file accordingly.
This information then can be used to update pom.xml files to use the latest versions of the modules.
== Create branches for projects
./project.py -sm judo-meta-psm -tm judo-platform -nf feature/JNG-3834_TestCI "JNG-3834 Test CI capability"
It creates feature branch, create an empty commit and create draft pull request for all projects between
judo-meta-psm and judo-platform
== Perform continues build
./project.py -sm judo-meta-psm judo-meta-jql judo-meta-expression -tm judo-platform -bs
It fetches versions for the given modules, updating pom.xml, pushing and waiting for new versions. It will
traverse graph and orchestrating that all descendants have correct and consistent version.
== Switch branch
./project.py -sm judo-meta-psm judo-meta-jql judo-meta-expression -tm judo-platform -sb develop
Switch branches back to develop for the given modules.
== Execute build locally with module and modules depending on it recursively to snapshot version
Calling the script with the -bs option will execute a local build with SNAPSHOT version. The other modules
will use the versions is defined in their pom.xml
./project.py -bs
It starts a build for all modules which is not virtual or ignored by default.
With the -bs switch the modules where the build starts from can be defined. In that case
the defined modules and all dependent modules starts to build.
To ignore specific modules, use -bi switch.
If the build is failing somewhere, after fixing the issue you can continue
./project.py -bs -c <module_to_continue_from>
To start a build from judo-meta-jsl, type
./project.py -bs -sm judo-meta-jsl
It can contain several start module.
If you do not want to build the whole dependency chain, you can define terminate modules.
In this case the modules between start and terminate modules will be built.
./project.py -bs -sm judo-meta-jsl -tm judo-runtime-core-jsl
== Change the dependencies of a given module to the latest versions
Assuming you've already updated the versions in the project-meta.yml file, you can update one module's dependencies to
the latest versions:
./project.py -ump <module name>
You can do the fetching and the updating in one step:
./project.py -fv -ump <module_name> -gh <github_token>
== Releasing using the script
Always release from a separate local repository, not your working copy.
For example clone again:
git clone --recurse-submodules [email protected]:BlackBeltTechnology/judo-ng.git ~/rel-judo-ng
Make sure everything locally is up-to-date:
git submodule init
git submodule update --recursive
./project.py -fv -gc -gh $(cat ~/githubtoken)
Switch to the correct tatami branch:
cd runtime/judo-tatami
git checkout develop
cd ../..
Start the builds:
./project.py -ib -gh $(cat ~/githubtoken)
When working an HTTP server run, you can see the process:
http://localhost:8000
"""
import atexit
import base64
import http
import json
import os
import re
import socket
import webbrowser
import traceback
import sys
import shutil
from argparse import RawDescriptionHelpFormatter, ArgumentParser
from typing import Any, Dict
import git
from github import Github, UnknownObjectException
import yaml
from xml.etree.ElementTree import Comment, register_namespace, parse, XMLParser, TreeBuilder
from subprocess import call
import time
from git import RemoteProgress
import networkx as nx
from networkx.drawing.nx_pydot import write_dot, to_pydot
from networkx.algorithms.dag import transitive_reduction
from networkx.algorithms.dag import ancestors, descendants
from tqdm import tqdm
import argparse
import textwrap
from http.server import BaseHTTPRequestHandler
import threading
import tempfile
from datetime import datetime
from colorama import init, Fore, Style
from atlassian import Jira
import hashlib
from datetime import datetime, timezone
from email.utils import format_datetime
# TODO: Adapt https://hal.archives-ouvertes.fr/hal-00695818/document
# TODO: Adapt https://www.cse.wustl.edu/~lu/papers/tpds-dags.pdf
init(autoreset=True)
# noinspection PyTypeChecker
parser: ArgumentParser = argparse.ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
description=textwrap.dedent(
"Handling module building of Judo NG\n\n" + __doc__))
general_arg_group = parser.add_argument_group('General arguments')
general_arg_group.add_argument("-sg", "--graphviz", action="store_true", dest="graphviz", default=False,
help='Save graphviz representation of current state')
general_arg_group.add_argument("-d", "--dirty", action="store_true", dest="dirty", default=False,
help='Do not update yaml')
general_arg_group.add_argument("-ib", "--integration_build", action="store_true", dest="integration_build",
default=False,
help='Continuous integration build. (same as -fv -pu -up -cu)')
general_arg_group.add_argument("-rb", "--release_build", action="store_true", dest="release_build",
default=False,
help='Continuous integration build. (same as -fv -pu -up -cu)')
general_arg_group.add_argument("-fd", "--fix-dependencies", action="store_true", dest="fix_dependencies",
default=False,
help='Add pom.xml defined dependencies to project-meta.yml')
general_arg_group.add_argument("-cu", "--continuous", action="store_true", dest="continuous_update", default=False,
help='Continuously update / fetch / wait until last level')
general_arg_group.add_argument("-sm", "--start-modules", action="store", dest="start_modules", default=None,
metavar='MODULE...', nargs="*",
help='Run only on the defined module(s)')
general_arg_group.add_argument("-tm", "--terminate-modules", dest="terminate_modules",
metavar='MODULE...', nargs="*",
help="The process is terminated with these given modules. Only the models between "
"modules and terminate modules will processed. ")
general_arg_group.add_argument("-bm", "--branch-modules", action="store", dest="modules_with_branch", default=None,
metavar='Branch name', nargs=1,
help='Run only on the module(s) in defined branch')
general_arg_group.add_argument("-im", "--ignored-modules", dest="ignored_modules", metavar='MODULE...',
nargs="*",
help="Ignore given module(s)")
general_arg_group.add_argument("-c", "-continue-module", dest="continue_module",
metavar='MODULE', nargs=1,
help="Continue processing from the given module")
general_arg_group.add_argument("-p", "-parallel", type=int, dest="parallel",
metavar='MODULE',
help="Number of parallel threads", default=4)
general_arg_group.add_argument("-relnotes", "--release-notes", dest="relnotes", nargs=1,
metavar="FROM_HASH[..TO_HASH]",
help="Generate release notes based on different project-meta.yml versions")
localbuild_arg_group = parser.add_argument_group('Local build control arguments')
localbuild_arg_group.add_argument("-bs", "--build-snapshot", dest="build_snapshot", action='store_true', default=False,
help="Build modules")
localbuild_arg_group.add_argument("-kc", "--keep-changes", dest="keep_changes", action='store_true', default=False,
help="Keep changes in files")
git_arg_group = parser.add_argument_group('GIT control arguments')
git_arg_group.add_argument("-gc", "--gitcheckout", action="store_true", dest="git_checkout", default=False,
help='Fetch / Reset / Checkout branch')
git_arg_group.add_argument("-pu", "--pushupdates", action="store_true", dest="push_updates", default=False,
help='Push updates in projects')
git_arg_group.add_argument("-noci", "--noci", action="store_true", dest="ci_skip", default=False,
help='Make commit with CI Ignore')
github_arg_group = parser.add_argument_group('GitHub API control arguments')
github_arg_group.add_argument("-fv", "--fetchversions", action="store_true", dest="fetch_versions",
default=False,
help='Fetch last released versions from github')
github_arg_group.add_argument("-fva", "--fetchversions_all", action="store_true", dest="fetch_versions_all",
default=False,
help='Fetch last released versions from github for all modules')
github_arg_group.add_argument("-nf", "--newfeature", action="store", dest="new_feature",
metavar='branch message', nargs='+',
help='Create feature branch and pull request. (same as -cbr and -cpr). '
'If branch name contains spaces, it will be replaced with underscores ("_"). '
'If message is left empty, original, passed branch parameter will be used as '
'PR title. '
'If message/or branch name start with for example feature/ then it will be removed '
'for the PR\'s title and body.')
github_arg_group.add_argument("-ub", "--updatebranch", action="store_true", dest="update_branch",
default=False,
help='Update checked out branches in project-meta.yml')
github_arg_group.add_argument("-cbr", "--createbranch", action="store", dest="create_branch",
metavar='Feature name', nargs=1,
help='Create branch')
github_arg_group.add_argument("-sbr", "--switchbranch", action="store", dest="switch_branch",
metavar='Feature name', nargs=1,
help='Switch to branch')
github_arg_group.add_argument("-cpr", "--createpr", action="store", dest="create_pr",
metavar='Pull request name', nargs=1,
help='Create pull request')
pom_arg_group = parser.add_argument_group('Maven POM control arguments')
pom_arg_group.add_argument("-up", "--updatepom", action="store_true", dest="update_pom", default=False,
help='Update pom.xml')
pom_arg_group.add_argument("-ump", "--updatemodulepom", nargs=1, dest="update_module_pom",
help='Update pom.xml of one module')
pom_arg_group.add_argument("-rp", "--runpostchangescripts", action="store_true", dest="run_postchangescripts",
default=False,
help='Run postchange script without version update')
access_arg_group = parser.add_argument_group('Access settings')
access_arg_group.add_argument("-gh", "--githubtoken", action="store", dest="github_token",
default=os.environ.get('JUDO_GITHUB_TOKEN', ''),
help='GitHub token used for authentication')
access_arg_group.add_argument("-jtok", "--jiratoken", action="store", dest="jira_token",
default=os.environ.get('JUDO_JIRA_TOKEN', ''),
help='Jira token used for authentication '
'(https://id.atlassian.com/manage-profile/security/api-tokens)')
access_arg_group.add_argument("-jusr", "--jirauser", action="store", dest="jira_user",
default=os.environ.get('JUDO_JIRA_USER', ''),
help='Jira user used for authentication - same user as token user')
args = parser.parse_args()
modules = []
module_by_name = {}
process_info = {}
class StoppableHTTPServer(http.server.HTTPServer):
def run(self):
try:
self.serve_forever()
except KeyboardInterrupt:
pass
finally:
self.server_close()
process_info_server: StoppableHTTPServer
process_info_server_pid: threading.Thread
register_namespace('', 'http://maven.apache.org/POM/4.0.0')
pom_namespace = "{http://maven.apache.org/POM/4.0.0}"
github = Github(login_or_token=args.github_token)
class CloneProgress(RemoteProgress):
def __init__(self):
super().__init__()
def update(self, op_code, cur_count, max_count=None, message=''):
return
class CommentedTreeBuilder(TreeBuilder):
def __init__(self, *arguments, **kwargs):
super(CommentedTreeBuilder, self).__init__(*arguments, **kwargs)
def comment(self, data):
self.start(Comment, {})
self.data(data)
self.end(Comment)
class PropagatingThread(threading.Thread):
def run(self):
self.exc = None
try:
if hasattr(self, '_Thread__target'):
# Thread uses name mangling prior to Python 3.
self.ret = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
else:
self.ret = self._target(*self._args, **self._kwargs)
except BaseException as e:
self.exc = e
def join(self, timeout=None):
super(PropagatingThread, self).join(timeout)
if self.exc:
raise self.exc
# return self.ret
class Module(object):
def __init__(self, init_dict):
self.name = init_dict['name']
if 'url' in init_dict:
self.url = init_dict['url']
self.path = None
if 'path' in init_dict:
self.path = init_dict['path']
self.branch = init_dict['branch']
self.property = init_dict['property']
self.rank = 1
if 'version' in init_dict:
self.version = init_dict['version'] # .encode("ascii", "ignore")
if 'github' in init_dict:
self.github = init_dict['github']
self.dependencies = []
if 'dependencies' in init_dict:
self.dependencies = init_dict['dependencies']
self.afterversionchange = []
if 'afterversionchange' in init_dict:
self.afterversionchange = init_dict['afterversionchange']
self.beforelocalbuild = []
if 'beforelocalbuild' in init_dict:
self.beforelocalbuild = init_dict['beforelocalbuild']
self.afterlocalbuild = []
if 'afterlocalbuild' in init_dict:
self.afterlocalbuild = init_dict['afterlocalbuild']
self.ignored = False
if 'ignored' in init_dict:
self.ignored = init_dict['ignored']
self.virtual = False
if 'virtual' in init_dict:
self.virtual = init_dict['virtual']
# if self.branch == 'master':
# self.ignored = True
def __repr__(self):
return self.name + " (" + str(self.rank) + ")"
def resolve_dependencies(self, _module_by_name):
dependencies = []
if type(self.dependencies) is list:
for reference in self.dependencies:
dependencies.append(_module_by_name[reference])
elif type(self.dependencies) is str:
dependencies.append(_module_by_name[self.dependencies])
else:
raise SystemExit(f"{Fore.RED}Error: references have to be list or str type")
self.dependencies = dependencies
def deresolve_dependencies(self):
dependencies = []
for dependency in self.dependencies:
dependencies.append(dependency.name)
self.dependencies = dependencies
def get_version_from_branch_and_tag(self, _tag):
_ver = None
if self.branch == 'master':
if _tag and re.match(r'^v(\d+\.)?(\d+\.)?(\*|\d+)$', _tag):
_ver = _tag.strip()[1:] # .encode('ascii', 'ignore')
else:
_branch = re.sub(r"[ #,\\\"'/;-]", "_", self.branch)
if _tag and re.match(r'^v.*' + _branch + '.*', _tag):
_ver = _tag.strip()[1:] # .encode('ascii', 'ignore')
return _ver
def update_version_with_given_version(self, _ver):
if _ver and self.version != _ver:
print(
f"{Fore.YELLOW}Updating release version of {Fore.GREEN}{self.name}{Fore.YELLOW}: "
f"{Fore.GREEN}{self.version} {Fore.YELLOW}=>{Fore.GREEN} {_ver}")
# if version.parse(ver) < version.parse(self.version):
# raise SystemExit(
# f"{Fore.RED}{version.parse(ver)} in properties smaller than {version.parse(self.version)} on
# project-meta.yml: "
# f"{self.name}")
self.version = _ver
return True
return False
def fetch_github_versions(self):
if self.ignored:
return False
# repository = github.get_organization(par['github'].split("/")[0]).get_repo(par['github'].split("/")[1])
repository = github.get_repo(self.github)
for _tag in repository.get_tags():
_ver = self.get_version_from_branch_and_tag(_tag.name)
# print(f"Checking tag: {_tag.name} - Ver: {_ver}")
if self.update_version_with_given_version(_ver):
return True
if _ver:
return False
return False
def fetch_git_tag_versions(self):
if self.ignored:
return False
_tags = reversed(sorted(self.get_remote_tags().keys()))
for _tag in _tags:
_ver = self.get_version_from_branch_and_tag(_tag)
# print(f"Checking tag: {_tag} - Ver: {_ver}")
if _ver and self.version != _ver:
if self.update_version_with_given_version(_ver):
return True
if _ver:
return False
return False
def update_dependency_versions_in_pom(self, write_pom=False):
if self.path is None:
return False
if self.ignored or self.virtual:
return False
print(f"{Fore.YELLOW}Checking POM: {Fore.GREEN}{self.path}/pom.xml")
pom = parse(open(self.path + "/pom.xml", encoding="UTF-8"),
parser=XMLParser(target=CommentedTreeBuilder()))
root = pom.getroot()
properties_element = root.find(pom_namespace + 'properties')
if properties_element is None:
raise SystemExit(f"{Fore.RED}Error Any reference version have to be in properties definition on pom.xml: "
f"{self.name}")
update = False
for dependency in self.dependencies:
ref_prop_element = properties_element.find(pom_namespace + dependency.property)
# print(" ---> Dependency: " + dependency.name + " " + dependency.version)
if ref_prop_element is None:
raise SystemExit(f"{Fore.RED}{dependency.property} have to be defined in properties on pom.xml: "
f"{self.name}")
if ref_prop_element.text != dependency.version:
# if version.parse(dependency.version) < version.parse(ref_prop_element.text):
# raise SystemExit(f"{Fore.RED}{version.parse(dependency.version)} in properties smaller than
# {version.parse(ref_prop_element.text)} on pom.xml: "
# f"{self.name}")
print(f" ---> Dependency update: {dependency.name} {ref_prop_element.text} -> {dependency.version}")
ref_prop_element.text = dependency.version
update = True
# print(pom)
if update:
if write_pom:
print(" Writing POM")
pom.write(self.path + "/pom.xml", encoding="UTF-8")
return True
return False
def call_postchangescripts(self):
_currentDir = os.getcwd() + '/' + self.path
for postchangescript in self.afterversionchange:
if call(postchangescript, shell=True, cwd=_currentDir) != 0:
return False
return True
def call_afterlocalbuildscripts(self):
_currentDir = os.getcwd() + '/' + self.path
for afterlocalbuildscript in self.afterlocalbuild:
_log = tempfile.NamedTemporaryFile()
_ref = None
with open(_log.name, 'w') as f:
_ret = call(afterlocalbuildscript, shell=True, cwd=_currentDir, stdout=f, stderr=f)
if _ret != 0:
with open(_log, "r") as f:
shutil.copyfileobj(f, sys.stdout)
return False
return True
def call_beforelocalbuildscripts(self):
_currentDir = os.getcwd() + '/' + self.path
for beforelocalbuildscript in self.beforelocalbuild:
_log = tempfile.NamedTemporaryFile()
_ref = None
with open(_log.name, 'w') as f:
_ret = call(beforelocalbuildscript, shell=True, cwd=_currentDir, stdout=f, stderr=f)
if _ret != 0:
with open(_log, "r") as f:
shutil.copyfileobj(f, sys.stdout)
return False
return True
def repo(self):
_currentDir = os.getcwd() + '/' + self.path
return git.Repo(_currentDir)
def checkout_branch(self):
_repo = self.repo()
# print(f"{Fore.YELLOW}Checkout branch {Fore.GREEN}{self.branch} {Fore.YELLOW}in {Fore.GREEN}{_repo.git_dir}")
if self.check_dirty():
print(f"{Fore.YELLOW} {self.name } is in dirty state, stashing")
_repo.git.stash(["-u", "-m \"[AUTO STASH]\""])
_updates = _repo.git.fetch(["--force", "origin"])
_updates = _repo.remotes.origin.fetch(progress=CloneProgress())
# for fetch_info in _updates:
# print(f"Tag: {fetch_info.ref} Author: {fetch_info.ref.commit.author} SHA: {fetch_info.ref.commit.hexsha}")
_repo.git.checkout(self.branch)
_repo.head.reset(index=True, working_tree=True)
_repo.remotes.origin.pull(progress=CloneProgress())
def checkout_tags(self):
_repo = self.repo()
_repo.git.fetch(["--tags", "--force", "origin"])
def get_remote_tags(self):
_repo = self.repo()
remote_refs = {}
for ref in _repo.git.ls_remote("--tags").split('\n'):
if not ref.startswith("From "):
hash_ref_list = ref.split('\t')
if len(hash_ref_list) == 2:
if hash_ref_list[1].startswith("refs/tags/"):
remote_refs[hash_ref_list[1].removeprefix("refs/tags/")] = hash_ref_list[0]
return remote_refs
def check_dirty(self):
_currentDir = os.getcwd() + '/' + self.path
_repo = git.Repo(os.getcwd() + '/' + self.path)
return _repo.is_dirty(untracked_files=True)
def commit_and_push_changes(self):
if self.branch == 'master':
print(f"{Fore.RED} Commit to 'master' branch not allowed for module {self.name}")
raise SystemExit(1)
_repo = self.repo()
print(f"{Fore.YELLOW}Commit and push: " + _repo.git_dir)
_repo.git.add(all=True)
prefix = ""
search = re.search("(JNG-\\d+)", self.branch)
if search:
prefix = search.group(0) + " "
_commit_message = f"{prefix}[Release] Updating versions"
if args.ci_skip:
_commit_message = _commit_message + " [ci skip]"
_repo.index.commit(_commit_message)
_origin = _repo.remote(name='origin')
_origin.push()
_repo.git.push()
def create_and_push_empty_commit(self, _commit_message):
if self.branch == 'master':
print(f"{Fore.RED} Commit to 'master' branch not allowed for module {self.name}")
raise SystemExit(1)
_repo = self.repo()
print(f"{Fore.YELLOW}Create empty commit and push: " + _repo.git_dir)
_repo.git.add(all=True)
_repo.index.commit(_commit_message)
_origin = _repo.remote(name='origin')
_origin.push()
_repo.git.push()
def switch_branch(self, _branch_name):
self.branch = _branch_name
if not self.virtual:
self.checkout_branch()
self.checkout_tags()
def create_branch(self, _branch_name):
_repo = github.get_repo(self.github)
if " " in _branch_name:
print(
f"{Fore.YELLOW}Sanitizing branch name: {Fore.GREEN}{_branch_name} {Fore.YELLOW}=> {Fore.GREEN}"
f"{_branch_name.replace(' ', '_')}")
_branch_name = _branch_name.replace(" ", "_")
found = False
for branch in _repo.get_branches():
if str.endswith(branch.name, _branch_name):
found = True
break
if found:
print(f"{Fore.BLUE}Branch already exists with name '{_branch_name}'")
self.switch_branch(_branch_name)
return
# if self._dirty:
# raise SystemExit(f"\n{Fore.RED}Repo have uncommitted changes: {self.name}.")
# _hashes = list(_repo.get_commits())
# if len(_hashes) <= 1:
# raise SystemExit(f"\n{Fore.RED}No commits found on repo: {self.name}.")
# _start_hash = _hashes[-1].sha
_develop = _repo.get_branch("develop")
_branch = None
try:
_branch = _repo.get_git_ref("heads/" + _branch_name)
except UnknownObjectException:
_branch = _repo.create_git_ref("refs/heads/" + _branch_name, sha=_develop.commit.sha)
self.branch = _branch_name
self.checkout_branch()
self.checkout_tags()
prefix = ""
search = re.search("(JNG-\\d+)", _branch_name)
if search:
prefix = search.group(0) + " "
self.create_and_push_empty_commit(f"{prefix}Initial feature commit [ci skip]")
def update_branch_from_git(self):
# get current branch
_repo = self.repo()
self.branch = _repo.active_branch.name
def create_pull_request(self, _message):
_repo = github.get_repo(self.github)
# _branch = _repo.get_git_ref("heads/" + self.branch)
match = re.match("\\w+/(JNG-\\d+.*)", _message)
if match:
_message = match.group(1)
try:
print(
f"{Fore.YELLOW}Creating pull request in {Fore.GREEN}{self.name} {Fore.YELLOW}on branch {Fore.GREEN}"
f"{self.branch}")
_repo.create_pull(
title=_message,
body=_message,
head='refs/heads/' + self.branch,
base='refs/heads/develop',
draft=True,
maintainer_can_modify=True
)
except Exception as e:
print(f"{Fore.RED}Creating pull request in {self.name} on branch {self.branch} failed: {e}")
def perform_release(self):
# Check all dependency is in master branch
for _dep in self.dependencies:
if _dep.branch != "master":
print(f"{Fore.RED} Error in {self.name} - Dependency: {_dep.name} not in master branch, "
f"instead of: {_dep.branch}")
raise SystemExit(1)
print(f"[RELEASE] {Fore.YELLOW}{self.name}: Create 'perform-release-on-{self.version}'")
_tag = self.repo().create_tag("perform-release-on-" + self.version, message="[RELEASE] Perform release")
self.repo().remotes.origin.push(_tag)
print(f"[RELEASE]{Fore.YELLOW}{self.name}: Switch branch to 'master'")
self.switch_branch("master")
print(f"[RELEASE]{Fore.YELLOW}{self.name}: Checkout 'master' branch")
self.checkout_branch()
print(f"[RELEASE]{Fore.YELLOW}{self.name}: Checkout tags")
self.checkout_tags()
print(f"[RELEASE]{Fore.YELLOW}{self.name}: Set last release version")
# self.update_git_tag_versions()
self.fetch_github_versions()
def switch_to_develop(self):
print(f"[DEVELOP]{Fore.YELLOW}{self.name}: Switch branch to 'develop'")
self.switch_branch("develop")
print(f"[DEVELOP]{Fore.YELLOW}{self.name}: Checkout 'develop' branch")
self.checkout_branch()
print(f"[DEVELOP]{Fore.YELLOW}{self.name}: Checkout tags")
self.checkout_tags()
# print(f"[DEVELOP]{Fore.YELLOW}{self.name}: Set last release version")
# self.update_git_tag_versions()
# self.fetch_github_versions()
# Check all dependency is in master branch
for _dep in self.dependencies:
if _dep.branch != "master":
print(f"{Fore.RED} Error in {self.name} - Dependency: {_dep.name} not in master branch, "
f"instead of: {_dep.branch}")
raise SystemExit(1)
def process_module(par, _modules, _module_by_name):
if type(par) is dict:
_new_module = Module(par)
_modules.append(_new_module)
_module_by_name[_new_module.name] = _new_module
elif type(par) is list:
for _item in par:
process_module(_item, _modules, _module_by_name)
def load_modules(_filename="project-meta.yml", _str=""):
if _filename:
with open(_filename, 'r') as stream:
try:
_results = yaml.load(stream, Loader=yaml.FullLoader)
return _results
except yaml.YAMLError as exc:
print(exc)
raise exc
elif _str:
try:
_results = yaml.load(_str, Loader=yaml.FullLoader)
return _results
except yaml.YAMLError as exc:
print(exc)
raise exc
else:
raise SystemExit(f"filename or str have to be defined")
def calculate_graph(_modules):
_g = nx.DiGraph()
for _module in _modules:
_g.add_node(_module)
for _module in _modules:
for _dependency in _module.dependencies:
if _dependency in _modules:
_g.add_edge(_dependency, _module)
return _g
def calculate_reduced_graph(_modules):
_gt = transitive_reduction(calculate_graph(_modules))
return _gt
def calculate_ranks(_modules):
_g = calculate_graph(_modules)
_groups = list(topological_sort_grouped(_g))
_rank = 0
for _group in _groups:
_rank += 1
for _module in _group:
_module.rank = _rank
def slice_modules(_modules, _module_name, _begin):
_sliced_modules = []
_g = calculate_graph(_modules)
_groups = list(topological_sort_grouped(_g))
_found = False
for _group in _groups:
for _module in _group:
if _module.name == _module_name:
_found = True
if _begin and not _found:
_sliced_modules.append(_module)
if not _begin and _found:
_sliced_modules.append(_module)
return _sliced_modules
# Algorithm from: https://stackoverflow.com/questions/56802797/digraph-parallel-ordering
# Edges: (1, 2) (2, 4) (3, 4), (4, 5), (4, 6), (6, 7)
# In [21]: list(nx.topological_sort(G))
# Out[21]: [3, 1, 2, 4, 6, 7, 5]
#
# In [22]: list(topological_sort_grouped(G))
# Out[22]: [[1, 3], [2], [4], [5, 6], [7]]
def topological_sort_grouped(_g):
indegree_map = {v: d for v, d in _g.in_degree() if d > 0}
zero_indegree = [v for v, d in _g.in_degree() if d == 0]
while zero_indegree:
yield zero_indegree
new_zero_indegree = []
for v in zero_indegree:
for _, child in _g.edges(v):
indegree_map[child] -= 1
if not indegree_map[child]:
new_zero_indegree.append(child)
zero_indegree = new_zero_indegree
def scrub_dict(d):
new_dict = {}
for k, v in d.items():
if isinstance(v, dict):
v = scrub_dict(v)
if isinstance(v, list):
v = scrub_list(v)
if v not in (u'', None, {}, []):
new_dict[k] = v
return new_dict
def scrub_list(d):
scrubbed_list = []
for i in d:
if isinstance(i, dict):
i = scrub_dict(i)
scrubbed_list.append(i)
return scrubbed_list
def save_modules(_modules, _module_by_name):
print(f"{Fore.YELLOW}Saving yaml")
_export = []
for _module in _modules:
_module.deresolve_dependencies()
_export.append(scrub_dict(vars(_module)))
with open("project-meta.yml", 'w') as yaml_file:
try:
yaml.dump(_export, yaml_file, default_flow_style=False, allow_unicode=True)
except yaml.YAMLError as exc:
print(exc)
raise exc
for _module in _modules:
_module.resolve_dependencies(_module_by_name)
def check_module_depenencies(_modules, _module_by_name, _fix_dependencies=False):
_errors = []
_pending_changes = False
for _module in _modules:
if not _module.virtual:
for _module_to_check in _modules:
version_in_pom = current_pom_version(_module, _module_to_check)
if version_in_pom:
if _module_to_check not in _module.dependencies:
print(f"{Fore.GREEN}{_module.name}{Fore.YELLOW} - doesn't contain "
f"{Fore.GREEN}{_module_to_check.name}{Fore.YELLOW} in dependencies, but "
f"{Fore.GREEN}{_module.path}/pom.xml{Fore.YELLOW} have "
f"{Fore.GREEN}{_module_to_check.property}")
if _fix_dependencies:
_module.dependencies.append(_module_to_check)
_pending_changes = True
else:
if _module_to_check in _module.dependencies:
_errors.append(f"{Fore.RED}{_module.name} - Property definition "
f"{Fore.GREEN}{_module_to_check.property}{Fore.RED} is missing in "
f"{Fore.GREEN}{_module.path}/pom.xml")
if len(_errors) > 0:
for _error in _errors:
print(f"{_error}\n")
raise SystemExit(f"\n{Fore.RED}Errors found in module dependencies.")
return _pending_changes
def print_dependency_graph(_modules):
_g = calculate_reduced_graph(_modules)
for node in _g.nodes():
_g.nodes[node]['shape'] = 'box'
_g.nodes[node]['label'] = f"{node.name} ({node.rank})"
write_dot(_g, "dependency.dot")
to_pydot(_g).write_svg("dependency.svg")
def print_dependency_graph_ascii(_modules):
_available_modules = set(filter(lambda _m: not _m.ignored and not _m.virtual, _modules))
_g = calculate_graph(_available_modules)
_groups = list(topological_sort_grouped(_g))
for idx in range(len(_groups)):
print(str(idx + 1) + " - " + str(_groups[idx]))
def get_request_handler(_modules, _process_info):
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
body = ""
etag = ""
_g = nx.DiGraph()
for _module in _process_info.keys():
_g.add_node(_module)
for _module in _modules:
for dependency in _module.dependencies:
if dependency in _modules and dependency in _process_info.keys():
_g.add_edge(_module, dependency)
_g = transitive_reduction(_g)
for node in _g.nodes():
_g.nodes[node]['shape'] = 'box'
_g.nodes[node]['label'] = f"{node.name} ({node.rank})"
_g.nodes[node]['fillcolor'] = 'azure3'
_g.nodes[node]['style'] = 'filled'
if _process_info.get(node, {"status": "UNKNOWN"}).get("status") == "UNKNOWN":
_g.nodes[node]['fillcolor'] = 'wheat'
if _process_info.get(node, {"status": "WAITING"}).get("status") == "WAITING":
_g.nodes[node]['fillcolor'] = 'skyblue'
if _process_info.get(node, {"status": ""}).get("status") == "RUNNING":
_g.nodes[node]['fillcolor'] = "yellow"
if _process_info.get(node, {"status": ""}).get("status") == "OK":
_g.nodes[node]['fillcolor'] = "green"
if _process_info.get(node, {"status": ""}).get("status") == "IDLE":
_g.nodes[node]['fillcolor'] = "lightslategrey"
if _process_info.get(node, {"status": ""}).get("status") == "ERROR":
_g.nodes[node]['fillcolor'] = "red"
dot_body = "<div id=\"dot\">" + to_pydot(_g).to_string() + "</div>"
if self.path.endswith('/svg'):
svg = to_pydot(_g).create_svg().decode("utf-8")
message_bytes = svg.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
body = "<embed src=\"data:image/svg+xml;base64," + base64_bytes.decode('ascii') + "\"/>"