git.py 28 KB

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