gitsm.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. """
  2. BitBake 'Fetch' git submodules implementation
  3. Inherits from and extends the Git fetcher to retrieve submodules of a git repository
  4. after cloning.
  5. SRC_URI = "gitsm://<see Git fetcher for syntax>"
  6. See the Git fetcher, git://, for usage documentation.
  7. NOTE: Switching a SRC_URI from "git://" to "gitsm://" requires a clean of your recipe.
  8. """
  9. # Copyright (C) 2013 Richard Purdie
  10. #
  11. # SPDX-License-Identifier: GPL-2.0-only
  12. #
  13. import os
  14. import bb
  15. import copy
  16. import shutil
  17. import tempfile
  18. from bb.fetch2.git import Git
  19. from bb.fetch2 import runfetchcmd
  20. from bb.fetch2 import logger
  21. from bb.fetch2 import Fetch
  22. class GitSM(Git):
  23. def supports(self, ud, d):
  24. """
  25. Check to see if a given url can be fetched with git.
  26. """
  27. return ud.type in ['gitsm']
  28. def process_submodules(self, ud, workdir, function, d):
  29. """
  30. Iterate over all of the submodules in this repository and execute
  31. the 'function' for each of them.
  32. """
  33. submodules = []
  34. paths = {}
  35. revision = {}
  36. uris = {}
  37. subrevision = {}
  38. def parse_gitmodules(gitmodules):
  39. modules = {}
  40. module = ""
  41. for line in gitmodules.splitlines():
  42. if line.startswith('[submodule'):
  43. module = line.split('"')[1]
  44. modules[module] = {}
  45. elif module and line.strip().startswith('path'):
  46. path = line.split('=')[1].strip()
  47. modules[module]['path'] = path
  48. elif module and line.strip().startswith('url'):
  49. url = line.split('=')[1].strip()
  50. modules[module]['url'] = url
  51. return modules
  52. # Collect the defined submodules, and their attributes
  53. for name in ud.names:
  54. try:
  55. gitmodules = runfetchcmd("%s show %s:.gitmodules" % (ud.basecmd, ud.revisions[name]), d, quiet=True, workdir=workdir)
  56. except:
  57. # No submodules to update
  58. continue
  59. for m, md in parse_gitmodules(gitmodules).items():
  60. try:
  61. module_hash = runfetchcmd("%s ls-tree -z -d %s %s" % (ud.basecmd, ud.revisions[name], md['path']), d, quiet=True, workdir=workdir)
  62. except:
  63. # If the command fails, we don't have a valid file to check. If it doesn't
  64. # fail -- it still might be a failure, see next check...
  65. module_hash = ""
  66. if not module_hash:
  67. logger.debug(1, "submodule %s is defined, but is not initialized in the repository. Skipping", m)
  68. continue
  69. submodules.append(m)
  70. paths[m] = md['path']
  71. revision[m] = ud.revisions[name]
  72. uris[m] = md['url']
  73. subrevision[m] = module_hash.split()[2]
  74. # Convert relative to absolute uri based on parent uri
  75. if uris[m].startswith('..'):
  76. newud = copy.copy(ud)
  77. newud.path = os.path.realpath(os.path.join(newud.path, uris[m]))
  78. uris[m] = Git._get_repo_url(self, newud)
  79. for module in submodules:
  80. # Translate the module url into a SRC_URI
  81. if "://" in uris[module]:
  82. # Properly formated URL already
  83. proto = uris[module].split(':', 1)[0]
  84. url = uris[module].replace('%s:' % proto, 'gitsm:', 1)
  85. else:
  86. if ":" in uris[module]:
  87. # Most likely an SSH style reference
  88. proto = "ssh"
  89. if ":/" in uris[module]:
  90. # Absolute reference, easy to convert..
  91. url = "gitsm://" + uris[module].replace(':/', '/', 1)
  92. else:
  93. # Relative reference, no way to know if this is right!
  94. logger.warning("Submodule included by %s refers to relative ssh reference %s. References may fail if not absolute." % (ud.url, uris[module]))
  95. url = "gitsm://" + uris[module].replace(':', '/', 1)
  96. else:
  97. # This has to be a file reference
  98. proto = "file"
  99. url = "gitsm://" + uris[module]
  100. url += ';protocol=%s' % proto
  101. url += ";name=%s" % module
  102. url += ";subpath=%s" % module
  103. ld = d.createCopy()
  104. # Not necessary to set SRC_URI, since we're passing the URI to
  105. # Fetch.
  106. #ld.setVar('SRC_URI', url)
  107. ld.setVar('SRCREV_%s' % module, subrevision[module])
  108. # Workaround for issues with SRCPV/SRCREV_FORMAT errors
  109. # error refer to 'multiple' repositories. Only the repository
  110. # in the original SRC_URI actually matters...
  111. ld.setVar('SRCPV', d.getVar('SRCPV'))
  112. ld.setVar('SRCREV_FORMAT', module)
  113. function(ud, url, module, paths[module], workdir, ld)
  114. return submodules != []
  115. def need_update(self, ud, d):
  116. if Git.need_update(self, ud, d):
  117. return True
  118. try:
  119. # Check for the nugget dropped by the download operation
  120. known_srcrevs = runfetchcmd("%s config --get-all bitbake.srcrev" % \
  121. (ud.basecmd), d, workdir=ud.clonedir)
  122. if ud.revisions[ud.names[0]] not in known_srcrevs.split():
  123. return True
  124. except bb.fetch2.FetchError:
  125. # No srcrev nuggets, so this is new and needs to be updated
  126. return True
  127. return False
  128. def download(self, ud, d):
  129. def download_submodule(ud, url, module, modpath, workdir, d):
  130. url += ";bareclone=1;nobranch=1"
  131. # Is the following still needed?
  132. #url += ";nocheckout=1"
  133. try:
  134. newfetch = Fetch([url], d, cache=False)
  135. newfetch.download()
  136. # Drop a nugget to add each of the srcrevs we've fetched (used by need_update)
  137. runfetchcmd("%s config --add bitbake.srcrev %s" % \
  138. (ud.basecmd, ud.revisions[ud.names[0]]), d, workdir=workdir)
  139. except Exception as e:
  140. logger.error('gitsm: submodule download failed: %s %s' % (type(e).__name__, str(e)))
  141. raise
  142. Git.download(self, ud, d)
  143. # If we're using a shallow mirror tarball it needs to be unpacked
  144. # temporarily so that we can examine the .gitmodules file
  145. if ud.shallow and os.path.exists(ud.fullshallow) and self.need_update(ud, d):
  146. tmpdir = tempfile.mkdtemp(dir=d.getVar("DL_DIR"))
  147. runfetchcmd("tar -xzf %s" % ud.fullshallow, d, workdir=tmpdir)
  148. self.process_submodules(ud, tmpdir, download_submodule, d)
  149. shutil.rmtree(tmpdir)
  150. else:
  151. self.process_submodules(ud, ud.clonedir, download_submodule, d)
  152. def unpack(self, ud, destdir, d):
  153. def unpack_submodules(ud, url, module, modpath, workdir, d):
  154. url += ";bareclone=1;nobranch=1"
  155. # Figure out where we clone over the bare submodules...
  156. if ud.bareclone:
  157. repo_conf = ud.destdir
  158. else:
  159. repo_conf = os.path.join(ud.destdir, '.git')
  160. try:
  161. newfetch = Fetch([url], d, cache=False)
  162. newfetch.unpack(root=os.path.dirname(os.path.join(repo_conf, 'modules', module)))
  163. except Exception as e:
  164. logger.error('gitsm: submodule unpack failed: %s %s' % (type(e).__name__, str(e)))
  165. raise
  166. local_path = newfetch.localpath(url)
  167. # Correct the submodule references to the local download version...
  168. runfetchcmd("%(basecmd)s config submodule.%(module)s.url %(url)s" % {'basecmd': ud.basecmd, 'module': module, 'url' : local_path}, d, workdir=ud.destdir)
  169. if ud.shallow:
  170. runfetchcmd("%(basecmd)s config submodule.%(module)s.shallow true" % {'basecmd': ud.basecmd, 'module': module}, d, workdir=ud.destdir)
  171. # Ensure the submodule repository is NOT set to bare, since we're checking it out...
  172. try:
  173. runfetchcmd("%s config core.bare false" % (ud.basecmd), d, quiet=True, workdir=os.path.join(repo_conf, 'modules', module))
  174. except:
  175. logger.error("Unable to set git config core.bare to false for %s" % os.path.join(repo_conf, 'modules', module))
  176. raise
  177. Git.unpack(self, ud, destdir, d)
  178. ret = self.process_submodules(ud, ud.destdir, unpack_submodules, d)
  179. if not ud.bareclone and ret:
  180. # All submodules should already be downloaded and configured in the tree. This simply sets
  181. # up the configuration and checks out the files. The main project config should remain
  182. # unmodified, and no download from the internet should occur.
  183. runfetchcmd("%s submodule update --recursive --no-fetch" % (ud.basecmd), d, quiet=True, workdir=ud.destdir)