forked from mendersoftware/integration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelease_tool.py
executable file
·3269 lines (2827 loc) · 113 KB
/
release_tool.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
# Copyright 2023 Northern.tech AS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import copy
import json
import os
import re
import shutil
import subprocess
import sys
import traceback
import datetime
try:
import yaml
except ImportError:
print("PyYAML missing, try running 'sudo pip3 install pyyaml'.")
sys.exit(2)
# Disable pager during menu navigation.
os.environ["GIT_PAGER"] = "cat"
# This is basically a YAML file which contains the state of the release tool.
# The easiest way to understand its format is by just looking at it after the
# key fields have been filled in. This is updated continuously while the script
# is operating.
# The repositories are indexed by their Git repository names.
RELEASE_TOOL_STATE = None
GITLAB_SERVER = "https://gitlab.com/api/v4"
GITLAB_JOB = "projects/Northern.tech%2FMender%2Fmender-qa"
GITLAB_TOKEN = None
GITLAB_CREDS_MISSING_ERR = """GitLab credentials not found. Possible locations:
- GITLAB_TOKEN environment variable
- 'pass' password management storage, under "token" label."""
# What we use in commits messages when bumping versions.
VERSION_BUMP_STRING = "chore: Bump versions for Mender"
# Whether or not pushes should really happen.
PUSH = True
# Whether this is a dry-run.
DRY_RUN = False
CONVENTIONAL_COMMIT_REGEX = (
r"^(?P<type>build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)"
r"(?:\(\w+\))?:.*"
)
class NotAVersionException(Exception):
pass
class Component:
COMPONENT_MAPS = None
name = None
type = None
_integration_version = None
def __init__(self, name, type):
self.name = name
self.type = type
def set_integration_version(version):
# If version is a range, use the later version.
if version is not None:
version = version.split("..")[-1]
if Component._integration_version != version:
Component._integration_version = version
# Invalidate cache.
Component.COMPONENT_MAPS = None
def git(self):
if self.type != "git":
raise Exception("Tried to get git name from non-git component")
return self.name
def docker_container(self):
if self.type != "docker_container":
raise Exception(
"Tried to get docker_container name from non-docker_container component"
)
return self.name
def docker_image(self):
if self.type != "docker_image":
raise Exception(
"Tried to get docker_image name from non-docker_image component"
)
return self.name
def set_custom_component_maps(self, maps):
# Set local maps for this object only.
self.COMPONENT_MAPS = maps
@staticmethod
def _initialize_component_maps():
if Component.COMPONENT_MAPS is None:
if Component._integration_version:
component_maps = execute_git(
None,
integration_dir(),
["show", f"{Component._integration_version}:component-maps.yml"],
capture=True,
capture_stderr=False,
)
Component.COMPONENT_MAPS = yaml.safe_load(component_maps)
else:
with open(os.path.join(integration_dir(), "component-maps.yml")) as fd:
Component.COMPONENT_MAPS = yaml.safe_load(fd)
@staticmethod
def get_component_of_type(type, name):
Component._initialize_component_maps()
if Component.COMPONENT_MAPS[type].get(name) is None:
raise KeyError("Component '%s' of type %s not found" % (name, type))
return Component(name, type)
@staticmethod
def get_component_of_any_type(name):
for type in ["git", "docker_image", "docker_container"]:
try:
return Component.get_component_of_type(type, name)
except KeyError:
continue
raise KeyError("Component '%s' not found" % name)
@staticmethod
def get_components_of_type(
type,
only_release=None,
only_non_release=False,
only_independent_component=False,
only_non_independent_component=False,
):
Component._initialize_component_maps()
if only_release is None:
if only_non_release:
only_release = False
else:
only_release = True
if only_release and only_non_release:
raise Exception("only_release and only_non_release can't both be true")
if only_independent_component and only_non_independent_component:
raise Exception(
"only_independent_component and only_non_independent_component can't both be true"
)
components = []
for comp in Component.COMPONENT_MAPS[type]:
is_independent_component = Component(comp, type).is_independent_component()
is_release_component = Component.COMPONENT_MAPS[type][comp][
"release_component"
]
if is_independent_component and only_non_independent_component:
continue
if not is_independent_component and only_independent_component:
continue
if is_release_component and only_non_release:
continue
if not is_release_component and only_release:
continue
components.append(Component(comp, type))
# For testing, not used in production. This prevents listing of
# Enterprise repositories, to ease running in Gitlab when no Enterprise
# credentials are present.
if os.environ.get("TEST_RELEASE_TOOL_LIST_OPEN_SOURCE_ONLY"):
components = [
comp
for comp in components
if comp.git() not in BACKEND_SERVICES_ENT
and comp.git() not in CLIENT_SERVICES_ENT
]
return components
def associated_components_of_type(self, type):
"""Returns all components of type `type` that are associated with self."""
Component._initialize_component_maps()
if type == self.type:
return [Component(self.name, self.type)]
try:
comps = []
for name in self.COMPONENT_MAPS[self.type][self.name][type]:
comps.append(Component(name, type))
return comps
except KeyError:
raise KeyError(
"No such combination: Component '%s' of type %s doesn't have any associated components of type %s"
% (self.name, self.type, type)
)
def is_release_component(self):
Component._initialize_component_maps()
return self.COMPONENT_MAPS[self.type][self.name]["release_component"]
def is_independent_component(self):
Component._initialize_component_maps()
def components_to_try():
yield self
if self.type == "git":
assoc_comp = self.associated_components_of_type("docker_image")
else:
assoc_comp = self.associated_components_of_type("git")
if len(assoc_comp) > 0:
yield assoc_comp[0]
for comp in components_to_try():
independent_component = self.COMPONENT_MAPS[comp.type][comp.name].get(
"independent_component"
)
if independent_component is not None:
return independent_component
return False
# categorize backend services wrt open/enterprise versions
# important for test suite selection
BACKEND_SERVICES_OPEN = {
"iot-manager",
"deviceauth",
"deviceconnect",
"create-artifact-worker",
"deviceconfig",
"reporting",
}
BACKEND_SERVICES_ENT = {
"tenantadm",
"deployments-enterprise",
"deviceauth-enterprise",
"inventory-enterprise",
"useradm-enterprise",
"workflows-enterprise",
"auditlogs",
"mtls-ambassador",
"devicemonitor",
"mender-conductor-enterprise",
"generate-delta-worker",
}
BACKEND_SERVICES_OPEN_ENT = {
"deployments",
"inventory",
"useradm",
"workflows",
"deviceauth",
}
BACKEND_SERVICES = (
BACKEND_SERVICES_OPEN | BACKEND_SERVICES_ENT | BACKEND_SERVICES_OPEN_ENT
)
CLIENT_SERVICES_ENT = {
"mender-binary-delta",
"monitor-client",
"mender-gateway",
}
def build_param(value):
if type(value) is dict:
return value["value"]
else:
return value
EXTRA_BUILDPARAMS_CACHE = None
# Helper to translate repo-something to REPO_SOMETHING_REV
def git_to_buildparam(git_name):
return git_name.replace("-", "_").upper() + "_REV"
def print_line():
print(
"--------------------------------------------------------------------------------"
)
def get_value_from_password_storage(server, key):
"""Gets a value from the 'pass' password storage framework. 'server' is the
server string which should be used to look up the key. If key is None, it
returns the first line, which is usually the password. Other lines are
treated as "key: value" pairs. 'key' can be either a string or a list of
strings."""
if type(key) is str:
keys = [key]
else:
keys = key
try:
# Remove https prefix.
if server.startswith("https://"):
server = server[len("https://") :]
# Remove address part.
if "/" in server:
server = server[: server.index("/")]
pass_dir = os.getenv("PASSWORD_STORE_DIR")
if not pass_dir:
pass_dir = os.path.join(os.getenv("HOME"), ".password-store")
server_path_str = os.getenv("PASS_GITLAB_COM")
if not server_path_str:
output = subprocess.check_output(
["find", pass_dir, "-type", "f", "-path", "*%s*" % server]
).decode()
count = 0
server_paths = []
for line in output.split("\n"):
if line == "":
continue
if line.startswith("%s/" % pass_dir):
line = line[len("%s/" % pass_dir) :]
if line.endswith(".gpg"):
line = line[: -len(".gpg")]
server_paths.append(line)
count += 1
if count == 0:
return None
elif count > 1:
print(
"More than one eligible candidate in 'pass' storage for %s:\n- %s"
% (server, "\n- ".join(server_paths))
)
print(
"Selecting the shortest one. If you wish to override, please set PASS_GITLAB_COM to the correct value."
)
server_path_str = sorted(server_paths, key=len)[0]
print("Attempting to fetch credentials from 'pass' %s..." % (server_path_str))
output = subprocess.check_output(["pass", "show", server_path_str]).decode()
line_no = 0
for line in output.split("\n"):
line_no += 1
if keys is None and line_no == 1:
return line
if line.find(":") < 0:
continue
key, value = line.split(":", 1)
key = key.strip()
value = value.strip()
if key in keys:
return value
except (subprocess.CalledProcessError, FileNotFoundError):
return None
def init_gitlab_creds():
global GITLAB_TOKEN
GITLAB_TOKEN = os.getenv("GITLAB_TOKEN")
if GITLAB_TOKEN is None:
GITLAB_TOKEN = get_value_from_password_storage(GITLAB_SERVER, "token")
def integration_dir():
"""Return the location of the integration repository."""
if os.path.isabs(sys.argv[0]):
return os.path.normpath(os.path.dirname(os.path.dirname(sys.argv[0])))
else:
return os.path.normpath(
os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), "..")
)
def ask(text):
"""Ask a question and return the reply."""
sys.stdout.write(text)
sys.stdout.flush()
reply = sys.stdin.readline().strip()
# Make a separator before next information chunk.
sys.stdout.write("\n")
return reply
def filter_docker_compose_files_list(list, version):
"""Returns a filtered list of known docker-compose files
version shall be one of "git", "docker".
"""
assert version in ["git", "docker"]
def _is_known_yml_file(entry):
return (
entry.startswith("git-versions")
and entry.endswith(".yml")
or entry == "other-components.yml"
or entry == "other-components-docker.yml"
or (entry.startswith("docker-compose") and entry.endswith(".yml"))
)
return [
entry
for entry in list
if _is_known_yml_file(entry)
and (
version == "all"
or (
(version == "git" and "docker" not in entry)
or (version == "docker" and "docker" in entry)
)
)
]
def docker_compose_files_list(dir, version):
"""Return all docker-compose*.yml files in given directory."""
return [
os.path.join(dir, entry)
for entry in filter_docker_compose_files_list(os.listdir(dir), version)
]
def get_docker_compose_data_from_json_list(json_list):
"""Return the Yaml as a simplified structure from the json list:
{
image_name: {
"containers": ["container_name"],
"image_prefix": "mendersoftware/" or "someserver.mender.io/blahblah",
"version": "version",
}
}
"""
data = {}
for json_str in json_list:
json_elem = yaml.safe_load(json_str)
for container, cont_info in json_elem["services"].items():
full_image = cont_info.get("image")
if full_image is None or (
"mendersoftware" not in full_image and "mender.io" not in full_image
):
continue
split = full_image.rsplit(":", 1)
ver = split[1]
split = split[0].rsplit("/", 1)
prefix = split[0]
image = split[1]
if data.get(image):
data[image]["containers"].append(container)
else:
data[image] = {
"containers": [container],
"image_prefix": prefix,
"version": ver,
}
return data
def version_specific_docker_compose_data_patching(data, rev):
"""This is a function which is unfortunately needed to patch legacy docker
compose data which exists in tags. This data is incorrect, but cannot be
fixed because they are tags.
The problem is this: The yml_components() function was changed to query
"git" components first, instead of "docker_image" components, as part of
introducing N-to-N mapping between docker images and git repos
(QA-344). After this it became impossible to query the mender and
monitor-client components, and the reason is that they're missing mappings
in the docker compose data. This went unnoticed before QA-344 because it
ended up querying the docker image instead, which has the same version. But
this is not true anymore.
Therefore, we patch in this modification below, since we cannot fix the
tags. Yes, this is ugly, but at least it's confined to versions below
3.3.0."""
last_comp = rev.split("/")[-1]
if re.match(r"^[0-9]+\.[0-9]\.", last_comp) is None:
# Not a recognized version, assume it's recent in which no change
# needed.
return data
major, minor, patch = last_comp.split(".", 2)
if int(major) > 3 or (int(major) == 3 and int(minor) > 2):
return data
# We need to insert these entries, which may be missing ("may be" because we
# don't check explicitly for more recent release branches or tags).
if data.get("mender") is None and data.get("mender-client-qemu") is not None:
data["mender"] = {
"containers": ["mender"],
"image_prefix": "mendersoftware/",
# In all versions < 3.2, mender-client-qemu version == mender version.
"version": data["mender-client-qemu"]["version"],
}
if last_comp.startswith("3.1.") and data.get("monitor-client") is None:
data["monitor-client"] = {
"containers": ["monitor-client"],
"image_prefix": "mendersoftware/",
# Only monitor-client 1.0.x had this problem, so we can hardcode it.
"version": "1.0.%s" % patch,
}
if (rev == "3.2.0" or rev == "3.2.1") and data.get("reporting") is None:
data["reporting"] = {
"containers": ["mender-reporting"],
"image_prefix": "mendersoftware/",
"version": "master",
}
if rev == "3.2.1":
for comp in [
("mender-artifact", ".0"),
("mender-cli", ".0"),
("mender-binary-delta", ".0"),
("mender-convert", ".2"),
]:
if data.get(comp[0]) is not None and data[comp[0]]["version"].endswith(
".x"
):
data[comp[0]]["version"] = data[comp[0]]["version"][:-2] + comp[1]
return data
def get_docker_compose_data(dir, version="git"):
"""Return docker-compose data from all the YML files in the directory.
See get_docker_compose_data_from_json_list."""
json_list = []
for filename in docker_compose_files_list(dir, version):
with open(filename) as fd:
json_list.append(fd.read())
return get_docker_compose_data_from_json_list(json_list)
def get_docker_compose_data_for_rev(git_dir, rev, version="git"):
"""Return docker-compose data from all the YML files in the given revision.
See get_docker_compose_data_from_json_list."""
try:
yamls = []
files = (
execute_git(None, git_dir, ["ls-tree", "--name-only", rev], capture=True)
.strip()
.split("\n")
)
for filename in filter_docker_compose_files_list(files, version):
output = execute_git(
None, git_dir, ["show", "%s:%s" % (rev, filename)], capture=True
)
yamls.append(output)
data = get_docker_compose_data_from_json_list(yamls)
return version_specific_docker_compose_data_patching(data, rev)
except Exception as ex:
raise Exception("Cannot get docker-compose data for %s" % rev) from ex
def version_of(
integration_dir, component, in_integration_version=None, git_version=True
):
git_components = component.associated_components_of_type("git")
docker_components = component.associated_components_of_type("docker_image")
if git_version:
if len(git_components) != 1:
raise Exception(
"Component %s (type: %s) can not be mapped "
"to a single git component, so its version is ambiguous. "
"Candidates: (%s)"
% (
component.name,
component.type,
", ".join([c.name for c in git_components]),
)
)
image_name = git_components[0].git()
else:
if len(docker_components) != 1:
raise Exception(
"Component %s (type: %s) can not be mapped "
"to a single docker component, so its version is ambiguous. "
"Candidates: (%s)"
% (
component.name,
component.type,
", ".join([c.name for c in docker_components]),
)
)
image_name = docker_components[0].docker_image()
if git_version and git_components[0].git() == "integration":
if in_integration_version is not None:
# Just return the supplied version string.
return in_integration_version
else:
# Return "closest" branch or tag name. Basically we measure the
# distance in commits from the merge base of most refs to the
# current HEAD, and then pick the shortest one, and we assume that
# this is our current version. We pick all the refs from tags and
# local branches, as well as single level upstream branches (which
# avoids pull requests).
return (
subprocess.check_output(
"""
for i in $(git for-each-ref --format='%(refname:short)' 'refs/tags/*' 'refs/heads/*' 'refs/remotes/*/*'); do
echo $(git log --oneline $(git merge-base $i HEAD)..HEAD | wc -l) $i
done | sort -n | head -n1 | awk '{print $2}'
""",
shell=True,
cwd=integration_dir,
)
.strip()
.decode()
)
if in_integration_version is not None:
# Check if there is a range, and if so, return range.
range_type = ""
rev_range = in_integration_version.split("...")
if len(rev_range) > 1:
range_type = "..."
else:
rev_range = in_integration_version.split("..")
if len(rev_range) > 1:
range_type = ".."
repo_range = []
for rev in rev_range:
# Figure out if the user string contained a remote or not
remote = ""
split = rev.split("/", 1)
if len(split) > 1:
remote_candidate = split[0]
ref_name = split[1]
if (
subprocess.call(
"git rev-parse -q --verify refs/heads/%s > /dev/null"
% ref_name,
shell=True,
cwd=integration_dir,
)
== 0
):
remote = remote_candidate + "/"
if not git_version:
data = get_docker_compose_data_for_rev(integration_dir, rev, "docker")
else:
data = get_docker_compose_data_for_rev(integration_dir, rev, "git")
# For pre 2.4.x releases git-versions.*.yml files do not exist hence this listing
# would be missing the backend components. Try loading the old "docker" versions.
if data.get(image_name) is None:
data = get_docker_compose_data_for_rev(
integration_dir, rev, "docker"
)
# If the repository didn't exist in that version, just return all
# commits in that case, IOW no lower end point range.
if data.get(image_name) is not None:
version = data[image_name]["version"]
# If it is a tag, do not prepend remote name
if re.search(r"^[0-9]+\.[0-9]+\.[0-9]+$", version):
repo_range.append(version)
else:
repo_range.append(remote + version)
return range_type.join(repo_range)
else:
if not git_version:
data = get_docker_compose_data(integration_dir, "docker")
else:
data = get_docker_compose_data(integration_dir, "git")
return data[image_name]["version"]
def do_version_of(args):
"""Process --version-of argument."""
if args.version_type is None:
version_type = "git"
else:
version_type = args.version_type
if args.in_integration_version is None:
# Already checked in main()
assert version_type == "git"
else:
assert version_type in ["docker", "git"], (
"%s is not a valid name type for --version-of!" % version_type
)
comp = None
try:
Component.set_integration_version(args.in_integration_version)
if version_type == "git":
comp = Component.get_component_of_type("git", args.version_of)
elif version_type == "docker":
comp = Component.get_component_of_type("docker_image", args.version_of)
except KeyError:
try:
comp = Component.get_component_of_any_type(args.version_of)
except KeyError:
print("Unrecognized repository: %s" % args.version_of)
sys.exit(1)
print(
version_of(
integration_dir(),
comp,
args.in_integration_version,
git_version=(version_type == "git"),
)
)
def do_list_repos(args, optional_too, only_backend, only_client):
"""Lists the repos, using the provided type."""
cli_types = {
"container": "docker_container",
"docker": "docker_image",
"git": "git",
}
assert args.list in cli_types.keys(), "%s is not a valid name type!" % args.list
type = cli_types[args.list]
assert args.list_format in ["simple", "table", "json"], (
"%s is not a valid name list format!" % args.list_format
)
Component.set_integration_version(args.in_integration_version)
repos = Component.get_components_of_type(
type,
only_release=(not optional_too),
only_non_independent_component=(only_backend),
only_independent_component=(only_client),
)
repos.sort(key=lambda x: x.name)
if args.list_format == "simple":
print("\n".join([r.name for r in repos]))
return
repos_versions_dict = {}
for repo in repos:
try:
repos_versions_dict[repo.name] = version_of(
integration_dir(),
repo,
args.in_integration_version,
git_version=(args.list == "git"),
)
except KeyError:
# This repo doesn't exist in the given integration version
repos_versions_dict[repo.name] = "UNRELEASED"
if args.list_format == "table":
name_len_max = str(max([len(r) for r in repos_versions_dict.keys()]))
version_len_max = str(max([len(r) for r in repos_versions_dict.values()]))
row_format = "| {:<" + name_len_max + "} | {:<" + version_len_max + "} |"
print(row_format.format("COMPONENT", "VERSION"))
print(
"\n".join(
[
row_format.format(name, version)
for name, version in repos_versions_dict.items()
]
)
)
elif args.list_format == "json":
json_object = {
"release": repos_versions_dict["integration"],
"repos": list(
map(
lambda item: {"name": item[0], "version": item[1]},
repos_versions_dict.items(),
)
),
}
print(json.dumps(json_object))
def version_sort_key(version):
"""Returns a key used to compare versions."""
components = version.split(".")
assert len(components) == 3, "Invalid version passed to version_sort_key"
major, minor = [int(components[0]), int(components[1])]
patch_and_beta = components[2].split("b")
assert len(patch_and_beta) in [1, 2], "Invalid patch/beta component"
patch = int(patch_and_beta[0])
if len(patch_and_beta) == 2:
beta = int(patch_and_beta[1])
else:
# Just for comparison purposes: rate high.
beta = 99
return "%02d%02d%02d%02d" % (major, minor, patch, beta)
def sorted_final_version_list(git_dir):
"""Returns a sorted list of all final version tags."""
tags = execute_git(
None,
git_dir,
[
"for-each-ref",
"--format=%(refname:short)",
# Two digits for each component ought to be enough...
"refs/tags/[0-9].[0-9].[0-9]",
"refs/tags/[0-9].[0-9].[0-9][0-9]",
"refs/tags/[0-9].[0-9][0-9].[0-9]",
"refs/tags/[0-9].[0-9][0-9].[0-9][0-9]",
"refs/tags/[0-9][0-9].[0-9].[0-9]",
"refs/tags/[0-9][0-9].[0-9].[0-9][0-9]",
"refs/tags/[0-9][0-9].[0-9][0-9].[0-9]",
"refs/tags/[0-9][0-9].[0-9][0-9].[0-9][0-9]",
"refs/tags/[0-9].[0-9].[0-9]b[0-9]",
"refs/tags/[0-9].[0-9].[0-9][0-9]b[0-9]",
"refs/tags/[0-9].[0-9][0-9].[0-9]b[0-9]",
"refs/tags/[0-9].[0-9][0-9].[0-9][0-9]b[0-9]",
"refs/tags/[0-9][0-9].[0-9].[0-9]b[0-9]",
"refs/tags/[0-9][0-9].[0-9].[0-9][0-9]b[0-9]",
"refs/tags/[0-9][0-9].[0-9][0-9].[0-9]b[0-9]",
"refs/tags/[0-9][0-9].[0-9][0-9].[0-9][0-9]b[0-9]",
],
capture=True,
)
return sorted(tags.split(), key=version_sort_key, reverse=True)
def state_value(state, key_list):
"""Gets a value from the state variable stored in the RELEASE_TOOL_STATE yaml
file. The key_list is a list of indexes, where each element represents a
subkey of the previous key.
The difference between this function and simply indexing 'state' directly is
that if any subkey is not found, including parent keys, None is returned
instead of exception.
"""
try:
next = state
for key in key_list:
next = next[key]
return next
except KeyError:
return None
def update_state(state, key_list, value):
"""Updates the state variable and writes this to the RELEASE_TOOL_STATE state
file. key_list is the same value as the state_value function."""
next = state
prev = state
for key in key_list:
prev = next
if next.get(key) is None:
next[key] = {}
next = next[key]
prev[key_list[-1]] = value
fd = open(RELEASE_TOOL_STATE, "w")
fd.write(yaml.dump(state))
fd.close()
def execute_git(state, repo_git, args, capture=False, capture_stderr=False):
"""Executes a Git command in the given repository, with args being a list
of arguments (not including git itself). capture and capture_stderr
arguments causes it to return stdout or stdout+stderr as a string.
state can be None, but if so, then repo_git needs to be an absolute path.
The function automatically takes into account Git commands with side effects
and applies push simulation and dry run if those are enabled."""
is_push = args[0] == "push"
is_change = (
is_push
or (args[0] == "tag" and len(args) > 1)
or (args[0] == "branch" and len(args) > 1)
or (args[0] == "config" and args[1] != "-l")
or (args[0] == "checkout")
or (args[0] == "commit")
or (args[0] == "fetch")
or (args[0] == "init")
or (args[0] == "reset")
)
if os.path.isabs(repo_git):
git_dir = repo_git
else:
git_dir = os.path.join(state["repo_dir"], repo_git)
if (not PUSH and is_push) or (DRY_RUN and is_change):
print("Would have executed: cd %s && git %s" % (git_dir, " ".join(args)))
return None
fd = os.open(".", flags=os.O_RDONLY)
os.chdir(git_dir)
if capture_stderr:
stderr = subprocess.STDOUT
else:
stderr = None
try:
if capture:
output = (
subprocess.check_output(["git"] + args, stderr=stderr).decode().strip()
)
else:
output = None
subprocess.check_call(["git"] + args, stderr=stderr)
finally:
os.fchdir(fd)
os.close(fd)
return output
def query_execute_git_list(execute_git_list):
"""Executes a list of Git commands after asking permission. The argument is
a list of triplets with the first three arguments of execute_git. Both
capture flags will be false during this call."""
print_line()
for cmd in execute_git_list:
# Provide quotes around arguments with spaces in them.
print(
"cd %s && git %s"
% (
cmd[1],
" ".join(
['"%s"' % str if str.find(" ") >= 0 else str for str in cmd[2]]
),
)
)
reply = ask("\nOk to execute the above commands? ")
if not reply.startswith("Y") and not reply.startswith("y"):
return False
for cmd in execute_git_list:
execute_git(cmd[0], cmd[1], cmd[2])
return True
def query_execute_list(execute_list, env=None):
"""Executes the list of commands after asking first. The argument is a list of
lists, where the inner list is the argument to subprocess.check_call.
The function automatically takes into account Docker commands with side
effects and applies push simulation and dry run if those are enabled.
"""
print_line()
for cmd in execute_list:
# Provide quotes around arguments with spaces in them.
print(" ".join(['"%s"' % str if str.find(" ") >= 0 else str for str in cmd]))
reply = ask("\nOk to execute the above commands? ")
if not reply.startswith("Y") and not reply.startswith("y"):
return False
for cmd in execute_list:
is_push = cmd[0] == "docker" and cmd[1] == "push"
is_change = is_push or (cmd[0] == "docker" and cmd[1] == "tag")
if (not PUSH and is_push) or (DRY_RUN and is_change):
print("Would have executed: %s" % " ".join(cmd))
continue
subprocess.check_call(cmd, env=env)
return True
def setup_temp_git_checkout(state, repo_git, ref):
"""Checks out a temporary Git directory, and returns an absolute path to
it. Checks out the ref specified in ref."""