git.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. - usehead
  42. For local git:// urls to use the current branch HEAD as the revision for use with
  43. AUTOREV. Implies nobranch.
  44. """
  45. # Copyright (C) 2005 Richard Purdie
  46. #
  47. # SPDX-License-Identifier: GPL-2.0-only
  48. #
  49. # This program is free software; you can redistribute it and/or modify
  50. # it under the terms of the GNU General Public License version 2 as
  51. # published by the Free Software Foundation.
  52. #
  53. # This program is distributed in the hope that it will be useful,
  54. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  55. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  56. # GNU General Public License for more details.
  57. #
  58. # You should have received a copy of the GNU General Public License along
  59. # with this program; if not, write to the Free Software Foundation, Inc.,
  60. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  61. import collections
  62. import errno
  63. import fnmatch
  64. import os
  65. import re
  66. import subprocess
  67. import tempfile
  68. import bb
  69. import bb.progress
  70. from bb.fetch2 import FetchMethod
  71. from bb.fetch2 import runfetchcmd
  72. from bb.fetch2 import logger
  73. class GitProgressHandler(bb.progress.LineFilterProgressHandler):
  74. """Extract progress information from git output"""
  75. def __init__(self, d):
  76. self._buffer = ''
  77. self._count = 0
  78. super(GitProgressHandler, self).__init__(d)
  79. # Send an initial progress event so the bar gets shown
  80. self._fire_progress(-1)
  81. def write(self, string):
  82. self._buffer += string
  83. stages = ['Counting objects', 'Compressing objects', 'Receiving objects', 'Resolving deltas']
  84. stage_weights = [0.2, 0.05, 0.5, 0.25]
  85. stagenum = 0
  86. for i, stage in reversed(list(enumerate(stages))):
  87. if stage in self._buffer:
  88. stagenum = i
  89. self._buffer = ''
  90. break
  91. self._status = stages[stagenum]
  92. percs = re.findall(r'(\d+)%', string)
  93. if percs:
  94. progress = int(round((int(percs[-1]) * stage_weights[stagenum]) + (sum(stage_weights[:stagenum]) * 100)))
  95. rates = re.findall(r'([\d.]+ [a-zA-Z]*/s+)', string)
  96. if rates:
  97. rate = rates[-1]
  98. else:
  99. rate = None
  100. self.update(progress, rate)
  101. else:
  102. if stagenum == 0:
  103. percs = re.findall(r': (\d+)', string)
  104. if percs:
  105. count = int(percs[-1])
  106. if count > self._count:
  107. self._count = count
  108. self._fire_progress(-count)
  109. super(GitProgressHandler, self).write(string)
  110. class Git(FetchMethod):
  111. bitbake_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.join(os.path.abspath(__file__))), '..', '..', '..'))
  112. make_shallow_path = os.path.join(bitbake_dir, 'bin', 'git-make-shallow')
  113. """Class to fetch a module or modules from git repositories"""
  114. def init(self, d):
  115. pass
  116. def supports(self, ud, d):
  117. """
  118. Check to see if a given url can be fetched with git.
  119. """
  120. return ud.type in ['git']
  121. def supports_checksum(self, urldata):
  122. return False
  123. def urldata_init(self, ud, d):
  124. """
  125. init git specific variable within url data
  126. so that the git method like latest_revision() can work
  127. """
  128. if 'protocol' in ud.parm:
  129. ud.proto = ud.parm['protocol']
  130. elif not ud.host:
  131. ud.proto = 'file'
  132. else:
  133. ud.proto = "git"
  134. if not ud.proto in ('git', 'file', 'ssh', 'http', 'https', 'rsync'):
  135. raise bb.fetch2.ParameterError("Invalid protocol type", ud.url)
  136. ud.nocheckout = ud.parm.get("nocheckout","0") == "1"
  137. ud.rebaseable = ud.parm.get("rebaseable","0") == "1"
  138. ud.nobranch = ud.parm.get("nobranch","0") == "1"
  139. # usehead implies nobranch
  140. ud.usehead = ud.parm.get("usehead","0") == "1"
  141. if ud.usehead:
  142. if ud.proto != "file":
  143. raise bb.fetch2.ParameterError("The usehead option is only for use with local ('protocol=file') git repositories", ud.url)
  144. ud.nobranch = 1
  145. # bareclone implies nocheckout
  146. ud.bareclone = ud.parm.get("bareclone","0") == "1"
  147. if ud.bareclone:
  148. ud.nocheckout = 1
  149. ud.unresolvedrev = {}
  150. branches = ud.parm.get("branch", "master").split(',')
  151. if len(branches) != len(ud.names):
  152. raise bb.fetch2.ParameterError("The number of name and branch parameters is not balanced", ud.url)
  153. ud.cloneflags = "-s -n"
  154. if ud.bareclone:
  155. ud.cloneflags += " --mirror"
  156. ud.shallow = d.getVar("BB_GIT_SHALLOW") == "1"
  157. ud.shallow_extra_refs = (d.getVar("BB_GIT_SHALLOW_EXTRA_REFS") or "").split()
  158. depth_default = d.getVar("BB_GIT_SHALLOW_DEPTH")
  159. if depth_default is not None:
  160. try:
  161. depth_default = int(depth_default or 0)
  162. except ValueError:
  163. raise bb.fetch2.FetchError("Invalid depth for BB_GIT_SHALLOW_DEPTH: %s" % depth_default)
  164. else:
  165. if depth_default < 0:
  166. raise bb.fetch2.FetchError("Invalid depth for BB_GIT_SHALLOW_DEPTH: %s" % depth_default)
  167. else:
  168. depth_default = 1
  169. ud.shallow_depths = collections.defaultdict(lambda: depth_default)
  170. revs_default = d.getVar("BB_GIT_SHALLOW_REVS")
  171. ud.shallow_revs = []
  172. ud.branches = {}
  173. for pos, name in enumerate(ud.names):
  174. branch = branches[pos]
  175. ud.branches[name] = branch
  176. ud.unresolvedrev[name] = branch
  177. shallow_depth = d.getVar("BB_GIT_SHALLOW_DEPTH_%s" % name)
  178. if shallow_depth is not None:
  179. try:
  180. shallow_depth = int(shallow_depth or 0)
  181. except ValueError:
  182. raise bb.fetch2.FetchError("Invalid depth for BB_GIT_SHALLOW_DEPTH_%s: %s" % (name, shallow_depth))
  183. else:
  184. if shallow_depth < 0:
  185. raise bb.fetch2.FetchError("Invalid depth for BB_GIT_SHALLOW_DEPTH_%s: %s" % (name, shallow_depth))
  186. ud.shallow_depths[name] = shallow_depth
  187. revs = d.getVar("BB_GIT_SHALLOW_REVS_%s" % name)
  188. if revs is not None:
  189. ud.shallow_revs.extend(revs.split())
  190. elif revs_default is not None:
  191. ud.shallow_revs.extend(revs_default.split())
  192. if (ud.shallow and
  193. not ud.shallow_revs and
  194. all(ud.shallow_depths[n] == 0 for n in ud.names)):
  195. # Shallow disabled for this URL
  196. ud.shallow = False
  197. if ud.usehead:
  198. ud.unresolvedrev['default'] = 'HEAD'
  199. ud.basecmd = d.getVar("FETCHCMD_git") or "git -c core.fsyncobjectfiles=0"
  200. write_tarballs = d.getVar("BB_GENERATE_MIRROR_TARBALLS") or "0"
  201. ud.write_tarballs = write_tarballs != "0" or ud.rebaseable
  202. ud.write_shallow_tarballs = (d.getVar("BB_GENERATE_SHALLOW_TARBALLS") or write_tarballs) != "0"
  203. ud.setup_revisions(d)
  204. for name in ud.names:
  205. # Ensure anything that doesn't look like a sha256 checksum/revision is translated into one
  206. if not ud.revisions[name] or len(ud.revisions[name]) != 40 or (False in [c in "abcdef0123456789" for c in ud.revisions[name]]):
  207. if ud.revisions[name]:
  208. ud.unresolvedrev[name] = ud.revisions[name]
  209. ud.revisions[name] = self.latest_revision(ud, d, name)
  210. gitsrcname = '%s%s' % (ud.host.replace(':', '.'), ud.path.replace('/', '.').replace('*', '.'))
  211. if gitsrcname.startswith('.'):
  212. gitsrcname = gitsrcname[1:]
  213. # for rebaseable git repo, it is necessary to keep mirror tar ball
  214. # per revision, so that even the revision disappears from the
  215. # upstream repo in the future, the mirror will remain intact and still
  216. # contains the revision
  217. if ud.rebaseable:
  218. for name in ud.names:
  219. gitsrcname = gitsrcname + '_' + ud.revisions[name]
  220. dl_dir = d.getVar("DL_DIR")
  221. gitdir = d.getVar("GITDIR") or (dl_dir + "/git2")
  222. ud.clonedir = os.path.join(gitdir, gitsrcname)
  223. ud.localfile = ud.clonedir
  224. mirrortarball = 'git2_%s.tar.gz' % gitsrcname
  225. ud.fullmirror = os.path.join(dl_dir, mirrortarball)
  226. ud.mirrortarballs = [mirrortarball]
  227. if ud.shallow:
  228. tarballname = gitsrcname
  229. if ud.bareclone:
  230. tarballname = "%s_bare" % tarballname
  231. if ud.shallow_revs:
  232. tarballname = "%s_%s" % (tarballname, "_".join(sorted(ud.shallow_revs)))
  233. for name, revision in sorted(ud.revisions.items()):
  234. tarballname = "%s_%s" % (tarballname, ud.revisions[name][:7])
  235. depth = ud.shallow_depths[name]
  236. if depth:
  237. tarballname = "%s-%s" % (tarballname, depth)
  238. shallow_refs = []
  239. if not ud.nobranch:
  240. shallow_refs.extend(ud.branches.values())
  241. if ud.shallow_extra_refs:
  242. shallow_refs.extend(r.replace('refs/heads/', '').replace('*', 'ALL') for r in ud.shallow_extra_refs)
  243. if shallow_refs:
  244. tarballname = "%s_%s" % (tarballname, "_".join(sorted(shallow_refs)).replace('/', '.'))
  245. fetcher = self.__class__.__name__.lower()
  246. ud.shallowtarball = '%sshallow_%s.tar.gz' % (fetcher, tarballname)
  247. ud.fullshallow = os.path.join(dl_dir, ud.shallowtarball)
  248. ud.mirrortarballs.insert(0, ud.shallowtarball)
  249. def localpath(self, ud, d):
  250. return ud.clonedir
  251. def need_update(self, ud, d):
  252. return self.clonedir_need_update(ud, d) or self.shallow_tarball_need_update(ud) or self.tarball_need_update(ud)
  253. def clonedir_need_update(self, ud, d):
  254. if not os.path.exists(ud.clonedir):
  255. return True
  256. for name in ud.names:
  257. if not self._contains_ref(ud, d, name, ud.clonedir):
  258. return True
  259. return False
  260. def shallow_tarball_need_update(self, ud):
  261. return ud.shallow and ud.write_shallow_tarballs and not os.path.exists(ud.fullshallow)
  262. def tarball_need_update(self, ud):
  263. return ud.write_tarballs and not os.path.exists(ud.fullmirror)
  264. def try_premirror(self, ud, d):
  265. # If we don't do this, updating an existing checkout with only premirrors
  266. # is not possible
  267. if bb.utils.to_boolean(d.getVar("BB_FETCH_PREMIRRORONLY")):
  268. return True
  269. if os.path.exists(ud.clonedir):
  270. return False
  271. return True
  272. def download(self, ud, d):
  273. """Fetch url"""
  274. # A current clone is preferred to either tarball, a shallow tarball is
  275. # preferred to an out of date clone, and a missing clone will use
  276. # either tarball.
  277. if ud.shallow and os.path.exists(ud.fullshallow) and self.need_update(ud, d):
  278. ud.localpath = ud.fullshallow
  279. return
  280. elif os.path.exists(ud.fullmirror) and not os.path.exists(ud.clonedir):
  281. bb.utils.mkdirhier(ud.clonedir)
  282. runfetchcmd("tar -xzf %s" % ud.fullmirror, d, workdir=ud.clonedir)
  283. repourl = self._get_repo_url(ud)
  284. # If the repo still doesn't exist, fallback to cloning it
  285. if not os.path.exists(ud.clonedir):
  286. # We do this since git will use a "-l" option automatically for local urls where possible
  287. if repourl.startswith("file://"):
  288. repourl = repourl[7:]
  289. clone_cmd = "LANG=C %s clone --bare --mirror %s %s --progress" % (ud.basecmd, repourl, ud.clonedir)
  290. if ud.proto.lower() != 'file':
  291. bb.fetch2.check_network_access(d, clone_cmd, ud.url)
  292. progresshandler = GitProgressHandler(d)
  293. runfetchcmd(clone_cmd, d, log=progresshandler)
  294. # Update the checkout if needed
  295. needupdate = False
  296. for name in ud.names:
  297. if not self._contains_ref(ud, d, name, ud.clonedir):
  298. needupdate = True
  299. break
  300. if needupdate:
  301. output = runfetchcmd("%s remote" % ud.basecmd, d, quiet=True, workdir=ud.clonedir)
  302. if "origin" in output:
  303. runfetchcmd("%s remote rm origin" % ud.basecmd, d, workdir=ud.clonedir)
  304. runfetchcmd("%s remote add --mirror=fetch origin %s" % (ud.basecmd, repourl), d, workdir=ud.clonedir)
  305. fetch_cmd = "LANG=C %s fetch -f --prune --progress %s refs/*:refs/*" % (ud.basecmd, repourl)
  306. if ud.proto.lower() != 'file':
  307. bb.fetch2.check_network_access(d, fetch_cmd, ud.url)
  308. progresshandler = GitProgressHandler(d)
  309. runfetchcmd(fetch_cmd, d, log=progresshandler, workdir=ud.clonedir)
  310. runfetchcmd("%s prune-packed" % ud.basecmd, d, workdir=ud.clonedir)
  311. runfetchcmd("%s pack-refs --all" % ud.basecmd, d, workdir=ud.clonedir)
  312. runfetchcmd("%s pack-redundant --all | xargs -r rm" % ud.basecmd, d, workdir=ud.clonedir)
  313. try:
  314. os.unlink(ud.fullmirror)
  315. except OSError as exc:
  316. if exc.errno != errno.ENOENT:
  317. raise
  318. for name in ud.names:
  319. if not self._contains_ref(ud, d, name, ud.clonedir):
  320. raise bb.fetch2.FetchError("Unable to find revision %s in branch %s even from upstream" % (ud.revisions[name], ud.branches[name]))
  321. def build_mirror_data(self, ud, d):
  322. if ud.shallow and ud.write_shallow_tarballs:
  323. if not os.path.exists(ud.fullshallow):
  324. if os.path.islink(ud.fullshallow):
  325. os.unlink(ud.fullshallow)
  326. tempdir = tempfile.mkdtemp(dir=d.getVar('DL_DIR'))
  327. shallowclone = os.path.join(tempdir, 'git')
  328. try:
  329. self.clone_shallow_local(ud, shallowclone, d)
  330. logger.info("Creating tarball of git repository")
  331. runfetchcmd("tar -czf %s ." % ud.fullshallow, d, workdir=shallowclone)
  332. runfetchcmd("touch %s.done" % ud.fullshallow, d)
  333. finally:
  334. bb.utils.remove(tempdir, recurse=True)
  335. elif ud.write_tarballs and not os.path.exists(ud.fullmirror):
  336. if os.path.islink(ud.fullmirror):
  337. os.unlink(ud.fullmirror)
  338. logger.info("Creating tarball of git repository")
  339. runfetchcmd("tar -czf %s ." % ud.fullmirror, d, workdir=ud.clonedir)
  340. runfetchcmd("touch %s.done" % ud.fullmirror, d)
  341. def clone_shallow_local(self, ud, dest, d):
  342. """Clone the repo and make it shallow.
  343. The upstream url of the new clone isn't set at this time, as it'll be
  344. set correctly when unpacked."""
  345. runfetchcmd("%s clone %s %s %s" % (ud.basecmd, ud.cloneflags, ud.clonedir, dest), d)
  346. to_parse, shallow_branches = [], []
  347. for name in ud.names:
  348. revision = ud.revisions[name]
  349. depth = ud.shallow_depths[name]
  350. if depth:
  351. to_parse.append('%s~%d^{}' % (revision, depth - 1))
  352. # For nobranch, we need a ref, otherwise the commits will be
  353. # removed, and for non-nobranch, we truncate the branch to our
  354. # srcrev, to avoid keeping unnecessary history beyond that.
  355. branch = ud.branches[name]
  356. if ud.nobranch:
  357. ref = "refs/shallow/%s" % name
  358. elif ud.bareclone:
  359. ref = "refs/heads/%s" % branch
  360. else:
  361. ref = "refs/remotes/origin/%s" % branch
  362. shallow_branches.append(ref)
  363. runfetchcmd("%s update-ref %s %s" % (ud.basecmd, ref, revision), d, workdir=dest)
  364. # Map srcrev+depths to revisions
  365. parsed_depths = runfetchcmd("%s rev-parse %s" % (ud.basecmd, " ".join(to_parse)), d, workdir=dest)
  366. # Resolve specified revisions
  367. parsed_revs = runfetchcmd("%s rev-parse %s" % (ud.basecmd, " ".join('"%s^{}"' % r for r in ud.shallow_revs)), d, workdir=dest)
  368. shallow_revisions = parsed_depths.splitlines() + parsed_revs.splitlines()
  369. # Apply extra ref wildcards
  370. all_refs = runfetchcmd('%s for-each-ref "--format=%%(refname)"' % ud.basecmd,
  371. d, workdir=dest).splitlines()
  372. for r in ud.shallow_extra_refs:
  373. if not ud.bareclone:
  374. r = r.replace('refs/heads/', 'refs/remotes/origin/')
  375. if '*' in r:
  376. matches = filter(lambda a: fnmatch.fnmatchcase(a, r), all_refs)
  377. shallow_branches.extend(matches)
  378. else:
  379. shallow_branches.append(r)
  380. # Make the repository shallow
  381. shallow_cmd = [self.make_shallow_path, '-s']
  382. for b in shallow_branches:
  383. shallow_cmd.append('-r')
  384. shallow_cmd.append(b)
  385. shallow_cmd.extend(shallow_revisions)
  386. runfetchcmd(subprocess.list2cmdline(shallow_cmd), d, workdir=dest)
  387. def unpack(self, ud, destdir, d):
  388. """ unpack the downloaded src to destdir"""
  389. subdir = ud.parm.get("subpath", "")
  390. if subdir != "":
  391. readpathspec = ":%s" % subdir
  392. def_destsuffix = "%s/" % os.path.basename(subdir.rstrip('/'))
  393. else:
  394. readpathspec = ""
  395. def_destsuffix = "git/"
  396. destsuffix = ud.parm.get("destsuffix", def_destsuffix)
  397. destdir = ud.destdir = os.path.join(destdir, destsuffix)
  398. if os.path.exists(destdir):
  399. bb.utils.prunedir(destdir)
  400. source_found = False
  401. source_error = []
  402. if not source_found:
  403. clonedir_is_up_to_date = not self.clonedir_need_update(ud, d)
  404. if clonedir_is_up_to_date:
  405. runfetchcmd("%s clone %s %s/ %s" % (ud.basecmd, ud.cloneflags, ud.clonedir, destdir), d)
  406. source_found = True
  407. else:
  408. source_error.append("clone directory not available or not up to date: " + ud.clonedir)
  409. if not source_found:
  410. if ud.shallow:
  411. if os.path.exists(ud.fullshallow):
  412. bb.utils.mkdirhier(destdir)
  413. runfetchcmd("tar -xzf %s" % ud.fullshallow, d, workdir=destdir)
  414. source_found = True
  415. else:
  416. source_error.append("shallow clone not available: " + ud.fullshallow)
  417. else:
  418. source_error.append("shallow clone not enabled")
  419. if not source_found:
  420. raise bb.fetch2.UnpackError("No up to date source found: " + "; ".join(source_error), ud.url)
  421. repourl = self._get_repo_url(ud)
  422. runfetchcmd("%s remote set-url origin %s" % (ud.basecmd, repourl), d, workdir=destdir)
  423. if self._contains_lfs(ud, d, destdir):
  424. path = d.getVar('PATH')
  425. if path:
  426. gitlfstool = bb.utils.which(path, "git-lfs", executable=True)
  427. if not gitlfstool:
  428. raise bb.fetch2.FetchError("Repository %s has lfs content, install git-lfs plugin on host to download" % (repourl))
  429. else:
  430. bb.note("Could not find 'PATH'")
  431. if not ud.nocheckout:
  432. if subdir != "":
  433. runfetchcmd("%s read-tree %s%s" % (ud.basecmd, ud.revisions[ud.names[0]], readpathspec), d,
  434. workdir=destdir)
  435. runfetchcmd("%s checkout-index -q -f -a" % ud.basecmd, d, workdir=destdir)
  436. elif not ud.nobranch:
  437. branchname = ud.branches[ud.names[0]]
  438. runfetchcmd("%s checkout -B %s %s" % (ud.basecmd, branchname, \
  439. ud.revisions[ud.names[0]]), d, workdir=destdir)
  440. runfetchcmd("%s branch %s --set-upstream-to origin/%s" % (ud.basecmd, branchname, \
  441. branchname), d, workdir=destdir)
  442. else:
  443. runfetchcmd("%s checkout %s" % (ud.basecmd, ud.revisions[ud.names[0]]), d, workdir=destdir)
  444. return True
  445. def clean(self, ud, d):
  446. """ clean the git directory """
  447. to_remove = [ud.localpath, ud.fullmirror, ud.fullmirror + ".done"]
  448. # The localpath is a symlink to clonedir when it is cloned from a
  449. # mirror, so remove both of them.
  450. if os.path.islink(ud.localpath):
  451. clonedir = os.path.realpath(ud.localpath)
  452. to_remove.append(clonedir)
  453. for r in to_remove:
  454. if os.path.exists(r):
  455. bb.note('Removing %s' % r)
  456. bb.utils.remove(r, True)
  457. def supports_srcrev(self):
  458. return True
  459. def _contains_ref(self, ud, d, name, wd):
  460. cmd = ""
  461. if ud.nobranch:
  462. cmd = "%s log --pretty=oneline -n 1 %s -- 2> /dev/null | wc -l" % (
  463. ud.basecmd, ud.revisions[name])
  464. else:
  465. cmd = "%s branch --contains %s --list %s 2> /dev/null | wc -l" % (
  466. ud.basecmd, ud.revisions[name], ud.branches[name])
  467. try:
  468. output = runfetchcmd(cmd, d, quiet=True, workdir=wd)
  469. except bb.fetch2.FetchError:
  470. return False
  471. if len(output.split()) > 1:
  472. raise bb.fetch2.FetchError("The command '%s' gave output with more then 1 line unexpectedly, output: '%s'" % (cmd, output))
  473. return output.split()[0] != "0"
  474. def _contains_lfs(self, ud, d, wd):
  475. """
  476. Check if the repository has 'lfs' (large file) content
  477. """
  478. cmd = "%s grep lfs HEAD:.gitattributes | wc -l" % (
  479. ud.basecmd)
  480. try:
  481. output = runfetchcmd(cmd, d, quiet=True, workdir=wd)
  482. if int(output) > 0:
  483. return True
  484. except (bb.fetch2.FetchError,ValueError):
  485. pass
  486. return False
  487. def _get_repo_url(self, ud):
  488. """
  489. Return the repository URL
  490. """
  491. if ud.user:
  492. username = ud.user + '@'
  493. else:
  494. username = ""
  495. return "%s://%s%s%s" % (ud.proto, username, ud.host, ud.path)
  496. def _revision_key(self, ud, d, name):
  497. """
  498. Return a unique key for the url
  499. """
  500. return "git:" + ud.host + ud.path.replace('/', '.') + ud.unresolvedrev[name]
  501. def _lsremote(self, ud, d, search):
  502. """
  503. Run git ls-remote with the specified search string
  504. """
  505. # Prevent recursion e.g. in OE if SRCPV is in PV, PV is in WORKDIR,
  506. # and WORKDIR is in PATH (as a result of RSS), our call to
  507. # runfetchcmd() exports PATH so this function will get called again (!)
  508. # In this scenario the return call of the function isn't actually
  509. # important - WORKDIR isn't needed in PATH to call git ls-remote
  510. # anyway.
  511. if d.getVar('_BB_GIT_IN_LSREMOTE', False):
  512. return ''
  513. d.setVar('_BB_GIT_IN_LSREMOTE', '1')
  514. try:
  515. repourl = self._get_repo_url(ud)
  516. cmd = "%s ls-remote %s %s" % \
  517. (ud.basecmd, repourl, search)
  518. if ud.proto.lower() != 'file':
  519. bb.fetch2.check_network_access(d, cmd, repourl)
  520. output = runfetchcmd(cmd, d, True)
  521. if not output:
  522. raise bb.fetch2.FetchError("The command %s gave empty output unexpectedly" % cmd, ud.url)
  523. finally:
  524. d.delVar('_BB_GIT_IN_LSREMOTE')
  525. return output
  526. def _latest_revision(self, ud, d, name):
  527. """
  528. Compute the HEAD revision for the url
  529. """
  530. output = self._lsremote(ud, d, "")
  531. # Tags of the form ^{} may not work, need to fallback to other form
  532. if ud.unresolvedrev[name][:5] == "refs/" or ud.usehead:
  533. head = ud.unresolvedrev[name]
  534. tag = ud.unresolvedrev[name]
  535. else:
  536. head = "refs/heads/%s" % ud.unresolvedrev[name]
  537. tag = "refs/tags/%s" % ud.unresolvedrev[name]
  538. for s in [head, tag + "^{}", tag]:
  539. for l in output.strip().split('\n'):
  540. sha1, ref = l.split()
  541. if s == ref:
  542. return sha1
  543. raise bb.fetch2.FetchError("Unable to resolve '%s' in upstream git repository in git ls-remote output for %s" % \
  544. (ud.unresolvedrev[name], ud.host+ud.path))
  545. def latest_versionstring(self, ud, d):
  546. """
  547. Compute the latest release name like "x.y.x" in "x.y.x+gitHASH"
  548. by searching through the tags output of ls-remote, comparing
  549. versions and returning the highest match.
  550. """
  551. pupver = ('', '')
  552. tagregex = re.compile(d.getVar('UPSTREAM_CHECK_GITTAGREGEX') or r"(?P<pver>([0-9][\.|_]?)+)")
  553. try:
  554. output = self._lsremote(ud, d, "refs/tags/*")
  555. except (bb.fetch2.FetchError, bb.fetch2.NetworkAccess) as e:
  556. bb.note("Could not list remote: %s" % str(e))
  557. return pupver
  558. verstring = ""
  559. revision = ""
  560. for line in output.split("\n"):
  561. if not line:
  562. break
  563. tag_head = line.split("/")[-1]
  564. # Ignore non-released branches
  565. m = re.search(r"(alpha|beta|rc|final)+", tag_head)
  566. if m:
  567. continue
  568. # search for version in the line
  569. tag = tagregex.search(tag_head)
  570. if tag == None:
  571. continue
  572. tag = tag.group('pver')
  573. tag = tag.replace("_", ".")
  574. if verstring and bb.utils.vercmp(("0", tag, ""), ("0", verstring, "")) < 0:
  575. continue
  576. verstring = tag
  577. revision = line.split()[0]
  578. pupver = (verstring, revision)
  579. return pupver
  580. def _build_revision(self, ud, d, name):
  581. return ud.revisions[name]
  582. def gitpkgv_revision(self, ud, d, name):
  583. """
  584. Return a sortable revision number by counting commits in the history
  585. Based on gitpkgv.bblass in meta-openembedded
  586. """
  587. rev = self._build_revision(ud, d, name)
  588. localpath = ud.localpath
  589. rev_file = os.path.join(localpath, "oe-gitpkgv_" + rev)
  590. if not os.path.exists(localpath):
  591. commits = None
  592. else:
  593. if not os.path.exists(rev_file) or not os.path.getsize(rev_file):
  594. from pipes import quote
  595. commits = bb.fetch2.runfetchcmd(
  596. "git rev-list %s -- | wc -l" % quote(rev),
  597. d, quiet=True).strip().lstrip('0')
  598. if commits:
  599. open(rev_file, "w").write("%d\n" % int(commits))
  600. else:
  601. commits = open(rev_file, "r").readline(128).strip()
  602. if commits:
  603. return False, "%s+%s" % (commits, rev[:7])
  604. else:
  605. return True, str(rev)
  606. def checkstatus(self, fetch, ud, d):
  607. try:
  608. self._lsremote(ud, d, "")
  609. return True
  610. except bb.fetch2.FetchError:
  611. return False