gitsm.py 9.2 KB

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