This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
mirrored from https://android.googlesource.com/tools/repo
-
Notifications
You must be signed in to change notification settings - Fork 146
/
repo
executable file
·1495 lines (1266 loc) · 46.1 KB
/
repo
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 (C) 2008 The Android Open Source Project
#
# 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.
"""Repo launcher.
This is a standalone tool that people may copy to anywhere in their system.
It is used to get an initial repo client checkout, and after that it runs the
copy of repo in the checkout.
"""
import datetime
import os
import platform
import shlex
import subprocess
import sys
# These should never be newer than the main.py version since this needs to be a
# bit more flexible with older systems. See that file for more details on the
# versions we select.
MIN_PYTHON_VERSION_SOFT = (3, 6)
MIN_PYTHON_VERSION_HARD = (3, 6)
# Keep basic logic in sync with repo_trace.py.
class Trace:
"""Trace helper logic."""
REPO_TRACE = "REPO_TRACE"
def __init__(self):
self.set(os.environ.get(self.REPO_TRACE) == "1")
def set(self, value):
self.enabled = bool(value)
def print(self, *args, **kwargs):
if self.enabled:
print(*args, **kwargs)
trace = Trace()
def exec_command(cmd):
"""Execute |cmd| or return None on failure."""
trace.print(":", " ".join(cmd))
try:
if platform.system() == "Windows":
ret = subprocess.call(cmd)
sys.exit(ret)
else:
os.execvp(cmd[0], cmd)
except Exception:
pass
def check_python_version():
"""Make sure the active Python version is recent enough."""
def reexec(prog):
exec_command([prog] + sys.argv)
ver = sys.version_info
major = ver.major
minor = ver.minor
# Try to re-exec the version specific Python if needed.
if (major, minor) < MIN_PYTHON_VERSION_SOFT:
# Python makes releases ~once a year, so try our min version +10 to help
# bridge the gap. This is the fallback anyways so perf isn't critical.
min_major, min_minor = MIN_PYTHON_VERSION_SOFT
for inc in range(0, 10):
reexec(f"python{min_major}.{min_minor + inc}")
# Fallback to older versions if possible.
for inc in range(
MIN_PYTHON_VERSION_SOFT[1] - MIN_PYTHON_VERSION_HARD[1], 0, -1
):
# Don't downgrade, and don't reexec ourselves (which would infinite loop).
if (min_major, min_minor - inc) <= (major, minor):
break
reexec(f"python{min_major}.{min_minor - inc}")
# We're still here, so diagnose things for the user.
if (major, minor) < MIN_PYTHON_VERSION_HARD:
print(
"repo: error: Python version is too old; "
"Please use Python {}.{} or newer.".format(
*MIN_PYTHON_VERSION_HARD
),
file=sys.stderr,
)
sys.exit(1)
if __name__ == "__main__":
check_python_version()
# repo default configuration
#
REPO_URL = os.environ.get("REPO_URL", None)
if not REPO_URL:
REPO_URL = "https://gerrit.googlesource.com/git-repo"
REPO_REV = os.environ.get("REPO_REV")
if not REPO_REV:
REPO_REV = "stable"
# URL to file bug reports for repo tool issues.
BUG_URL = "https://issues.gerritcodereview.com/issues/new?component=1370071"
# increment this whenever we make important changes to this script
VERSION = (2, 50)
# increment this if the MAINTAINER_KEYS block is modified
KEYRING_VERSION = (2, 3)
# Each individual key entry is created by using:
# gpg --armor --export keyid
MAINTAINER_KEYS = """
Repo Maintainer <repo@android.kernel.org>
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzOb
fbfbA/4ioOrxy8ifSoga7ITyZMA+XbW8bx33WXutO9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fUFI3zaGdMDcMFju1cWt2Un8E3gtscGufzbz1Z5Z
Gak+tCOWUyuYNWX3noit7Dk6+3JGHGaQettldNu2PLM9SbIXd2EaqK/eEv9BS3dd
ItkZwzyZXSaQ9UqAceY1AHskJJ5KVXIRLuhP5jBWWo3fnRMyMYt2nwNBAJ9B9TA8
VlBniwIl5EzCvOFOTGrtewCdHOvr3N3ieypGz1BzyCN9tJMO3G24MwReRal9Fgkr
BgEEAdpHDwEBB0BhPE/je6OuKgWzJ1mnrUmHhn4IMOHp+58+T5kHU3Oy6YjXBBgR
AgAgFiEEi7mteT6OYVOvD5pEFlMNXpIPXGUFAl5FqX0CGwIAgQkQFlMNXpIPXGV2
IAQZFggAHRYhBOH5BA16P22vrIl809O5XaJD5Io5BQJeRal9AAoJENO5XaJD5Io5
MEkA/3uLmiwANOcgE0zB9zga0T/KkYhYOWFx7zRyDhrTf9spAPwIfSBOAGtwxjLO
DCce5OaQJl/YuGHvXq2yx5h7T8pdAZ+PAJ4qfIk2LLSidsplTDXOKhOQAuOqUQCf
cZ7aFsJF4PtcDrfdejyAxbtsSHI=
=82Tj
-----END PGP PUBLIC KEY BLOCK-----
"""
GIT = "git" # our git command
# NB: The version of git that the repo launcher requires may be much older than
# the version of git that the main repo source tree requires. Keeping this at
# an older version also makes it easier for users to upgrade/rollback as needed.
MIN_GIT_VERSION = (1, 7, 9) # minimum supported git version
repodir = ".repo" # name of repo's private directory
S_repo = "repo" # special repo repository
S_manifests = "manifests" # special manifest repository
REPO_MAIN = S_repo + "/main.py" # main script
GITC_CONFIG_FILE = "/gitc/.config"
GITC_FS_ROOT_DIR = "/gitc/manifest-rw/"
import collections
import errno
import json
import optparse
import re
import shutil
import stat
import urllib.error
import urllib.request
repo_config_dir = os.getenv("REPO_CONFIG_DIR", os.path.expanduser("~"))
home_dot_repo = os.path.join(repo_config_dir, ".repoconfig")
gpg_dir = os.path.join(home_dot_repo, "gnupg")
def GetParser(gitc_init=False):
"""Setup the CLI parser."""
if gitc_init:
sys.exit("repo: fatal: GITC not supported.")
else:
usage = "repo init [options] [-u] url"
parser = optparse.OptionParser(usage=usage)
InitParser(parser)
return parser
def InitParser(parser):
"""Setup the CLI parser."""
# NB: Keep in sync with command.py:_CommonOptions().
# Logging.
group = parser.add_option_group("Logging options")
group.add_option(
"-v",
"--verbose",
dest="output_mode",
action="store_true",
help="show all output",
)
group.add_option(
"-q",
"--quiet",
dest="output_mode",
action="store_false",
help="only show errors",
)
# Manifest.
group = parser.add_option_group("Manifest options")
group.add_option(
"-u",
"--manifest-url",
help="manifest repository location",
metavar="URL",
)
group.add_option(
"-b",
"--manifest-branch",
metavar="REVISION",
help="manifest branch or revision (use HEAD for default)",
)
group.add_option(
"--manifest-upstream-branch",
help="when a commit is provided to --manifest-branch, this "
"is the name of the git ref in which the commit can be found",
metavar="BRANCH",
)
group.add_option(
"-m",
"--manifest-name",
default="default.xml",
help="initial manifest file",
metavar="NAME.xml",
)
group.add_option(
"-g",
"--groups",
default="default",
help="restrict manifest projects to ones with specified "
"group(s) [default|all|G1,G2,G3|G4,-G5,-G6]",
metavar="GROUP",
)
group.add_option(
"-p",
"--platform",
default="auto",
help="restrict manifest projects to ones with a specified "
"platform group [auto|all|none|linux|darwin|...]",
metavar="PLATFORM",
)
group.add_option(
"--submodules",
action="store_true",
help="sync any submodules associated with the manifest repo",
)
group.add_option(
"--standalone-manifest",
action="store_true",
help="download the manifest as a static file "
"rather then create a git checkout of "
"the manifest repo",
)
group.add_option(
"--manifest-depth",
type="int",
default=0,
metavar="DEPTH",
help="create a shallow clone of the manifest repo with "
"given depth (0 for full clone); see git clone "
"(default: %default)",
)
# Options that only affect manifest project, and not any of the projects
# specified in the manifest itself.
group = parser.add_option_group("Manifest (only) checkout options")
group.add_option(
"--current-branch",
"-c",
default=True,
dest="current_branch_only",
action="store_true",
help="fetch only current manifest branch from server (default)",
)
group.add_option(
"--no-current-branch",
dest="current_branch_only",
action="store_false",
help="fetch all manifest branches from server",
)
group.add_option(
"--tags", action="store_true", help="fetch tags in the manifest"
)
group.add_option(
"--no-tags",
dest="tags",
action="store_false",
help="don't fetch tags in the manifest",
)
# These are fundamentally different ways of structuring the checkout.
group = parser.add_option_group("Checkout modes")
group.add_option(
"--mirror",
action="store_true",
help="create a replica of the remote repositories "
"rather than a client working directory",
)
group.add_option(
"--archive",
action="store_true",
help="checkout an archive instead of a git repository for "
"each project. See git archive.",
)
group.add_option(
"--worktree",
action="store_true",
help="use git-worktree to manage projects",
)
# These are fundamentally different ways of structuring the checkout.
group = parser.add_option_group("Project checkout optimizations")
group.add_option(
"--reference", help="location of mirror directory", metavar="DIR"
)
group.add_option(
"--dissociate",
action="store_true",
help="dissociate from reference mirrors after clone",
)
group.add_option(
"--depth",
type="int",
default=None,
help="create a shallow clone with given depth; " "see git clone",
)
group.add_option(
"--partial-clone",
action="store_true",
help="perform partial clone (https://git-scm.com/"
"docs/gitrepository-layout#_code_partialclone_code)",
)
group.add_option(
"--no-partial-clone",
action="store_false",
help="disable use of partial clone (https://git-scm.com/"
"docs/gitrepository-layout#_code_partialclone_code)",
)
group.add_option(
"--partial-clone-exclude",
action="store",
help="exclude the specified projects (a comma-delimited "
"project names) from partial clone (https://git-scm.com"
"/docs/gitrepository-layout#_code_partialclone_code)",
)
group.add_option(
"--clone-filter",
action="store",
default="blob:none",
help="filter for use with --partial-clone " "[default: %default]",
)
group.add_option(
"--use-superproject",
action="store_true",
default=None,
help="use the manifest superproject to sync projects; implies -c",
)
group.add_option(
"--no-use-superproject",
action="store_false",
dest="use_superproject",
help="disable use of manifest superprojects",
)
group.add_option(
"--clone-bundle",
action="store_true",
help="enable use of /clone.bundle on HTTP/HTTPS "
"(default if not --partial-clone)",
)
group.add_option(
"--no-clone-bundle",
dest="clone_bundle",
action="store_false",
help="disable use of /clone.bundle on HTTP/HTTPS (default if --partial-clone)",
)
group.add_option(
"--git-lfs", action="store_true", help="enable Git LFS support"
)
group.add_option(
"--no-git-lfs",
dest="git_lfs",
action="store_false",
help="disable Git LFS support",
)
# Tool.
group = parser.add_option_group("repo Version options")
group.add_option(
"--repo-url", metavar="URL", help="repo repository location ($REPO_URL)"
)
group.add_option(
"--repo-rev", metavar="REV", help="repo branch or revision ($REPO_REV)"
)
group.add_option(
"--repo-branch", dest="repo_rev", help=optparse.SUPPRESS_HELP
)
group.add_option(
"--no-repo-verify",
dest="repo_verify",
default=True,
action="store_false",
help="do not verify repo source code",
)
# Other.
group = parser.add_option_group("Other options")
group.add_option(
"--config-name",
action="store_true",
default=False,
help="Always prompt for name/e-mail",
)
return parser
# This is a poor replacement for subprocess.run until we require Python 3.6+.
RunResult = collections.namedtuple(
"RunResult", ("returncode", "stdout", "stderr")
)
class RunError(Exception):
"""Error when running a command failed."""
def run_command(cmd, **kwargs):
"""Run |cmd| and return its output."""
check = kwargs.pop("check", False)
if kwargs.pop("capture_output", False):
kwargs.setdefault("stdout", subprocess.PIPE)
kwargs.setdefault("stderr", subprocess.PIPE)
cmd_input = kwargs.pop("input", None)
def decode(output):
"""Decode |output| to text."""
if output is None:
return output
try:
return output.decode("utf-8")
except UnicodeError:
print(
f"repo: warning: Invalid UTF-8 output:\ncmd: {cmd!r}\n{output}",
file=sys.stderr,
)
return output.decode("utf-8", "backslashreplace")
# Run & package the results.
proc = subprocess.Popen(cmd, **kwargs)
(stdout, stderr) = proc.communicate(input=cmd_input)
dbg = ": " + " ".join(cmd)
if cmd_input is not None:
dbg += " 0<|"
if stdout == subprocess.PIPE:
dbg += " 1>|"
if stderr == subprocess.PIPE:
dbg += " 2>|"
elif stderr == subprocess.STDOUT:
dbg += " 2>&1"
trace.print(dbg)
ret = RunResult(proc.returncode, decode(stdout), decode(stderr))
# If things failed, print useful debugging output.
if check and ret.returncode:
print(
f'repo: error: "{cmd[0]}" failed with exit status {ret.returncode}',
file=sys.stderr,
)
cwd = kwargs.get("cwd", os.getcwd())
print(f" cwd: {cwd}\n cmd: {cmd!r}", file=sys.stderr)
def _print_output(name, output):
if output:
print(
f" {name}:"
+ "".join(f"\n >> {x}" for x in output.splitlines()),
file=sys.stderr,
)
_print_output("stdout", ret.stdout)
_print_output("stderr", ret.stderr)
raise RunError(ret)
return ret
_gitc_manifest_dir = None
def get_gitc_manifest_dir():
global _gitc_manifest_dir
if _gitc_manifest_dir is None:
_gitc_manifest_dir = ""
try:
with open(GITC_CONFIG_FILE) as gitc_config:
for line in gitc_config:
match = re.match("gitc_dir=(?P<gitc_manifest_dir>.*)", line)
if match:
_gitc_manifest_dir = match.group("gitc_manifest_dir")
except OSError:
pass
return _gitc_manifest_dir
def gitc_parse_clientdir(gitc_fs_path):
"""Parse a path in the GITC FS and return its client name.
Args:
gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
Returns:
The GITC client name.
"""
if gitc_fs_path == GITC_FS_ROOT_DIR:
return None
if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
manifest_dir = get_gitc_manifest_dir()
if manifest_dir == "":
return None
if manifest_dir[-1] != "/":
manifest_dir += "/"
if gitc_fs_path == manifest_dir:
return None
if not gitc_fs_path.startswith(manifest_dir):
return None
return gitc_fs_path.split(manifest_dir)[1].split("/")[0]
return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split("/")[0]
class CloneFailure(Exception):
"""Indicate the remote clone of repo itself failed."""
def check_repo_verify(repo_verify, quiet=False):
"""Check the --repo-verify state."""
if not repo_verify:
print(
"repo: warning: verification of repo code has been disabled;\n"
"repo will not be able to verify the integrity of itself.\n",
file=sys.stderr,
)
return False
if NeedSetupGnuPG():
return SetupGnuPG(quiet)
return True
def check_repo_rev(dst, rev, repo_verify=True, quiet=False):
"""Check that |rev| is valid."""
do_verify = check_repo_verify(repo_verify, quiet=quiet)
remote_ref, local_rev = resolve_repo_rev(dst, rev)
if not quiet and not remote_ref.startswith("refs/heads/"):
print(
"warning: repo is not tracking a remote branch, so it will not "
"receive updates",
file=sys.stderr,
)
if do_verify:
rev = verify_rev(dst, remote_ref, local_rev, quiet)
else:
rev = local_rev
return (remote_ref, rev)
def _Init(args, gitc_init=False):
"""Installs repo by cloning it over the network."""
parser = GetParser(gitc_init=gitc_init)
opt, args = parser.parse_args(args)
if args:
if not opt.manifest_url:
opt.manifest_url = args.pop(0)
if args:
parser.print_usage()
sys.exit(1)
opt.quiet = opt.output_mode is False
opt.verbose = opt.output_mode is True
if opt.clone_bundle is None:
opt.clone_bundle = False if opt.partial_clone else True
url = opt.repo_url or REPO_URL
rev = opt.repo_rev or REPO_REV
try:
os.mkdir(repodir)
except OSError as e:
if e.errno != errno.EEXIST:
print(
f"fatal: cannot make {repodir} directory: {e.strerror}",
file=sys.stderr,
)
# Don't raise CloneFailure; that would delete the
# name. Instead exit immediately.
#
sys.exit(1)
_CheckGitVersion()
try:
if not opt.quiet:
print("Downloading Repo source from", url)
dst_final = os.path.abspath(os.path.join(repodir, S_repo))
dst = dst_final + ".tmp"
shutil.rmtree(dst, ignore_errors=True)
_Clone(url, dst, opt.clone_bundle, opt.quiet, opt.verbose)
remote_ref, rev = check_repo_rev(
dst, rev, opt.repo_verify, quiet=opt.quiet
)
_Checkout(dst, remote_ref, rev, opt.quiet)
if not os.path.isfile(os.path.join(dst, "repo")):
print(
"fatal: '%s' does not look like a git-repo repository, is "
"--repo-url set correctly?" % url,
file=sys.stderr,
)
raise CloneFailure()
os.rename(dst, dst_final)
except CloneFailure:
print("fatal: double check your --repo-rev setting.", file=sys.stderr)
if opt.quiet:
print(
"fatal: repo init failed; run without --quiet to see why",
file=sys.stderr,
)
raise
def run_git(*args, **kwargs):
"""Run git and return execution details."""
kwargs.setdefault("capture_output", True)
kwargs.setdefault("check", True)
try:
return run_command([GIT] + list(args), **kwargs)
except OSError as e:
print(file=sys.stderr)
print('repo: error: "%s" is not available' % GIT, file=sys.stderr)
print("repo: error: %s" % e, file=sys.stderr)
print(file=sys.stderr)
print(
"Please make sure %s is installed and in your path." % GIT,
file=sys.stderr,
)
sys.exit(1)
except RunError:
raise CloneFailure()
# The git version info broken down into components for easy analysis.
# Similar to Python's sys.version_info.
GitVersion = collections.namedtuple(
"GitVersion", ("major", "minor", "micro", "full")
)
def ParseGitVersion(ver_str=None):
if ver_str is None:
# Load the version ourselves.
ver_str = run_git("--version").stdout
if not ver_str.startswith("git version "):
return None
full_version = ver_str[len("git version ") :].strip()
num_ver_str = full_version.split("-")[0]
to_tuple = []
for num_str in num_ver_str.split(".")[:3]:
if num_str.isdigit():
to_tuple.append(int(num_str))
else:
to_tuple.append(0)
to_tuple.append(full_version)
return GitVersion(*to_tuple)
def _CheckGitVersion():
ver_act = ParseGitVersion()
if ver_act is None:
print("fatal: unable to detect git version", file=sys.stderr)
raise CloneFailure()
if ver_act < MIN_GIT_VERSION:
need = ".".join(map(str, MIN_GIT_VERSION))
print(
f"fatal: git {need} or later required; found {ver_act.full}",
file=sys.stderr,
)
raise CloneFailure()
def SetGitTrace2ParentSid(env=None):
"""Set up GIT_TRACE2_PARENT_SID for git tracing."""
# We roughly follow the format git itself uses in trace2/tr2_sid.c.
# (1) Be unique (2) be valid filename (3) be fixed length.
#
# Since we always export this variable, we try to avoid more expensive calls.
# e.g. We don't attempt hostname lookups or hashing the results.
if env is None:
env = os.environ
KEY = "GIT_TRACE2_PARENT_SID"
now = datetime.datetime.now(datetime.timezone.utc)
timestamp = now.strftime("%Y%m%dT%H%M%SZ")
value = f"repo-{timestamp}-P{os.getpid():08x}"
# If it's already set, then append ourselves.
if KEY in env:
value = env[KEY] + "/" + value
_setenv(KEY, value, env=env)
def _setenv(key, value, env=None):
"""Set |key| in the OS environment |env| to |value|."""
if env is None:
env = os.environ
# Environment handling across systems is messy.
try:
env[key] = value
except UnicodeEncodeError:
env[key] = value.encode()
def NeedSetupGnuPG():
if not os.path.isdir(home_dot_repo):
return True
kv = os.path.join(home_dot_repo, "keyring-version")
if not os.path.exists(kv):
return True
kv = open(kv).read()
if not kv:
return True
kv = tuple(map(int, kv.split(".")))
if kv < KEYRING_VERSION:
return True
return False
def SetupGnuPG(quiet):
try:
os.mkdir(home_dot_repo)
except OSError as e:
if e.errno != errno.EEXIST:
print(
f"fatal: cannot make {home_dot_repo} directory: {e.strerror}",
file=sys.stderr,
)
sys.exit(1)
try:
os.mkdir(gpg_dir, stat.S_IRWXU)
except OSError as e:
if e.errno != errno.EEXIST:
print(
f"fatal: cannot make {gpg_dir} directory: {e.strerror}",
file=sys.stderr,
)
sys.exit(1)
if not quiet:
print(
"repo: Updating release signing keys to keyset ver "
+ ".".join(str(x) for x in KEYRING_VERSION),
)
# NB: We use --homedir (and cwd below) because some environments (Windows) do
# not correctly handle full native paths. We avoid the issue by changing to
# the right dir with cwd=gpg_dir before executing gpg, and then telling gpg to
# use the cwd (.) as its homedir which leaves the path resolution logic to it.
cmd = ["gpg", "--homedir", ".", "--import"]
try:
# gpg can be pretty chatty. Always capture the output and if something goes
# wrong, the builtin check failure will dump stdout & stderr for debugging.
run_command(
cmd,
stdin=subprocess.PIPE,
capture_output=True,
cwd=gpg_dir,
check=True,
input=MAINTAINER_KEYS.encode("utf-8"),
)
except OSError:
if not quiet:
print("warning: gpg (GnuPG) is not available.", file=sys.stderr)
print(
"warning: Installing it is strongly encouraged.",
file=sys.stderr,
)
print(file=sys.stderr)
return False
with open(os.path.join(home_dot_repo, "keyring-version"), "w") as fd:
fd.write(".".join(map(str, KEYRING_VERSION)) + "\n")
return True
def _SetConfig(cwd, name, value):
"""Set a git configuration option to the specified value."""
run_git("config", name, value, cwd=cwd)
def _GetRepoConfig(name):
"""Read a repo configuration option."""
config = os.path.join(home_dot_repo, "config")
if not os.path.exists(config):
return None
cmd = ["config", "--file", config, "--get", name]
ret = run_git(*cmd, check=False)
if ret.returncode == 0:
return ret.stdout
elif ret.returncode == 1:
return None
else:
print(
f"repo: error: git {' '.join(cmd)} failed:\n{ret.stderr}",
file=sys.stderr,
)
raise RunError()
def _InitHttp():
handlers = []
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
try:
import netrc
n = netrc.netrc()
for host in n.hosts:
p = n.hosts[host]
mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
except Exception:
pass
handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
if "http_proxy" in os.environ:
url = os.environ["http_proxy"]
handlers.append(
urllib.request.ProxyHandler({"http": url, "https": url})
)
if "REPO_CURL_VERBOSE" in os.environ:
handlers.append(urllib.request.HTTPHandler(debuglevel=1))
handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
urllib.request.install_opener(urllib.request.build_opener(*handlers))
def _Fetch(url, cwd, src, quiet, verbose):
cmd = ["fetch"]
if not verbose:
cmd.append("--quiet")
err = None
if not quiet and sys.stdout.isatty():
cmd.append("--progress")
elif not verbose:
err = subprocess.PIPE
cmd.append(src)
cmd.append("+refs/heads/*:refs/remotes/origin/*")
cmd.append("+refs/tags/*:refs/tags/*")
run_git(*cmd, stderr=err, capture_output=False, cwd=cwd)
def _DownloadBundle(url, cwd, quiet, verbose):
if not url.endswith("/"):
url += "/"
url += "clone.bundle"
ret = run_git(
"config", "--get-regexp", "url.*.insteadof", cwd=cwd, check=False
)
for line in ret.stdout.splitlines():
m = re.compile(r"^url\.(.*)\.insteadof (.*)$").match(line)
if m:
new_url = m.group(1)
old_url = m.group(2)
if url.startswith(old_url):
url = new_url + url[len(old_url) :]
break
if not url.startswith("http:") and not url.startswith("https:"):
return False
dest = open(os.path.join(cwd, ".git", "clone.bundle"), "w+b")
try:
try:
r = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
if e.code not in [400, 401, 403, 404, 501]:
print("warning: Cannot get %s" % url, file=sys.stderr)
print("warning: HTTP error %s" % e.code, file=sys.stderr)
return False
except urllib.error.URLError as e:
print("fatal: Cannot get %s" % url, file=sys.stderr)
print("fatal: error %s" % e.reason, file=sys.stderr)
raise CloneFailure()
try:
if verbose:
print("Downloading clone bundle %s" % url, file=sys.stderr)
while True:
buf = r.read(8192)
if not buf:
return True
dest.write(buf)
finally:
r.close()
finally:
dest.close()
def _ImportBundle(cwd):
path = os.path.join(cwd, ".git", "clone.bundle")
try:
_Fetch(cwd, cwd, path, True, False)
finally:
os.remove(path)