git.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 implementation
  5. git fetcher support the SRC_URI with format of:
  6. SRC_URI = "git://some.host/somepath;OptionA=xxx;OptionB=xxx;..."
  7. Supported SRC_URI options are:
  8. - branch
  9. The git branch to retrieve from. The default is "master"
  10. This option also supports multiple branch fetching, with branches
  11. separated by commas. In multiple branches case, the name option
  12. must have the same number of names to match the branches, which is
  13. used to specify the SRC_REV for the branch
  14. e.g:
  15. SRC_URI="git://some.host/somepath;branch=branchX,branchY;name=nameX,nameY"
  16. SRCREV_nameX = "xxxxxxxxxxxxxxxxxxxx"
  17. SRCREV_nameY = "YYYYYYYYYYYYYYYYYYYY"
  18. - tag
  19. The git tag to retrieve. The default is "master"
  20. - protocol
  21. The method to use to access the repository. Common options are "git",
  22. "http", "https", "file", "ssh" and "rsync". The default is "git".
  23. - rebaseable
  24. rebaseable indicates that the upstream git repo may rebase in the future,
  25. and current revision may disappear from upstream repo. This option will
  26. remind fetcher to preserve local cache carefully for future use.
  27. The default value is "0", set rebaseable=1 for rebaseable git repo.
  28. - nocheckout
  29. Don't checkout source code when unpacking. set this option for the recipe
  30. who has its own routine to checkout code.
  31. The default is "0", set nocheckout=1 if needed.
  32. - bareclone
  33. Create a bare clone of the source code and don't checkout the source code
  34. when unpacking. Set this option for the recipe who has its own routine to
  35. checkout code and tracking branch requirements.
  36. The default is "0", set bareclone=1 if needed.
  37. - nobranch
  38. Don't check the SHA validation for branch. set this option for the recipe
  39. referring to commit which is valid in tag instead of branch.
  40. The default is "0", set nobranch=1 if needed.
  41. """
  42. #Copyright (C) 2005 Richard Purdie
  43. #
  44. # This program is free software; you can redistribute it and/or modify
  45. # it under the terms of the GNU General Public License version 2 as
  46. # published by the Free Software Foundation.
  47. #
  48. # This program is distributed in the hope that it will be useful,
  49. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  50. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  51. # GNU General Public License for more details.
  52. #
  53. # You should have received a copy of the GNU General Public License along
  54. # with this program; if not, write to the Free Software Foundation, Inc.,
  55. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  56. import errno
  57. import os
  58. import re
  59. import bb
  60. import errno
  61. from bb import data
  62. from bb.fetch2 import FetchMethod
  63. from bb.fetch2 import runfetchcmd
  64. from bb.fetch2 import logger
  65. class Git(FetchMethod):
  66. """Class to fetch a module or modules from git repositories"""
  67. def init(self, d):
  68. pass
  69. def supports(self, ud, d):
  70. """
  71. Check to see if a given url can be fetched with git.
  72. """
  73. return ud.type in ['git']
  74. def supports_checksum(self, urldata):
  75. return False
  76. def urldata_init(self, ud, d):
  77. """
  78. init git specific variable within url data
  79. so that the git method like latest_revision() can work
  80. """
  81. if 'protocol' in ud.parm:
  82. ud.proto = ud.parm['protocol']
  83. elif not ud.host:
  84. ud.proto = 'file'
  85. else:
  86. ud.proto = "git"
  87. if not ud.proto in ('git', 'file', 'ssh', 'http', 'https', 'rsync'):
  88. raise bb.fetch2.ParameterError("Invalid protocol type", ud.url)
  89. ud.nocheckout = ud.parm.get("nocheckout","0") == "1"
  90. ud.rebaseable = ud.parm.get("rebaseable","0") == "1"
  91. ud.nobranch = ud.parm.get("nobranch","0") == "1"
  92. # bareclone implies nocheckout
  93. ud.bareclone = ud.parm.get("bareclone","0") == "1"
  94. if ud.bareclone:
  95. ud.nocheckout = 1
  96. ud.unresolvedrev = {}
  97. branches = ud.parm.get("branch", "master").split(',')
  98. if len(branches) != len(ud.names):
  99. raise bb.fetch2.ParameterError("The number of name and branch parameters is not balanced", ud.url)
  100. ud.branches = {}
  101. for name in ud.names:
  102. branch = branches[ud.names.index(name)]
  103. ud.branches[name] = branch
  104. ud.unresolvedrev[name] = branch
  105. ud.basecmd = data.getVar("FETCHCMD_git", d, True) or "git -c core.fsyncobjectfiles=0"
  106. ud.write_tarballs = ((data.getVar("BB_GENERATE_MIRROR_TARBALLS", d, True) or "0") != "0") or ud.rebaseable
  107. ud.setup_revisons(d)
  108. for name in ud.names:
  109. # Ensure anything that doesn't look like a sha256 checksum/revision is translated into one
  110. if not ud.revisions[name] or len(ud.revisions[name]) != 40 or (False in [c in "abcdef0123456789" for c in ud.revisions[name]]):
  111. if ud.revisions[name]:
  112. ud.unresolvedrev[name] = ud.revisions[name]
  113. ud.revisions[name] = self.latest_revision(ud, d, name)
  114. gitsrcname = '%s%s' % (ud.host.replace(':', '.'), ud.path.replace('/', '.').replace('*', '.'))
  115. if gitsrcname.startswith('.'):
  116. gitsrcname = gitsrcname[1:]
  117. # for rebaseable git repo, it is necessary to keep mirror tar ball
  118. # per revision, so that even the revision disappears from the
  119. # upstream repo in the future, the mirror will remain intact and still
  120. # contains the revision
  121. if ud.rebaseable:
  122. for name in ud.names:
  123. gitsrcname = gitsrcname + '_' + ud.revisions[name]
  124. ud.mirrortarball = 'git2_%s.tar.gz' % (gitsrcname)
  125. ud.fullmirror = os.path.join(d.getVar("DL_DIR", True), ud.mirrortarball)
  126. gitdir = d.getVar("GITDIR", True) or (d.getVar("DL_DIR", True) + "/git2/")
  127. ud.clonedir = os.path.join(gitdir, gitsrcname)
  128. ud.localfile = ud.clonedir
  129. def localpath(self, ud, d):
  130. return ud.clonedir
  131. def need_update(self, ud, d):
  132. if not os.path.exists(ud.clonedir):
  133. return True
  134. os.chdir(ud.clonedir)
  135. for name in ud.names:
  136. if not self._contains_ref(ud, d, name):
  137. return True
  138. if ud.write_tarballs and not os.path.exists(ud.fullmirror):
  139. return True
  140. return False
  141. def try_premirror(self, ud, d):
  142. # If we don't do this, updating an existing checkout with only premirrors
  143. # is not possible
  144. if d.getVar("BB_FETCH_PREMIRRORONLY", True) is not None:
  145. return True
  146. if os.path.exists(ud.clonedir):
  147. return False
  148. return True
  149. def download(self, ud, d):
  150. """Fetch url"""
  151. # If the checkout doesn't exist and the mirror tarball does, extract it
  152. if not os.path.exists(ud.clonedir) and os.path.exists(ud.fullmirror):
  153. bb.utils.mkdirhier(ud.clonedir)
  154. os.chdir(ud.clonedir)
  155. runfetchcmd("tar -xzf %s" % (ud.fullmirror), d)
  156. repourl = self._get_repo_url(ud)
  157. # If the repo still doesn't exist, fallback to cloning it
  158. if not os.path.exists(ud.clonedir):
  159. # We do this since git will use a "-l" option automatically for local urls where possible
  160. if repourl.startswith("file://"):
  161. repourl = repourl[7:]
  162. clone_cmd = "%s clone --bare --mirror %s %s" % (ud.basecmd, repourl, ud.clonedir)
  163. if ud.proto.lower() != 'file':
  164. bb.fetch2.check_network_access(d, clone_cmd)
  165. runfetchcmd(clone_cmd, d)
  166. os.chdir(ud.clonedir)
  167. # Update the checkout if needed
  168. needupdate = False
  169. for name in ud.names:
  170. if not self._contains_ref(ud, d, name):
  171. needupdate = True
  172. if needupdate:
  173. try:
  174. runfetchcmd("%s remote rm origin" % ud.basecmd, d)
  175. except bb.fetch2.FetchError:
  176. logger.debug(1, "No Origin")
  177. runfetchcmd("%s remote add --mirror=fetch origin %s" % (ud.basecmd, repourl), d)
  178. fetch_cmd = "%s fetch -f --prune %s refs/*:refs/*" % (ud.basecmd, repourl)
  179. if ud.proto.lower() != 'file':
  180. bb.fetch2.check_network_access(d, fetch_cmd, ud.url)
  181. runfetchcmd(fetch_cmd, d)
  182. runfetchcmd("%s prune-packed" % ud.basecmd, d)
  183. runfetchcmd("%s pack-redundant --all | xargs -r rm" % ud.basecmd, d)
  184. try:
  185. os.unlink(ud.fullmirror)
  186. except OSError as exc:
  187. if exc.errno != errno.ENOENT:
  188. raise
  189. os.chdir(ud.clonedir)
  190. for name in ud.names:
  191. if not self._contains_ref(ud, d, name):
  192. raise bb.fetch2.FetchError("Unable to find revision %s in branch %s even from upstream" % (ud.revisions[name], ud.branches[name]))
  193. def build_mirror_data(self, ud, d):
  194. # Generate a mirror tarball if needed
  195. if ud.write_tarballs and not os.path.exists(ud.fullmirror):
  196. # it's possible that this symlink points to read-only filesystem with PREMIRROR
  197. if os.path.islink(ud.fullmirror):
  198. os.unlink(ud.fullmirror)
  199. os.chdir(ud.clonedir)
  200. logger.info("Creating tarball of git repository")
  201. runfetchcmd("tar -czf %s %s" % (ud.fullmirror, os.path.join(".") ), d)
  202. runfetchcmd("touch %s.done" % (ud.fullmirror), d)
  203. def unpack(self, ud, destdir, d):
  204. """ unpack the downloaded src to destdir"""
  205. subdir = ud.parm.get("subpath", "")
  206. if subdir != "":
  207. readpathspec = ":%s" % (subdir)
  208. def_destsuffix = "%s/" % os.path.basename(subdir.rstrip('/'))
  209. else:
  210. readpathspec = ""
  211. def_destsuffix = "git/"
  212. destsuffix = ud.parm.get("destsuffix", def_destsuffix)
  213. destdir = ud.destdir = os.path.join(destdir, destsuffix)
  214. if os.path.exists(destdir):
  215. bb.utils.prunedir(destdir)
  216. cloneflags = "-s -n"
  217. if ud.bareclone:
  218. cloneflags += " --mirror"
  219. # Versions of git prior to 1.7.9.2 have issues where foo.git and foo get confused
  220. # and you end up with some horrible union of the two when you attempt to clone it
  221. # The least invasive workaround seems to be a symlink to the real directory to
  222. # fool git into ignoring any .git version that may also be present.
  223. #
  224. # The issue is fixed in more recent versions of git so we can drop this hack in future
  225. # when that version becomes common enough.
  226. clonedir = ud.clonedir
  227. if not ud.path.endswith(".git"):
  228. indirectiondir = destdir[:-1] + ".indirectionsymlink"
  229. if os.path.exists(indirectiondir):
  230. os.remove(indirectiondir)
  231. bb.utils.mkdirhier(os.path.dirname(indirectiondir))
  232. os.symlink(ud.clonedir, indirectiondir)
  233. clonedir = indirectiondir
  234. runfetchcmd("%s clone %s %s/ %s" % (ud.basecmd, cloneflags, clonedir, destdir), d)
  235. os.chdir(destdir)
  236. repourl = self._get_repo_url(ud)
  237. runfetchcmd("%s remote set-url origin %s" % (ud.basecmd, repourl), d)
  238. if not ud.nocheckout:
  239. if subdir != "":
  240. runfetchcmd("%s read-tree %s%s" % (ud.basecmd, ud.revisions[ud.names[0]], readpathspec), d)
  241. runfetchcmd("%s checkout-index -q -f -a" % ud.basecmd, d)
  242. elif not ud.nobranch:
  243. branchname = ud.branches[ud.names[0]]
  244. runfetchcmd("%s checkout -B %s %s" % (ud.basecmd, branchname, \
  245. ud.revisions[ud.names[0]]), d)
  246. runfetchcmd("%s branch --set-upstream %s origin/%s" % (ud.basecmd, branchname, \
  247. branchname), d)
  248. else:
  249. runfetchcmd("%s checkout %s" % (ud.basecmd, ud.revisions[ud.names[0]]), d)
  250. return True
  251. def clean(self, ud, d):
  252. """ clean the git directory """
  253. bb.utils.remove(ud.localpath, True)
  254. bb.utils.remove(ud.fullmirror)
  255. bb.utils.remove(ud.fullmirror + ".done")
  256. def supports_srcrev(self):
  257. return True
  258. def _contains_ref(self, ud, d, name):
  259. cmd = ""
  260. if ud.nobranch:
  261. cmd = "%s log --pretty=oneline -n 1 %s -- 2> /dev/null | wc -l" % (
  262. ud.basecmd, ud.revisions[name])
  263. else:
  264. cmd = "%s branch --contains %s --list %s 2> /dev/null | wc -l" % (
  265. ud.basecmd, ud.revisions[name], ud.branches[name])
  266. try:
  267. output = runfetchcmd(cmd, d, quiet=True)
  268. except bb.fetch2.FetchError:
  269. return False
  270. if len(output.split()) > 1:
  271. raise bb.fetch2.FetchError("The command '%s' gave output with more then 1 line unexpectedly, output: '%s'" % (cmd, output))
  272. return output.split()[0] != "0"
  273. def _get_repo_url(self, ud):
  274. """
  275. Return the repository URL
  276. """
  277. if ud.user:
  278. username = ud.user + '@'
  279. else:
  280. username = ""
  281. return "%s://%s%s%s" % (ud.proto, username, ud.host, ud.path)
  282. def _revision_key(self, ud, d, name):
  283. """
  284. Return a unique key for the url
  285. """
  286. return "git:" + ud.host + ud.path.replace('/', '.') + ud.unresolvedrev[name]
  287. def _lsremote(self, ud, d, search):
  288. """
  289. Run git ls-remote with the specified search string
  290. """
  291. repourl = self._get_repo_url(ud)
  292. cmd = "%s ls-remote %s %s" % \
  293. (ud.basecmd, repourl, search)
  294. if ud.proto.lower() != 'file':
  295. bb.fetch2.check_network_access(d, cmd)
  296. output = runfetchcmd(cmd, d, True)
  297. if not output:
  298. raise bb.fetch2.FetchError("The command %s gave empty output unexpectedly" % cmd, ud.url)
  299. return output
  300. def _latest_revision(self, ud, d, name):
  301. """
  302. Compute the HEAD revision for the url
  303. """
  304. output = self._lsremote(ud, d, "")
  305. # Tags of the form ^{} may not work, need to fallback to other form
  306. if ud.unresolvedrev[name][:5] == "refs/":
  307. head = ud.unresolvedrev[name]
  308. tag = ud.unresolvedrev[name]
  309. else:
  310. head = "refs/heads/%s" % ud.unresolvedrev[name]
  311. tag = "refs/tags/%s" % ud.unresolvedrev[name]
  312. for s in [head, tag + "^{}", tag]:
  313. for l in output.split('\n'):
  314. if s in l:
  315. return l.split()[0]
  316. raise bb.fetch2.FetchError("Unable to resolve '%s' in upstream git repository in git ls-remote output for %s" % \
  317. (ud.unresolvedrev[name], ud.host+ud.path))
  318. def latest_versionstring(self, ud, d):
  319. """
  320. Compute the latest release name like "x.y.x" in "x.y.x+gitHASH"
  321. by searching through the tags output of ls-remote, comparing
  322. versions and returning the highest match.
  323. """
  324. pupver = ('', '')
  325. tagregex = re.compile(d.getVar('UPSTREAM_CHECK_GITTAGREGEX', True) or "(?P<pver>([0-9][\.|_]?)+)")
  326. try:
  327. output = self._lsremote(ud, d, "refs/tags/*")
  328. except bb.fetch2.FetchError or bb.fetch2.NetworkAccess:
  329. return pupver
  330. verstring = ""
  331. revision = ""
  332. for line in output.split("\n"):
  333. if not line:
  334. break
  335. tag_head = line.split("/")[-1]
  336. # Ignore non-released branches
  337. m = re.search("(alpha|beta|rc|final)+", tag_head)
  338. if m:
  339. continue
  340. # search for version in the line
  341. tag = tagregex.search(tag_head)
  342. if tag == None:
  343. continue
  344. tag = tag.group('pver')
  345. tag = tag.replace("_", ".")
  346. if verstring and bb.utils.vercmp(("0", tag, ""), ("0", verstring, "")) < 0:
  347. continue
  348. verstring = tag
  349. revision = line.split()[0]
  350. pupver = (verstring, revision)
  351. return pupver
  352. def _build_revision(self, ud, d, name):
  353. return ud.revisions[name]
  354. def gitpkgv_revision(self, ud, d, name):
  355. """
  356. Return a sortable revision number by counting commits in the history
  357. Based on gitpkgv.bblass in meta-openembedded
  358. """
  359. rev = self._build_revision(ud, d, name)
  360. localpath = ud.localpath
  361. rev_file = os.path.join(localpath, "oe-gitpkgv_" + rev)
  362. if not os.path.exists(localpath):
  363. commits = None
  364. else:
  365. if not os.path.exists(rev_file) or not os.path.getsize(rev_file):
  366. from pipes import quote
  367. commits = bb.fetch2.runfetchcmd(
  368. "git rev-list %s -- | wc -l" % (quote(rev)),
  369. d, quiet=True).strip().lstrip('0')
  370. if commits:
  371. open(rev_file, "w").write("%d\n" % int(commits))
  372. else:
  373. commits = open(rev_file, "r").readline(128).strip()
  374. if commits:
  375. return False, "%s+%s" % (commits, rev[:7])
  376. else:
  377. return True, str(rev)
  378. def checkstatus(self, fetch, ud, d):
  379. try:
  380. self._lsremote(ud, d, "")
  381. return True
  382. except FetchError:
  383. return False