Debian Codegraph @

src/buildstream_plugins/sources/git.py

raw
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 #
14 # Authors:
15 # Tristan Van Berkom <[email protected]>
16 # Chandan Singh <[email protected]>
17 # Tom Mewett <[email protected]>
18
19 #
20 # This plugin was originally developped in the https://github.com/apache/buildstream/
21 # repository and was copied from 1a3c707a6c46573ab159de64ac9cd92e7f6027e6
22 #
23
24 """
25 git - stage files from a git repository
26 =======================================
27
28 **Host dependencies:**
29
30 * git
31
32 .. attention::
33
34 Note that this plugin **will checkout git submodules by default**; even if
35 they are not specified in the `.bst` file.
36
37 **Usage:**
38
39 .. code:: yaml
40
41 # Specify the git source kind
42 kind: git
43
44 # Specify the repository url, using an alias defined
45 # in your project configuration is recommended.
46 url: upstream:foo.git
47
48 # Optionally specify a symbolic tracking branch or tag, this
49 # will be used to update the 'ref' when refreshing the pipeline.
50 track: master
51
52 # Optionally specify the ref format used for tracking.
53 # The default is 'sha1' for the raw commit hash.
54 # If you specify 'git-describe', the commit hash will be prefixed
55 # with the closest tag.
56 ref-format: sha1
57
58 # Specify the commit ref, this must be specified in order to
59 # checkout sources and build, but can be automatically updated
60 # if the 'track' attribute was specified.
61 ref: d63cbb6fdc0bbdadc4a1b92284826a6d63a7ebcd
62
63 # Optionally specify whether submodules should be checked-out.
64 # This is done recursively, as with `git clone --recurse-submodules`.
65 # If not set, this will default to 'True'
66 checkout-submodules: True
67
68 # If your repository has submodules, explicitly specifying the
69 # url from which they are to be fetched allows you to easily
70 # rebuild the same sources from a different location. This is
71 # especially handy when used with project defined aliases which
72 # can be redefined at a later time, or overridden with mirrors.
73 #
74 # You may also explicitly specify whether to check out this
75 # submodule. If 'checkout' is set, it will control whether to
76 # checkout that submodule and recurse into it. It defaults to the
77 # value of 'checkout-submodules'.
78 submodules:
79 plugins/bar:
80 url: upstream:bar.git
81 checkout: True
82 plugins/bar/quux:
83 checkout: False
84 plugins/baz:
85 url: upstream:baz.git
86 checkout: False
87
88 # Modify the default version guessing pattern
89 #
90 # Since 2.5
91 #
92 version-guess-pattern: \'(\\d+)\\.(\\d+)(?:\\.(\\d+))?\'
93
94 # Override the version guessing with an explicit version
95 #
96 # Since 2.5
97 #
98 version: 5.9
99
100 # Enable tag tracking.
101 #
102 # This causes the `tags` metadata to be populated automatically
103 # as a result of tracking the git source.
104 #
105 # By default this is 'False'.
106 #
107 track-tags: True
108
109 # If the list of tags below is set, then a lightweight dummy
110 # git repository will be staged along with the content at
111 # build time.
112 #
113 # This is useful for a growing number of modules which use
114 # `git describe` at build time in order to determine the version
115 # which will be encoded into the built software.
116 #
117 # The 'tags' below is considered as a part of the git source
118 # reference and will be stored in the 'project.refs' file if
119 # that has been selected as your project's ref-storage.
120 #
121 # Migration notes:
122 #
123 # If you are upgrading from BuildStream 1.2, which used to
124 # stage the entire repository by default, you will notice that
125 # some modules which use `git describe` are broken, and will
126 # need to enable this feature in order to fix them.
127 #
128 # If you need to enable this feature without changing the
129 # the specific commit that you are building, then we recommend
130 # the following migration steps for any git sources where
131 # `git describe` is required:
132 #
133 # o Enable `track-tags` feature
134 # o Set the `track` parameter to the desired commit sha which
135 # the current `ref` points to
136 # o Run `bst source track` for these elements, this will result in
137 # populating the `tags` portion of the refs without changing
138 # the refs
139 # o Restore the `track` parameter to the branches which you have
140 # previously been tracking afterwards.
141 #
142 tags:
143 - tag: lightweight-example
144 commit: 04ad0dc656cb7cc6feb781aa13bdbf1d67d0af78
145 annotated: false
146 - tag: annotated-example
147 commit: 10abe77fe8d77385d86f225b503d9185f4ef7f3a
148 annotated: true
149
150 See `built-in functionality doumentation
151 <https://docs.buildstream.build/master/buildstream.source.html#core-source-builtins>`_ for
152 details on common configuration options for sources.
153
154
155 Configurable Warnings:
156 ~~~~~~~~~~~~~~~~~~~~~~
157 This plugin provides the following
158 `configurable warnings <https://docs.buildstream.build/master/format_project.html#configurable-warnings>`_:
159
160 - ``git:inconsistent-submodule`` - A submodule present in the git repository's .gitmodules was never
161 added with `git submodule add`.
162
163 - ``git:unlisted-submodule`` - A submodule is present in the git repository but was not specified in
164 the source configuration and was not disabled for checkout.
165
166 - ``git:invalid-submodule`` - A submodule is specified in the source configuration but does not exist
167 in the repository.
168
169 This plugin also utilises the following configurable
170 `core warnings <https://docs.buildstream.build/master/buildstream.types.html#buildstream.types.CoreWarnings>`_:
171
172 - `ref-not-in-track <https://docs.buildstream.build/master/buildstream.types.html#buildstream.types.CoreWarnings.REF_NOT_IN_TRACK>`_ -
173 The provided ref was not found in the provided track in the element's git repository.
174
175
176 Reporting `SourceInfo <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfo>`_
177 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178 The git source reports the URL of the git repository as the *url*.
179
180 Further, the git source reports the `SourceInfoMedium.GIT
181 <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfoMedium.GIT>`_
182 *medium* and the `SourceVersionType.COMMIT
183 <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceVersionType.COMMIT>`_
184 *version_type*, for which it reports the git commit sha as the *version*.
185
186 If the ref is found to be in ``git-describe`` format, an attempt to guess the version based on the
187 git tag portion of the ref will be made for the reporting of the *guess_version*. Control over how
188 the guess is made or overridden is controlled based on the ``version-guess-pattern`` and ``version``
189 configuration attributes described above.
190
191 In order to understand how the ``version-guess-pattern`` works, please refer to the documentation
192 for `utils.guess_version() <https://docs.buildstream.build/master/buildstream.source.html#buildstream.utils.guess_version>`_
193
194 In the case that a git describe string represents a commit that is beyond the tag portion
195 of the git describe reference (i.e. the version is not exact), then the number of commits
196 found beyond the tag will be reported in the ``commit-offset`` field of the *extra_data*.
197
198 .. attention::
199
200 SourceInfo is **not** reported for submodules.
201
202 This is due to the limitation that the git plugin requires to have the toplevel
203 module fetched first in order to have knowledge of the commits of the submodules.
204
205 While this does not provide *complete* information on the provenance of sources,
206 at least one can consider the module to be a comprehensive whole, and the versions
207 of submodules are deterministically controlled by the version of the main repository.
208 """
209
210 import os
211 import re
212 import shutil
213 from io import StringIO
214 from tempfile import TemporaryFile
215
216 from configparser import RawConfigParser
217
218 from buildstream import Source, SourceError, SourceFetcher
219 from buildstream import CoreWarnings, FastEnum
220 from buildstream import utils
221 from buildstream.utils import DirectoryExistsError
222
223 #
224 # Soft import of buildstream symbols only available in newer versions
225 #
226 # The BST_MIN_VERSION will provide a better user experience.
227 #
228 try:
229 from buildstream import SourceInfoMedium, SourceVersionType
230 except ImportError:
231 pass
232
233 GIT_MODULES = ".gitmodules"
234 EXACT_TAG_PATTERN = r"(?P<tag>.*)-0-g(?P<commit>.*)"
235
236 # Warnings
237 WARN_INCONSISTENT_SUBMODULE = "inconsistent-submodule"
238 WARN_UNLISTED_SUBMODULE = "unlisted-submodule"
239 WARN_INVALID_SUBMODULE = "invalid-submodule"
240
241
242 class _RefFormat(FastEnum):
243 SHA1 = "sha1"
244 GIT_DESCRIBE = "git-describe"
245
246
247 def _strip_tag(rev):
248 return rev.split("-g")[-1]
249
250
251 # This class represents a single Git repository. The Git source needs to account for
252 # submodules, but we don't want to cache them all under the umbrella of the
253 # superproject - so we use this class which caches them independently, according
254 # to their URL. Instances keep reference to their "parent" GitSource,
255 # and if applicable, where in the superproject they are found.
256 #
257 # Args:
258 # source (GitSource): The parent source
259 # path (str): The relative location of the submodule in the superproject;
260 # the empty string for the superproject itself
261 # url (str): Where to clone the repo from
262 # ref (str): Specified 'ref' from the source configuration
263 # primary (bool): Whether this is the primary URL for the source
264 # tags (list): Tag configuration; see GitSource._load_tags
265 #
266 class GitMirror(SourceFetcher):
267 def __init__(self, source, path, url, ref, *, primary=False, tags=None):
268
269 super().__init__()
270 self.source = source
271 self.path = path
272 self.url = url
273 self.ref = ref
274 self.tags = tags or []
275 self.primary = primary
276 self.mirror = os.path.join(source.get_mirror_directory(), utils.url_directory_name(url))
277
278 # _ensure_repo():
279 #
280 # Ensures that the Git repository exists at the mirror location and is configured
281 # to fetch from the given URL
282 #
283 def _ensure_repo(self):
284 if not os.path.exists(self.mirror):
285 with self.source.tempdir() as tmpdir:
286 self.source.call(
287 [self.source.host_git, "init", "--bare", tmpdir],
288 fail="Failed to initialise repository",
289 )
290
291 try:
292 utils.move_atomic(tmpdir, self.mirror)
293 except DirectoryExistsError:
294 # Another process was quicker to download this repository.
295 # Let's discard our own
296 self.source.status("{}: Discarding duplicate repository".format(self.source))
297 except OSError as e:
298 raise SourceError(
299 "{}: Failed to move created repository from '{}' to '{}': {}".format(
300 self.source, tmpdir, self.mirror, e
301 )
302 ) from e
303
304 def _fetch(self, url, fetch_all=False):
305 self._ensure_repo()
306
307 # Work out whether we can fetch a specific tag: are we given a ref which
308 # 1. is in git-describe format
309 # 2. refers to an exact tag (is "...-0-g...")
310 # 3. is available on the remote and tags the specified commit?
311 # And lastly: are we on a new-enough Git which allows cloning from our potentially shallow cache?
312 if fetch_all:
313 pass
314 # Fetching from a shallow-cloned repo was first supported in v1.9.0
315 elif not self.ref or self.source.host_git_version is not None and self.source.host_git_version < (1, 9, 0):
316 fetch_all = True
317 else:
318 m = re.match(EXACT_TAG_PATTERN, self.ref)
319 if m is None:
320 fetch_all = True
321 else:
322 tag = m.group("tag")
323 commit = m.group("commit")
324
325 if not self.remote_has_tag(url, tag, commit):
326 self.source.status(
327 "{}: {} is not advertised on {}. Fetching all Git refs".format(self.source, self.ref, url)
328 )
329 fetch_all = True
330 else:
331 exit_code = self.source.call(
332 [
333 self.source.host_git,
334 "fetch",
335 "--depth=1",
336 url,
337 "+refs/tags/{tag}:refs/tags/{tag}".format(tag=tag),
338 ],
339 cwd=self.mirror,
340 )
341 if exit_code != 0:
342 self.source.status(
343 "{}: Failed to fetch tag '{}' from {}. Fetching all Git refs".format(self.source, tag, url)
344 )
345 fetch_all = True
346
347 if fetch_all:
348 self.source.call(
349 [
350 self.source.host_git,
351 "fetch",
352 "--prune",
353 url,
354 "+refs/heads/*:refs/heads/*",
355 "+refs/tags/*:refs/tags/*",
356 ],
357 fail="Failed to fetch from remote git repository: {}".format(url),
358 fail_temporarily=True,
359 cwd=self.mirror,
360 )
361
362 def fetch(self, alias_override=None): # pylint: disable=arguments-differ
363 resolved_url = self.source.translate_url(self.url, alias_override=alias_override, primary=self.primary)
364
365 with self.source.timed_activity("Fetching from {}".format(resolved_url), silent_nested=True):
366 if not self.has_ref():
367 self._fetch(resolved_url)
368 self.assert_ref()
369
370 def has_ref(self):
371 if not self.ref:
372 return False
373
374 # If the mirror doesnt exist, we also dont have the ref
375 if not os.path.exists(self.mirror):
376 return False
377
378 # Check if the ref is really there
379 rc = self.source.call([self.source.host_git, "cat-file", "-t", self.ref], cwd=self.mirror)
380 return rc == 0
381
382 def assert_ref(self):
383 if not self.has_ref():
384 raise SourceError(
385 "{}: expected ref '{}' was not found in git repository: '{}'".format(self.source, self.ref, self.url)
386 )
387
388 # remote_has_tag():
389 #
390 # Args:
391 # url (str)
392 # tag (str)
393 # commit (str)
394 #
395 # Returns:
396 # (bool): Whether the remote at `url` has the tag `tag` attached to `commit`
397 #
398 def remote_has_tag(self, url, tag, commit):
399 _, ls_remote = self.source.check_output(
400 [self.source.host_git, "ls-remote", url],
401 cwd=self.mirror,
402 fail="Failed to list advertised remote refs from git repository {}".format(url),
403 )
404
405 line = "{commit}\trefs/tags/{tag}".format(commit=commit, tag=tag)
406 return line in ls_remote or line + "^{}" in ls_remote
407
408 # to_commit():
409 #
410 # Args:
411 # rev (str): A Git "commit-ish" rev
412 #
413 # Returns:
414 # (str): The full revision ID of the commit
415 #
416 def to_commit(self, rev):
417 _, output = self.source.check_output(
418 [self.source.host_git, "rev-list", "-n", "1", rev],
419 fail="Unable to find revision {}".format(rev),
420 cwd=self.mirror,
421 )
422
423 return output.strip()
424
425 # describe():
426 #
427 # Args:
428 # rev (str): A Git "commit-ish" rev
429 #
430 # Returns:
431 # (str): The full revision ID of the commit given by rev, prepended
432 # with tag information as given by git-describe (where available)
433 #
434 def describe(self, rev):
435 _, output = self.source.check_output(
436 [
437 self.source.host_git,
438 "describe",
439 "--tags",
440 "--abbrev=40",
441 "--long",
442 "--always",
443 rev,
444 ],
445 fail="Unable to find revision {}".format(rev),
446 cwd=self.mirror,
447 )
448
449 return output.strip()
450
451 # reachable_tags():
452 #
453 # Args:
454 # rev (str): A Git "commit-ish" rev
455 #
456 # Returns:
457 # (list): A list of tags in the ancestry of rev. Each entry is a triple of the form
458 # (tag name (str), commit ref (str), annotated (bool)) describing a tag,
459 # its tagged commit and whether it's annotated
460 #
461 def reachable_tags(self, rev):
462 tags = set()
463 for options in [
464 [],
465 ["--first-parent"],
466 ["--tags"],
467 ["--tags", "--first-parent"],
468 ]:
469 exit_code, output = self.source.check_output(
470 [
471 self.source.host_git,
472 "describe",
473 "--abbrev=0",
474 rev,
475 *options,
476 ],
477 cwd=self.mirror,
478 )
479 if exit_code == 0:
480 tag = output.strip()
481 _, commit_ref = self.source.check_output(
482 [self.source.host_git, "rev-parse", tag + "^{commit}"],
483 fail="Unable to resolve tag '{}'".format(tag),
484 cwd=self.mirror,
485 )
486 exit_code = self.source.call(
487 [self.source.host_git, "cat-file", "tag", tag],
488 cwd=self.mirror,
489 )
490 annotated = exit_code == 0
491
492 tags.add((tag, commit_ref.strip(), annotated))
493
494 return list(tags)
495
496 def stage(self, directory):
497 fullpath = os.path.join(directory, self.path)
498
499 # Using --shared here avoids copying the objects into the checkout, in any
500 # case we're just checking out a specific commit and then removing the .git/
501 # directory.
502 self.source.call(
503 [
504 self.source.host_git,
505 "clone",
506 "--no-checkout",
507 "--shared",
508 self.mirror,
509 fullpath,
510 ],
511 fail="Failed to create git mirror {} in directory: {}".format(self.mirror, fullpath),
512 fail_temporarily=True,
513 )
514
515 self.source.call(
516 [self.source.host_git, "checkout", "--force", self.ref],
517 fail="Failed to checkout git ref {}".format(self.ref),
518 cwd=fullpath,
519 )
520
521 # Remove .git dir
522 shutil.rmtree(os.path.join(fullpath, ".git"))
523
524 self._rebuild_git(fullpath)
525
526 def init_workspace(self, directory):
527 fullpath = os.path.join(directory, self.path)
528 url = self.source.translate_url(self.url)
529
530 self.source.call(
531 [
532 self.source.host_git,
533 "clone",
534 "--no-checkout",
535 self.mirror,
536 fullpath,
537 ],
538 fail="Failed to clone git mirror {} in directory: {}".format(self.mirror, fullpath),
539 fail_temporarily=True,
540 )
541
542 self.source.call(
543 [self.source.host_git, "remote", "set-url", "origin", url],
544 fail='Failed to add remote origin "{}"'.format(url),
545 cwd=fullpath,
546 )
547
548 self.source.call(
549 [self.source.host_git, "checkout", "--force", self.ref],
550 fail="Failed to checkout git ref {}".format(self.ref),
551 cwd=fullpath,
552 )
553
554 # get_submodule_mirrors():
555 #
556 # Returns:
557 # An iterator through new instances of this class, one of each submodule
558 # in the repo
559 #
560 def get_submodule_mirrors(self):
561 for path, url in self.submodule_list():
562 ref = self.submodule_ref(path)
563 if ref is not None:
564 mirror = self.__class__(self.source, os.path.join(self.path, path), url, ref)
565 yield mirror
566
567 # List the submodules (path/url tuples) present at the given ref of this repo
568 def submodule_list(self):
569 modules = "{}:{}".format(self.ref, GIT_MODULES)
570 exit_code, output = self.source.check_output([self.source.host_git, "show", modules], cwd=self.mirror)
571
572 # If git show reports error code 128 here, we take it to mean there is
573 # no .gitmodules file to display for the given revision.
574 if exit_code == 128:
575 return
576 elif exit_code != 0:
577 raise SourceError("{plugin}: Failed to show gitmodules at ref {ref}".format(plugin=self, ref=self.ref))
578
579 content = "\n".join([l.strip() for l in output.splitlines()])
580
581 io = StringIO(content)
582 parser = RawConfigParser()
583 parser.read_file(io)
584
585 for section in parser.sections():
586 # validate section name against the 'submodule "foo"' pattern
587 if re.match(r'submodule "(.*)"', section):
588 path = parser.get(section, "path")
589 url = parser.get(section, "url")
590
591 yield (path, url)
592
593 # Fetch the ref which this mirror requires its submodule to have,
594 # at the given ref of this mirror.
595 def submodule_ref(self, submodule, ref=None):
596 if not ref:
597 ref = self.ref
598
599 # list objects in the parent repo tree to find the commit
600 # object that corresponds to the submodule
601 _, output = self.source.check_output(
602 [self.source.host_git, "ls-tree", ref, submodule],
603 fail="ls-tree failed for commit {} and submodule: {}".format(ref, submodule),
604 cwd=self.mirror,
605 )
606
607 # read the commit hash from the output
608 fields = output.split()
609 if len(fields) >= 2 and fields[1] == "commit":
610 submodule_commit = output.split()[2]
611
612 # fail if the commit hash is invalid
613 if len(submodule_commit) != 40:
614 raise SourceError(
615 "{}: Error reading commit information for submodule '{}'".format(self.source, submodule)
616 )
617
618 return submodule_commit
619
620 else:
621 detail = (
622 "The submodule '{}' is defined either in the BuildStream source\n".format(submodule)
623 + "definition, or in a .gitmodules file. But the submodule was never added to the\n"
624 + "underlying git repository with `git submodule add`."
625 )
626
627 self.source.warn(
628 "{}: Ignoring inconsistent submodule '{}'".format(self.source, submodule),
629 detail=detail,
630 warning_token=WARN_INCONSISTENT_SUBMODULE,
631 )
632
633 return None
634
635 def _rebuild_git(self, fullpath):
636 if not self.tags:
637 return
638
639 with self.source.tempdir() as tmpdir:
640 included = set()
641 shallow = set()
642 for _, commit_ref, _ in self.tags:
643
644 if commit_ref == self.ref:
645 # rev-list does not work in case of same rev
646 shallow.add(self.ref)
647 else:
648 _, out = self.source.check_output(
649 [
650 self.source.host_git,
651 "rev-list",
652 "--ancestry-path",
653 "--boundary",
654 "{}..{}".format(commit_ref, self.ref),
655 ],
656 fail="Failed to get git history {}..{} in directory: {}".format(
657 commit_ref, self.ref, fullpath
658 ),
659 fail_temporarily=True,
660 cwd=self.mirror,
661 )
662 self.source.warn("refs {}..{}: {}".format(commit_ref, self.ref, out.splitlines()))
663 for line in out.splitlines():
664 rev = line.lstrip("-")
665 if line[0] == "-":
666 shallow.add(rev)
667 else:
668 included.add(rev)
669
670 shallow -= included
671 included |= shallow
672
673 self.source.call(
674 [self.source.host_git, "init"],
675 fail="Cannot initialize git repository: {}".format(fullpath),
676 cwd=fullpath,
677 )
678
679 for rev in included:
680 with TemporaryFile(dir=tmpdir) as commit_file:
681 self.source.call(
682 [self.source.host_git, "cat-file", "commit", rev],
683 stdout=commit_file,
684 fail="Failed to get commit {}".format(rev),
685 cwd=self.mirror,
686 )
687 commit_file.seek(0, 0)
688 self.source.call(
689 [
690 self.source.host_git,
691 "hash-object",
692 "-w",
693 "-t",
694 "commit",
695 "--stdin",
696 ],
697 stdin=commit_file,
698 fail="Failed to add commit object {}".format(rev),
699 cwd=fullpath,
700 )
701
702 with open(
703 os.path.join(fullpath, ".git", "shallow"),
704 "w",
705 encoding="utf-8",
706 ) as shallow_file:
707 for rev in shallow:
708 shallow_file.write("{}\n".format(rev))
709
710 for tag, commit_ref, annotated in self.tags:
711 if annotated:
712 with TemporaryFile(dir=tmpdir) as tag_file:
713 tag_data = "object {}\ntype commit\ntag {}\ntagger Unspecified Tagger <unspecified-tagger> 0 +0000\n".format(
714 commit_ref, tag
715 )
716 tag_file.write(tag_data.encode("ascii"))
717 tag_file.seek(0, 0)
718 _, tag_ref = self.source.check_output(
719 [
720 self.source.host_git,
721 "hash-object",
722 "-w",
723 "-t",
724 "tag",
725 "--stdin",
726 ],
727 stdin=tag_file,
728 fail="Failed to add tag object {}".format(tag),
729 cwd=fullpath,
730 )
731
732 self.source.call(
733 [self.source.host_git, "tag", tag, tag_ref.strip()],
734 fail="Failed to tag: {}".format(tag),
735 cwd=fullpath,
736 )
737 else:
738 self.source.call(
739 [self.source.host_git, "tag", tag, commit_ref],
740 fail="Failed to tag: {}".format(tag),
741 cwd=fullpath,
742 )
743
744 with open(os.path.join(fullpath, ".git", "HEAD"), "w", encoding="utf-8") as head:
745 self.source.call(
746 [self.source.host_git, "rev-parse", self.ref],
747 stdout=head,
748 fail="Failed to parse commit {}".format(self.ref),
749 cwd=self.mirror,
750 )
751
752
753 class GitSource(Source):
754 # pylint: disable=attribute-defined-outside-init
755
756 BST_MIN_VERSION = "2.5"
757
758 def configure(self, node):
759 ref = node.get_str("ref", None)
760
761 config_keys = [
762 "url",
763 "track",
764 "ref",
765 "submodules",
766 "checkout-submodules",
767 "ref-format",
768 "track-tags",
769 "tags",
770 "version",
771 "version-guess-pattern",
772 ]
773 node.validate_keys(config_keys + Source.COMMON_CONFIG_KEYS)
774
775 tags_node = node.get_sequence("tags", [])
776 for tag_node in tags_node:
777 tag_node.validate_keys(["tag", "commit", "annotated"])
778
779 tags = self._load_tags(node)
780 self.track_tags = node.get_bool("track-tags", default=False)
781
782 self.original_url = node.get_str("url")
783 self.mirror = GitMirror(self, "", self.original_url, ref, tags=tags, primary=True)
784 self.tracking = node.get_str("track", None)
785
786 self.ref_format = node.get_enum("ref-format", _RefFormat, _RefFormat.SHA1)
787
788 self.guess_pattern_string = node.get_str("version-guess-pattern", None)
789 self.guess_pattern = None
790 if self.guess_pattern_string is not None:
791 self.guess_pattern = re.compile(self.guess_pattern_string)
792
793 # Get the explicitly set guess_version for the toplevel git repo
794 self.version = node.get_str("version", None)
795
796 # At this point we now know if the source has a ref and/or a track.
797 # If it is missing both then we will be unable to track or build.
798 if self.mirror.ref is None and self.tracking is None:
799 raise SourceError(
800 "{}: Git sources require a ref and/or track".format(self),
801 reason="missing-track-and-ref",
802 )
803
804 self.checkout_submodules = node.get_bool("checkout-submodules", default=True)
805
806 # Parse a dict of submodule overrides, stored in the submodule_overrides
807 # and submodule_checkout_overrides dictionaries.
808 self.submodule_overrides = {}
809 self.submodule_checkout_overrides = {}
810 modules = node.get_mapping("submodules", {})
811 for path in modules.keys():
812 submodule = modules.get_mapping(path)
813 url = submodule.get_str("url", None)
814
815 # Make sure to mark all URLs that are specified in the configuration
816 if url:
817 self.mark_download_url(url, primary=False)
818
819 self.submodule_overrides[path] = url
820 if "checkout" in submodule:
821 checkout = submodule.get_bool("checkout")
822 self.submodule_checkout_overrides[path] = checkout
823
824 self.mark_download_url(self.original_url)
825
826 def preflight(self):
827 # Check if git is installed, get the binary at the same time
828 self.host_git = utils.get_host_tool("git")
829
830 rc, version_str = self.check_output([self.host_git, "--version"])
831 # e.g. on Git for Windows we get "git version 2.21.0.windows.1".
832 # e.g. on Mac via Homebrew we get "git version 2.19.0".
833 if rc == 0:
834 self.host_git_version = tuple(int(x) for x in version_str.split(" ")[2].split(".")[:3])
835 else:
836 self.host_git_version = None
837
838 def get_unique_key(self):
839 ref = self.mirror.ref
840 if ref is not None:
841 # Strip any (arbitary) tag information, leaving just the commit ID
842 ref = _strip_tag(ref)
843
844 # Here we want to encode the local name of the repository and
845 # the ref, if the user changes the alias to fetch the same sources
846 # from another location, it should not affect the cache key.
847 key = [self.original_url, ref]
848 if self.mirror.tags:
849 tags = {tag: (commit, annotated) for tag, commit, annotated in self.mirror.tags}
850 key.append({"tags": tags})
851
852 # Only modify the cache key with checkout_submodules if it's something
853 # other than the default behaviour.
854 if self.checkout_submodules is False:
855 key.append({"checkout_submodules": self.checkout_submodules})
856
857 # We want the cache key to change if the source was
858 # configured differently, and submodules count.
859 if self.submodule_overrides:
860 key.append(self.submodule_overrides)
861
862 if self.submodule_checkout_overrides:
863 key.append({"submodule_checkout_overrides": self.submodule_checkout_overrides})
864
865 # Backwards compatible method of supporting configuration
866 # attributes which affect SourceInfo generation.
867 if self.version is not None:
868 key.append(self.version)
869 elif self.guess_pattern_string is not None:
870 key.append(self.guess_pattern_string)
871
872 return key
873
874 def is_resolved(self):
875 return self.mirror.ref is not None
876
877 def is_cached(self):
878 return self._have_all_refs()
879
880 def load_ref(self, node):
881 self.mirror.ref = node.get_str("ref", None)
882 self.mirror.tags = self._load_tags(node)
883
884 def get_ref(self):
885 if self.mirror.ref is None:
886 return None
887 return self.mirror.ref, self.mirror.tags
888
889 def set_ref(self, ref, node):
890 if not ref:
891 self.mirror.ref = None
892 if "ref" in node:
893 del node["ref"]
894 self.mirror.tags = []
895 if "tags" in node:
896 del node["tags"]
897 else:
898 actual_ref, tags = ref
899 node["ref"] = self.mirror.ref = actual_ref
900 self.mirror.tags = tags
901 if tags:
902 node["tags"] = [
903 {
904 "tag": tag,
905 "commit": commit_ref,
906 "annotated": annotated,
907 }
908 for tag, commit_ref, annotated in tags
909 ]
910 else:
911 if "tags" in node:
912 del node["tags"]
913
914 def track(self): # pylint: disable=arguments-differ
915
916 # If self.tracking is not specified it's not an error, just silently return
917 if not self.tracking:
918 # Is there a better way to check if a ref is given.
919 if self.mirror.ref is None:
920 detail = "Without a tracking branch ref can not be updated. Please " + "provide a ref or a track."
921 raise SourceError(
922 "{}: No track or ref".format(self),
923 detail=detail,
924 reason="track-attempt-no-track",
925 )
926 return None
927
928 # Resolve the URL for the message
929 resolved_url = self.translate_url(self.mirror.url)
930 with self.timed_activity(
931 "Tracking {} from {}".format(self.tracking, resolved_url),
932 silent_nested=True,
933 ):
934 self.mirror._fetch(resolved_url, fetch_all=True)
935
936 ref = self.mirror.to_commit(self.tracking)
937 tags = self.mirror.reachable_tags(ref) if self.track_tags else []
938
939 if self.ref_format == _RefFormat.GIT_DESCRIBE:
940 ref = self.mirror.describe(ref)
941
942 return ref, tags
943
944 def init_workspace(self, directory):
945 with self.timed_activity('Setting up workspace "{}"'.format(directory), silent_nested=True):
946 self.mirror.init_workspace(directory)
947 for mirror in self._recurse_submodules(configure=True):
948 mirror.init_workspace(directory)
949
950 def stage(self, directory):
951 # Stage the main repo in the specified directory
952 #
953 with self.timed_activity("Staging {}".format(self.mirror.url), silent_nested=True):
954 self.mirror.stage(directory)
955 for mirror in self._recurse_submodules(configure=True):
956 mirror.stage(directory)
957
958 def get_source_fetchers(self):
959 self.mirror.mark_download_url(self.mirror.url)
960 yield self.mirror
961 # _recurse_submodules only iterates those which are known at the current
962 # cached state - but fetch is called on each result as we go, so this will
963 # yield all configured submodules
964 for submodule in self._recurse_submodules(configure=True):
965 submodule.mark_download_url(submodule.url)
966 yield submodule
967
968 def validate_cache(self):
969 discovered_submodules = {}
970 unlisted_submodules = []
971 invalid_submodules = []
972
973 for submodule in self._recurse_submodules(configure=False):
974 discovered_submodules[submodule.path] = submodule.url
975 if self._ignoring_submodule(submodule.path):
976 continue
977
978 if submodule.path not in self.submodule_overrides:
979 unlisted_submodules.append((submodule.path, submodule.url))
980
981 # Warn about submodules which are explicitly configured but do not exist
982 for path, url in self.submodule_overrides.items():
983 if path not in discovered_submodules:
984 invalid_submodules.append((path, url))
985
986 if invalid_submodules:
987 detail = []
988 for path, url in invalid_submodules:
989 detail.append(" Submodule URL '{}' at path '{}'".format(url, path))
990
991 self.warn(
992 "{}: Invalid submodules specified".format(self),
993 warning_token=WARN_INVALID_SUBMODULE,
994 detail="The following submodules are specified in the source "
995 "description but do not exist according to the repository\n\n" + "\n".join(detail),
996 )
997
998 # Warn about submodules which exist but have not been explicitly configured
999 if unlisted_submodules:
1000 detail = []
1001 for path, url in unlisted_submodules:
1002 detail.append(" Submodule URL '{}' at path '{}'".format(url, path))
1003
1004 self.warn(
1005 "{}: Unlisted submodules exist".format(self),
1006 warning_token=WARN_UNLISTED_SUBMODULE,
1007 detail="The following submodules exist but are not specified "
1008 + "in the source description\n\n"
1009 + "\n".join(detail),
1010 )
1011
1012 # Assert that the ref exists in the track tag/branch, if track has been specified.
1013 # Also don't do this check if an exact tag ref is given, as we probably didn't fetch
1014 # any branch refs
1015 ref_in_track = False
1016 if not re.match(EXACT_TAG_PATTERN, self.mirror.ref) and self.tracking:
1017 _, branch = self.check_output(
1018 [
1019 self.host_git,
1020 "branch",
1021 "--list",
1022 self.tracking,
1023 "--contains",
1024 self.mirror.ref,
1025 ],
1026 cwd=self.mirror.mirror,
1027 )
1028 if branch:
1029 ref_in_track = True
1030 else:
1031 _, tag = self.check_output(
1032 [
1033 self.host_git,
1034 "tag",
1035 "--list",
1036 self.tracking,
1037 "--contains",
1038 self.mirror.ref,
1039 ],
1040 cwd=self.mirror.mirror,
1041 )
1042 if tag:
1043 ref_in_track = True
1044
1045 if not ref_in_track:
1046 detail = (
1047 "The ref provided for the element does not exist locally "
1048 + "in the provided track branch / tag '{}'.\n".format(self.tracking)
1049 + "You may wish to track the element to update the ref from '{}' ".format(self.tracking)
1050 + "with `bst source track`,\n"
1051 + "or examine the upstream at '{}' for the specific ref.".format(self.mirror.url)
1052 )
1053
1054 self.warn(
1055 "{}: expected ref '{}' was not found in given track '{}' for staged repository: '{}'\n".format(
1056 self, self.mirror.ref, self.tracking, self.mirror.url
1057 ),
1058 detail=detail,
1059 warning_token=CoreWarnings.REF_NOT_IN_TRACK,
1060 )
1061
1062 # _guess_version()
1063 #
1064 # Guess the version, in the case the ref is recorded in git-describe format
1065 #
1066 # Returns: a three-tuple composed of the following three values:
1067 # - the version (a git sha)
1068 # - the version_guess (as guessed from the tag portion of a git describe string)
1069 # - the number of commits beyond the tag (indicating that the guessed version is in this case inexact)
1070 #
1071 # All returns are either None or strings, only the "sha" is guaranteed to be discovered.
1072 #
1073 def _guess_version(self):
1074 version_guess = self.version
1075 commits = None
1076 commit_sha = None
1077
1078 string = self.mirror.ref
1079
1080 main_split = string.rsplit("-g", 1)
1081 if len(main_split) < 2:
1082 # Didn't find the `-g`, assume its a raw git sha as input
1083 commit_sha = string
1084 else:
1085 # Split out the commits and the tag portion (which may also contain '-')
1086 commit_sha = main_split[1]
1087 sub_split = main_split[0].rsplit("-", 1)
1088
1089 commits = sub_split[1]
1090 if commits == "0":
1091 commits = None
1092
1093 # Run the guess logic on the tag portion of the git describe string
1094 if version_guess is None:
1095 version_guess = utils.guess_version(sub_split[0], pattern=self.guess_pattern)
1096
1097 return (commit_sha, version_guess, commits)
1098
1099 def collect_source_info(self):
1100 extra_data = None
1101 commit_sha, version_guess, commits = self._guess_version()
1102 if commits:
1103 extra_data = {"commit-offset": commits}
1104
1105 return [
1106 self.create_source_info(
1107 self.mirror.url,
1108 SourceInfoMedium.GIT,
1109 SourceVersionType.COMMIT,
1110 commit_sha,
1111 version_guess=version_guess,
1112 extra_data=extra_data,
1113 )
1114 ]
1115
1116 ###########################################################
1117 # Local Functions #
1118 ###########################################################
1119
1120 def _have_all_refs(self):
1121 return self.mirror.has_ref() and all(
1122 submodule.has_ref() for submodule in self._recurse_submodules(configure=True)
1123 )
1124
1125 # _configure_submodules():
1126 #
1127 # Args:
1128 # submodules: An iterator of GitMirror (or similar) objects for submodules
1129 #
1130 # Returns:
1131 # An iterator through `submodules` but filtered of any ignored submodules
1132 # and modified to use any custom URLs configured in the source
1133 #
1134 def _configure_submodules(self, submodules):
1135 for submodule in submodules:
1136 if self._ignoring_submodule(submodule.path):
1137 continue
1138 # Allow configuration to override the upstream location of the submodules.
1139 submodule.url = self.submodule_overrides.get(submodule.path, submodule.url)
1140
1141 yield submodule
1142
1143 # _recurse_submodules():
1144 #
1145 # Recursively iterates through GitMirrors for submodules of the main repo. Only
1146 # submodules that are cached are recursed into - but this is decided at
1147 # iteration time, so you can fetch in a for loop over this function to fetch
1148 # all submodules.
1149 #
1150 # Args:
1151 # configure (bool): Whether to apply the 'submodule' config while recursing
1152 # (URL changing and 'checkout' overrides)
1153 #
1154 def _recurse_submodules(self, configure):
1155 def recurse(mirror):
1156 submodules = mirror.get_submodule_mirrors()
1157 if configure:
1158 submodules = self._configure_submodules(submodules)
1159
1160 for submodule in submodules:
1161 yield submodule
1162 if submodule.has_ref():
1163 yield from recurse(submodule)
1164
1165 yield from recurse(self.mirror)
1166
1167 def _load_tags(self, node):
1168 tags = []
1169 tags_node = node.get_sequence("tags", [])
1170 for tag_node in tags_node:
1171 tag = tag_node.get_str("tag")
1172 commit_ref = tag_node.get_str("commit")
1173 annotated = tag_node.get_bool("annotated")
1174 tags.append((tag, commit_ref, annotated))
1175 return tags
1176
1177 # _ignoring_submodule():
1178 #
1179 # Args:
1180 # path (str): The path of a submodule in the superproject
1181 #
1182 # Returns:
1183 # (bool): Whether to not clone/checkout this submodule
1184 #
1185 def _ignoring_submodule(self, path):
1186 return not self.submodule_checkout_overrides.get(path, self.checkout_submodules)
1187
1188
1189 # Plugin entry point
1190 def setup():
1191 return GitSource