-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
git.py
481 lines (393 loc) · 17.3 KB
/
git.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
"""Git-related utilities."""
import re
import git
import structlog
from django.core.exceptions import ValidationError
from git.exc import BadName, InvalidGitRepositoryError, NoSuchPathError
from gitdb.util import hex_to_bin
from readthedocs.builds.constants import BRANCH, EXTERNAL, TAG
from readthedocs.config import ALL
from readthedocs.projects.constants import (
GITHUB_BRAND,
GITHUB_PR_PULL_PATTERN,
GITLAB_BRAND,
GITLAB_MR_PULL_PATTERN,
)
from readthedocs.projects.exceptions import RepositoryError
from readthedocs.projects.validators import validate_submodule_url
from readthedocs.vcs_support.base import BaseVCS, VCSVersion
log = structlog.get_logger(__name__)
class Backend(BaseVCS):
"""Git VCS backend."""
supports_tags = True
supports_branches = True
supports_submodules = True
supports_lsremote = True
fallback_branch = 'master' # default branch
repo_depth = 50
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.token = kwargs.get('token')
self.repo_url = self._get_clone_url()
def _get_clone_url(self):
if '://' in self.repo_url:
hacked_url = self.repo_url.split('://')[1]
hacked_url = re.sub('.git$', '', hacked_url)
clone_url = 'https://%s' % hacked_url
if self.token:
clone_url = 'https://{}@{}'.format(self.token, hacked_url)
return clone_url
# Don't edit URL because all hosts aren't the same
# else:
# clone_url = 'git://%s' % (hacked_url)
return self.repo_url
def set_remote_url(self, url):
return self.run('git', 'remote', 'set-url', 'origin', url)
def update(self, identifier=None):
"""
Clone or update the repository.
:param identifier: This is the optional identifier for git fetch - a branch or tag name.
PR references are generated automatically for certain Git providers.
:return:
"""
super().update(identifier=identifier)
if self.use_clone_fetch_checkout_pattern():
# New behavior: Clone is responsible for skipping the operation if the
# repo is already cloned.
self.clone_ng()
# New behavior: No confusing return value. We are not using return values
# in the callers.
self.fetch_ng(identifier=identifier)
else:
if self.repo_exists():
self.set_remote_url(self.repo_url)
return self.fetch()
self.make_clean_working_dir()
# A fetch is always required to get external versions properly
if self.version_type == EXTERNAL:
self.clone()
return self.fetch()
return self.clone()
def get_remote_fetch_reference(self, identifier):
"""
Gets a valid remote reference for the identifier.
:param identifier: Should be a branch or tag name when building branches or tags.
:return: A reference valid for fetch operation
"""
# Tags and branches have the tag/branch identifier set by the caller who instantiated the
# Git backend -- this means that the build process needs to know this from build data,
# essentially from an incoming webhook call.
if self.version_type in (BRANCH, TAG):
return identifier
if self.version_type == EXTERNAL:
# TODO: We should be able to resolve this without looking up in oauth registry
git_provider_name = self.project.git_provider_name
# TODO: Why are these our only patterns?
if git_provider_name == GITHUB_BRAND:
return GITHUB_PR_PULL_PATTERN.format(id=self.verbose_name)
if self.project.git_provider_name == GITLAB_BRAND:
return GITLAB_MR_PULL_PATTERN.format(id=self.verbose_name)
# This seems to be the default behavior when we don't know the remote
# reference for a PR/MR: Just fetch everything
# TODO: Provide more information about fetch operations without references
return None
def clone_ng(self):
# If the repository is already cloned, we don't do anything.
# This is likely legacy, but we may want to be able to call .update()
# several times in the same build
if self.repo_exists():
return
# --no-checkout: Makes it explicit what we are doing here. Nothing is checked out
# until it's explicitly done.
# --depth 1: Shallow clone, fetch as little data as possible.
cmd = ["git", "clone", "--no-checkout", "--depth", "1", self.repo_url, "."]
code, stdout, stderr = self.run(*cmd)
return code, stdout, stderr
def fetch_ng(self, identifier):
"""Implementation for new clone+fetch+checkout pattern."""
# --force: Likely legacy, it seems to be irrelevant to this usage
# --tags: We need to fetch tags in order to resolve these references in the checkout
# --prune: Likely legacy, we don't expect a previous fetch command to have run
# --prune-tags: Likely legacy, we don't expect a previous fetch command to have run
# --tags: This flag was used in the previous approach such that all tags were fetched
# in order to checkout a tag afterwards.
cmd = ["git", "fetch", "origin", "--force", "--tags", "--prune", "--prune-tags"]
remote_reference = self.get_remote_fetch_reference(identifier)
if remote_reference:
# TODO: We are still fetching the latest 50 commits.
# A PR might have another commit added after the build has started...
cmd.extend(["--depth", self.repo_depth, remote_reference])
code, stdout, stderr = self.run(*cmd)
return code, stdout, stderr
def repo_exists(self):
try:
self._repo
except (InvalidGitRepositoryError, NoSuchPathError):
return False
return True
@property
def _repo(self):
"""Get a `git.Repo` instance from the current `self.working_dir`."""
return git.Repo(self.working_dir, expand_vars=False)
def are_submodules_available(self, config):
"""Test whether git submodule checkout step should be performed."""
submodules_in_config = (
config.submodules.exclude != ALL or config.submodules.include
)
if not submodules_in_config:
return False
# Keep compatibility with previous projects
return bool(self.submodules)
def validate_submodules(self, config):
"""
Returns the submodules and check that its URLs are valid.
.. note::
Always call after `self.are_submodules_available`.
:returns: tuple(bool, list)
Returns `True` if all required submodules URLs are valid.
Returns a list of all required submodules:
- Include is `ALL`, returns all submodules available.
- Include is a list, returns just those.
- Exclude is `ALL` - this should never happen.
- Exclude is a list, returns all available submodules
but those from the list.
Returns `False` if at least one submodule is invalid.
Returns the list of invalid submodules.
"""
submodules = {sub.path: sub for sub in self.submodules}
for sub_path in config.submodules.exclude:
path = sub_path.rstrip('/')
if path in submodules:
del submodules[path]
if config.submodules.include != ALL and config.submodules.include:
submodules_include = {}
for sub_path in config.submodules.include:
path = sub_path.rstrip('/')
submodules_include[path] = submodules[path]
submodules = submodules_include
invalid_submodules = []
for path, submodule in submodules.items():
try:
validate_submodule_url(submodule.url)
except ValidationError:
invalid_submodules.append(path)
if invalid_submodules:
return False, invalid_submodules
return True, submodules.keys()
def use_shallow_clone(self):
"""
Test whether shallow clone should be performed.
.. note::
Temporarily, we support skipping this option as builds that rely on
git history can fail if using shallow clones. This should
eventually be configurable via the web UI.
"""
from readthedocs.projects.models import Feature
return not self.project.has_feature(Feature.DONT_SHALLOW_CLONE)
def use_clone_fetch_checkout_pattern(self):
"""Use the new and optimized clone / fetch / checkout pattern."""
from readthedocs.projects.models import Feature
# TODO: Remove the 'not'
return not self.project.has_feature(Feature.GIT_CLONE_FETCH_CHECKOUT_PATTERN)
def fetch(self):
# --force lets us checkout branches that are not fast-forwarded
# https://github.com/readthedocs/readthedocs.org/issues/6097
cmd = ['git', 'fetch', 'origin',
'--force', '--tags', '--prune', '--prune-tags']
if self.use_shallow_clone():
cmd.extend(['--depth', str(self.repo_depth)])
if self.verbose_name and self.version_type == EXTERNAL:
if self.project.git_provider_name == GITHUB_BRAND:
cmd.append(
GITHUB_PR_PULL_PATTERN.format(id=self.verbose_name)
)
if self.project.git_provider_name == GITLAB_BRAND:
cmd.append(
GITLAB_MR_PULL_PATTERN.format(id=self.verbose_name)
)
code, stdout, stderr = self.run(*cmd)
return code, stdout, stderr
def checkout_revision(self, revision):
try:
code, out, err = self.run('git', 'checkout', '--force', revision)
return [code, out, err]
except RepositoryError:
raise RepositoryError(
RepositoryError.FAILED_TO_CHECKOUT.format(revision),
)
def clone(self):
"""Clones the repository."""
cmd = ['git', 'clone', '--no-single-branch']
if self.use_shallow_clone():
cmd.extend(['--depth', str(self.repo_depth)])
cmd.extend([self.repo_url, '.'])
try:
code, stdout, stderr = self.run(*cmd)
# TODO: for those VCS providers that don't tell us the `default_branch`
# of the repository in the incoming webhook,
# we need to get it from the cloned repository itself.
#
# cmd = ['git', 'symbolic-ref', 'refs/remotes/origin/HEAD']
# _, default_branch, _ = self.run(*cmd)
# default_branch = default_branch.replace('refs/remotes/origin/', '')
#
# The idea is to hit the APIv2 here to update the `latest` version with
# the `default_branch` we just got from the repository itself,
# after clonning it.
# However, we don't know the PK for the version we want to update.
#
# api_v2.version(pk).patch(
# {'default_branch': default_branch}
# )
return code, stdout, stderr
except RepositoryError:
raise RepositoryError(RepositoryError.CLONE_ERROR())
def lsremote(self, include_tags=True, include_branches=True):
"""
Use ``git ls-remote`` to list branches and tags without cloning the repository.
:returns: tuple containing a list of branch and tags
"""
if not include_tags and not include_branches:
return [], []
extra_args = []
if include_tags:
extra_args.append("--tags")
if include_branches:
extra_args.append("--heads")
cmd = ["git", "ls-remote", *extra_args, self.repo_url]
self.check_working_dir()
_, stdout, _ = self.run(*cmd, demux=True, record=False)
branches = []
# Git has two types of tags: lightweight and annotated.
# Lightweight tags are the "normal" ones.
all_tags = {}
light_tags = {}
for line in stdout.splitlines():
commit, ref = line.split(maxsplit=1)
if ref.startswith("refs/heads/"):
branch = ref.replace("refs/heads/", "", 1)
branches.append(VCSVersion(self, branch, branch))
if ref.startswith("refs/tags/"):
tag = ref.replace("refs/tags/", "", 1)
# If the tag is annotated, then the real commit
# will be on the ref ending with ^{}.
if tag.endswith('^{}'):
light_tags[tag[:-3]] = commit
else:
all_tags[tag] = commit
# Merge both tags, lightweight tags will have
# priority over annotated tags.
all_tags.update(light_tags)
tags = [VCSVersion(self, commit, tag) for tag, commit in all_tags.items()]
return branches, tags
@property
def tags(self):
versions = []
repo = self._repo
# Build a cache of tag -> commit
# GitPython is not very optimized for reading large numbers of tags
ref_cache = {} # 'ref/tags/<tag>' -> hexsha
# This code is the same that is executed for each tag in gitpython,
# we execute it only once for all tags.
for hexsha, ref in git.TagReference._iter_packed_refs(repo):
gitobject = git.Object.new_from_sha(repo, hex_to_bin(hexsha))
if gitobject.type == 'commit':
ref_cache[ref] = str(gitobject)
elif gitobject.type == 'tag' and gitobject.object.type == 'commit':
ref_cache[ref] = str(gitobject.object)
for tag in repo.tags:
if tag.path in ref_cache:
hexsha = ref_cache[tag.path]
else:
try:
hexsha = str(tag.commit)
except ValueError:
# ValueError: Cannot resolve commit as tag TAGNAME points to a
# blob object - use the `.object` property instead to access it
# This is not a real tag for us, so we skip it
# https://github.com/rtfd/readthedocs.org/issues/4440
log.warning('Git tag skipped.', tag=tag, exc_info=True)
continue
versions.append(VCSVersion(self, hexsha, str(tag)))
return versions
@property
def branches(self):
repo = self._repo
versions = []
branches = []
# ``repo.remotes.origin.refs`` returns remote branches
if repo.remotes:
branches += repo.remotes.origin.refs
for branch in branches:
verbose_name = branch.name
if verbose_name.startswith("origin/"):
verbose_name = verbose_name.replace("origin/", "", 1)
if verbose_name == "HEAD":
continue
versions.append(
VCSVersion(
repository=self,
identifier=verbose_name,
verbose_name=verbose_name,
)
)
return versions
@property
def commit(self):
if self.repo_exists():
_, stdout, _ = self.run('git', 'rev-parse', 'HEAD', record=False)
return stdout.strip()
return None
@property
def submodules(self):
return list(self._repo.submodules)
def checkout(self, identifier=None):
"""Checkout to identifier or latest."""
super().checkout()
# NOTE: if there is no identifier, we default to default branch cloned
if not identifier:
return
identifier = self.find_ref(identifier)
# Checkout the correct identifier for this branch.
code, out, err = self.checkout_revision(identifier)
# Clean any remains of previous checkouts
self.run('git', 'clean', '-d', '-f', '-f')
return code, out, err
def update_submodules(self, config):
if self.are_submodules_available(config):
valid, submodules = self.validate_submodules(config)
if valid:
self.checkout_submodules(submodules, config)
else:
raise RepositoryError(
RepositoryError.INVALID_SUBMODULES.format(submodules),
)
def checkout_submodules(self, submodules, config):
"""Checkout all repository submodules."""
self.run('git', 'submodule', 'sync')
cmd = [
'git',
'submodule',
'update',
'--init',
'--force',
]
if config.submodules.recursive:
cmd.append('--recursive')
cmd += submodules
self.run(*cmd)
def find_ref(self, ref):
# Check if ref starts with 'origin/'
if ref.startswith('origin/'):
return ref
# Check if ref is a branch of the origin remote
if self.ref_exists('remotes/origin/' + ref):
return 'origin/' + ref
return ref
def ref_exists(self, ref):
try:
if self._repo.commit(ref):
return True
except (BadName, ValueError):
return False
return False