project.py 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  1. # Copyright (C) 2008 The Android Open Source Project
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import print_function
  15. import traceback
  16. import errno
  17. import filecmp
  18. import os
  19. import random
  20. import re
  21. import shutil
  22. import stat
  23. import subprocess
  24. import sys
  25. import time
  26. from color import Coloring
  27. from git_command import GitCommand, git_require
  28. from git_config import GitConfig, IsId, GetSchemeFromUrl, ID_RE
  29. from error import GitError, HookError, UploadError
  30. from error import ManifestInvalidRevisionError
  31. from trace import IsTrace, Trace
  32. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  33. def _lwrite(path, content):
  34. lock = '%s.lock' % path
  35. fd = open(lock, 'wb')
  36. try:
  37. fd.write(content)
  38. finally:
  39. fd.close()
  40. try:
  41. os.rename(lock, path)
  42. except OSError:
  43. os.remove(lock)
  44. raise
  45. def _error(fmt, *args):
  46. msg = fmt % args
  47. print('error: %s' % msg, file=sys.stderr)
  48. def not_rev(r):
  49. return '^' + r
  50. def sq(r):
  51. return "'" + r.replace("'", "'\''") + "'"
  52. _project_hook_list = None
  53. def _ProjectHooks():
  54. """List the hooks present in the 'hooks' directory.
  55. These hooks are project hooks and are copied to the '.git/hooks' directory
  56. of all subprojects.
  57. This function caches the list of hooks (based on the contents of the
  58. 'repo/hooks' directory) on the first call.
  59. Returns:
  60. A list of absolute paths to all of the files in the hooks directory.
  61. """
  62. global _project_hook_list
  63. if _project_hook_list is None:
  64. d = os.path.abspath(os.path.dirname(__file__))
  65. d = os.path.join(d , 'hooks')
  66. _project_hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
  67. return _project_hook_list
  68. class DownloadedChange(object):
  69. _commit_cache = None
  70. def __init__(self, project, base, change_id, ps_id, commit):
  71. self.project = project
  72. self.base = base
  73. self.change_id = change_id
  74. self.ps_id = ps_id
  75. self.commit = commit
  76. @property
  77. def commits(self):
  78. if self._commit_cache is None:
  79. self._commit_cache = self.project.bare_git.rev_list(
  80. '--abbrev=8',
  81. '--abbrev-commit',
  82. '--pretty=oneline',
  83. '--reverse',
  84. '--date-order',
  85. not_rev(self.base),
  86. self.commit,
  87. '--')
  88. return self._commit_cache
  89. class ReviewableBranch(object):
  90. _commit_cache = None
  91. def __init__(self, project, branch, base):
  92. self.project = project
  93. self.branch = branch
  94. self.base = base
  95. @property
  96. def name(self):
  97. return self.branch.name
  98. @property
  99. def commits(self):
  100. if self._commit_cache is None:
  101. self._commit_cache = self.project.bare_git.rev_list(
  102. '--abbrev=8',
  103. '--abbrev-commit',
  104. '--pretty=oneline',
  105. '--reverse',
  106. '--date-order',
  107. not_rev(self.base),
  108. R_HEADS + self.name,
  109. '--')
  110. return self._commit_cache
  111. @property
  112. def unabbrev_commits(self):
  113. r = dict()
  114. for commit in self.project.bare_git.rev_list(
  115. not_rev(self.base),
  116. R_HEADS + self.name,
  117. '--'):
  118. r[commit[0:8]] = commit
  119. return r
  120. @property
  121. def date(self):
  122. return self.project.bare_git.log(
  123. '--pretty=format:%cd',
  124. '-n', '1',
  125. R_HEADS + self.name,
  126. '--')
  127. def UploadForReview(self, people, auto_topic=False, draft=False):
  128. self.project.UploadForReview(self.name,
  129. people,
  130. auto_topic=auto_topic,
  131. draft=draft)
  132. def GetPublishedRefs(self):
  133. refs = {}
  134. output = self.project.bare_git.ls_remote(
  135. self.branch.remote.SshReviewUrl(self.project.UserEmail),
  136. 'refs/changes/*')
  137. for line in output.split('\n'):
  138. try:
  139. (sha, ref) = line.split()
  140. refs[sha] = ref
  141. except ValueError:
  142. pass
  143. return refs
  144. class StatusColoring(Coloring):
  145. def __init__(self, config):
  146. Coloring.__init__(self, config, 'status')
  147. self.project = self.printer('header', attr = 'bold')
  148. self.branch = self.printer('header', attr = 'bold')
  149. self.nobranch = self.printer('nobranch', fg = 'red')
  150. self.important = self.printer('important', fg = 'red')
  151. self.added = self.printer('added', fg = 'green')
  152. self.changed = self.printer('changed', fg = 'red')
  153. self.untracked = self.printer('untracked', fg = 'red')
  154. class DiffColoring(Coloring):
  155. def __init__(self, config):
  156. Coloring.__init__(self, config, 'diff')
  157. self.project = self.printer('header', attr = 'bold')
  158. class _Annotation:
  159. def __init__(self, name, value, keep):
  160. self.name = name
  161. self.value = value
  162. self.keep = keep
  163. class _CopyFile:
  164. def __init__(self, src, dest, abssrc, absdest):
  165. self.src = src
  166. self.dest = dest
  167. self.abs_src = abssrc
  168. self.abs_dest = absdest
  169. def _Copy(self):
  170. src = self.abs_src
  171. dest = self.abs_dest
  172. # copy file if it does not exist or is out of date
  173. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  174. try:
  175. # remove existing file first, since it might be read-only
  176. if os.path.exists(dest):
  177. os.remove(dest)
  178. else:
  179. dest_dir = os.path.dirname(dest)
  180. if not os.path.isdir(dest_dir):
  181. os.makedirs(dest_dir)
  182. shutil.copy(src, dest)
  183. # make the file read-only
  184. mode = os.stat(dest)[stat.ST_MODE]
  185. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  186. os.chmod(dest, mode)
  187. except IOError:
  188. _error('Cannot copy file %s to %s', src, dest)
  189. class RemoteSpec(object):
  190. def __init__(self,
  191. name,
  192. url = None,
  193. review = None):
  194. self.name = name
  195. self.url = url
  196. self.review = review
  197. class RepoHook(object):
  198. """A RepoHook contains information about a script to run as a hook.
  199. Hooks are used to run a python script before running an upload (for instance,
  200. to run presubmit checks). Eventually, we may have hooks for other actions.
  201. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  202. files are copied into each '.git/hooks' folder for each project. Repo-level
  203. hooks are associated instead with repo actions.
  204. Hooks are always python. When a hook is run, we will load the hook into the
  205. interpreter and execute its main() function.
  206. """
  207. def __init__(self,
  208. hook_type,
  209. hooks_project,
  210. topdir,
  211. abort_if_user_denies=False):
  212. """RepoHook constructor.
  213. Params:
  214. hook_type: A string representing the type of hook. This is also used
  215. to figure out the name of the file containing the hook. For
  216. example: 'pre-upload'.
  217. hooks_project: The project containing the repo hooks. If you have a
  218. manifest, this is manifest.repo_hooks_project. OK if this is None,
  219. which will make the hook a no-op.
  220. topdir: Repo's top directory (the one containing the .repo directory).
  221. Scripts will run with CWD as this directory. If you have a manifest,
  222. this is manifest.topdir
  223. abort_if_user_denies: If True, we'll throw a HookError() if the user
  224. doesn't allow us to run the hook.
  225. """
  226. self._hook_type = hook_type
  227. self._hooks_project = hooks_project
  228. self._topdir = topdir
  229. self._abort_if_user_denies = abort_if_user_denies
  230. # Store the full path to the script for convenience.
  231. if self._hooks_project:
  232. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  233. self._hook_type + '.py')
  234. else:
  235. self._script_fullpath = None
  236. def _GetHash(self):
  237. """Return a hash of the contents of the hooks directory.
  238. We'll just use git to do this. This hash has the property that if anything
  239. changes in the directory we will return a different has.
  240. SECURITY CONSIDERATION:
  241. This hash only represents the contents of files in the hook directory, not
  242. any other files imported or called by hooks. Changes to imported files
  243. can change the script behavior without affecting the hash.
  244. Returns:
  245. A string representing the hash. This will always be ASCII so that it can
  246. be printed to the user easily.
  247. """
  248. assert self._hooks_project, "Must have hooks to calculate their hash."
  249. # We will use the work_git object rather than just calling GetRevisionId().
  250. # That gives us a hash of the latest checked in version of the files that
  251. # the user will actually be executing. Specifically, GetRevisionId()
  252. # doesn't appear to change even if a user checks out a different version
  253. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  254. #
  255. # NOTE: Local (non-committed) changes will not be factored into this hash.
  256. # I think this is OK, since we're really only worried about warning the user
  257. # about upstream changes.
  258. return self._hooks_project.work_git.rev_parse('HEAD')
  259. def _GetMustVerb(self):
  260. """Return 'must' if the hook is required; 'should' if not."""
  261. if self._abort_if_user_denies:
  262. return 'must'
  263. else:
  264. return 'should'
  265. def _CheckForHookApproval(self):
  266. """Check to see whether this hook has been approved.
  267. We'll look at the hash of all of the hooks. If this matches the hash that
  268. the user last approved, we're done. If it doesn't, we'll ask the user
  269. about approval.
  270. Note that we ask permission for each individual hook even though we use
  271. the hash of all hooks when detecting changes. We'd like the user to be
  272. able to approve / deny each hook individually. We only use the hash of all
  273. hooks because there is no other easy way to detect changes to local imports.
  274. Returns:
  275. True if this hook is approved to run; False otherwise.
  276. Raises:
  277. HookError: Raised if the user doesn't approve and abort_if_user_denies
  278. was passed to the consturctor.
  279. """
  280. hooks_config = self._hooks_project.config
  281. git_approval_key = 'repo.hooks.%s.approvedhash' % self._hook_type
  282. # Get the last hash that the user approved for this hook; may be None.
  283. old_hash = hooks_config.GetString(git_approval_key)
  284. # Get the current hash so we can tell if scripts changed since approval.
  285. new_hash = self._GetHash()
  286. if old_hash is not None:
  287. # User previously approved hook and asked not to be prompted again.
  288. if new_hash == old_hash:
  289. # Approval matched. We're done.
  290. return True
  291. else:
  292. # Give the user a reason why we're prompting, since they last told
  293. # us to "never ask again".
  294. prompt = 'WARNING: Scripts have changed since %s was allowed.\n\n' % (
  295. self._hook_type)
  296. else:
  297. prompt = ''
  298. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  299. if sys.stdout.isatty():
  300. prompt += ('Repo %s run the script:\n'
  301. ' %s\n'
  302. '\n'
  303. 'Do you want to allow this script to run '
  304. '(yes/yes-never-ask-again/NO)? ') % (
  305. self._GetMustVerb(), self._script_fullpath)
  306. response = raw_input(prompt).lower()
  307. print()
  308. # User is doing a one-time approval.
  309. if response in ('y', 'yes'):
  310. return True
  311. elif response == 'yes-never-ask-again':
  312. hooks_config.SetString(git_approval_key, new_hash)
  313. return True
  314. # For anything else, we'll assume no approval.
  315. if self._abort_if_user_denies:
  316. raise HookError('You must allow the %s hook or use --no-verify.' %
  317. self._hook_type)
  318. return False
  319. def _ExecuteHook(self, **kwargs):
  320. """Actually execute the given hook.
  321. This will run the hook's 'main' function in our python interpreter.
  322. Args:
  323. kwargs: Keyword arguments to pass to the hook. These are often specific
  324. to the hook type. For instance, pre-upload hooks will contain
  325. a project_list.
  326. """
  327. # Keep sys.path and CWD stashed away so that we can always restore them
  328. # upon function exit.
  329. orig_path = os.getcwd()
  330. orig_syspath = sys.path
  331. try:
  332. # Always run hooks with CWD as topdir.
  333. os.chdir(self._topdir)
  334. # Put the hook dir as the first item of sys.path so hooks can do
  335. # relative imports. We want to replace the repo dir as [0] so
  336. # hooks can't import repo files.
  337. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  338. # Exec, storing global context in the context dict. We catch exceptions
  339. # and convert to a HookError w/ just the failing traceback.
  340. context = {}
  341. try:
  342. execfile(self._script_fullpath, context)
  343. except Exception:
  344. raise HookError('%s\nFailed to import %s hook; see traceback above.' % (
  345. traceback.format_exc(), self._hook_type))
  346. # Running the script should have defined a main() function.
  347. if 'main' not in context:
  348. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  349. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  350. # We don't actually want hooks to define their main with this argument--
  351. # it's there to remind them that their hook should always take **kwargs.
  352. # For instance, a pre-upload hook should be defined like:
  353. # def main(project_list, **kwargs):
  354. #
  355. # This allows us to later expand the API without breaking old hooks.
  356. kwargs = kwargs.copy()
  357. kwargs['hook_should_take_kwargs'] = True
  358. # Call the main function in the hook. If the hook should cause the
  359. # build to fail, it will raise an Exception. We'll catch that convert
  360. # to a HookError w/ just the failing traceback.
  361. try:
  362. context['main'](**kwargs)
  363. except Exception:
  364. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  365. 'above.' % (
  366. traceback.format_exc(), self._hook_type))
  367. finally:
  368. # Restore sys.path and CWD.
  369. sys.path = orig_syspath
  370. os.chdir(orig_path)
  371. def Run(self, user_allows_all_hooks, **kwargs):
  372. """Run the hook.
  373. If the hook doesn't exist (because there is no hooks project or because
  374. this particular hook is not enabled), this is a no-op.
  375. Args:
  376. user_allows_all_hooks: If True, we will never prompt about running the
  377. hook--we'll just assume it's OK to run it.
  378. kwargs: Keyword arguments to pass to the hook. These are often specific
  379. to the hook type. For instance, pre-upload hooks will contain
  380. a project_list.
  381. Raises:
  382. HookError: If there was a problem finding the hook or the user declined
  383. to run a required hook (from _CheckForHookApproval).
  384. """
  385. # No-op if there is no hooks project or if hook is disabled.
  386. if ((not self._hooks_project) or
  387. (self._hook_type not in self._hooks_project.enabled_repo_hooks)):
  388. return
  389. # Bail with a nice error if we can't find the hook.
  390. if not os.path.isfile(self._script_fullpath):
  391. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  392. # Make sure the user is OK with running the hook.
  393. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  394. return
  395. # Run the hook with the same version of python we're using.
  396. self._ExecuteHook(**kwargs)
  397. class Project(object):
  398. def __init__(self,
  399. manifest,
  400. name,
  401. remote,
  402. gitdir,
  403. worktree,
  404. relpath,
  405. revisionExpr,
  406. revisionId,
  407. rebase = True,
  408. groups = None,
  409. sync_c = False,
  410. upstream = None):
  411. self.manifest = manifest
  412. self.name = name
  413. self.remote = remote
  414. self.gitdir = gitdir.replace('\\', '/')
  415. if worktree:
  416. self.worktree = worktree.replace('\\', '/')
  417. else:
  418. self.worktree = None
  419. self.relpath = relpath
  420. self.revisionExpr = revisionExpr
  421. if revisionId is None \
  422. and revisionExpr \
  423. and IsId(revisionExpr):
  424. self.revisionId = revisionExpr
  425. else:
  426. self.revisionId = revisionId
  427. self.rebase = rebase
  428. self.groups = groups
  429. self.sync_c = sync_c
  430. self.upstream = upstream
  431. self.snapshots = {}
  432. self.copyfiles = []
  433. self.annotations = []
  434. self.config = GitConfig.ForRepository(
  435. gitdir = self.gitdir,
  436. defaults = self.manifest.globalConfig)
  437. if self.worktree:
  438. self.work_git = self._GitGetByExec(self, bare=False)
  439. else:
  440. self.work_git = None
  441. self.bare_git = self._GitGetByExec(self, bare=True)
  442. self.bare_ref = GitRefs(gitdir)
  443. # This will be filled in if a project is later identified to be the
  444. # project containing repo hooks.
  445. self.enabled_repo_hooks = []
  446. @property
  447. def Exists(self):
  448. return os.path.isdir(self.gitdir)
  449. @property
  450. def CurrentBranch(self):
  451. """Obtain the name of the currently checked out branch.
  452. The branch name omits the 'refs/heads/' prefix.
  453. None is returned if the project is on a detached HEAD.
  454. """
  455. b = self.work_git.GetHead()
  456. if b.startswith(R_HEADS):
  457. return b[len(R_HEADS):]
  458. return None
  459. def IsRebaseInProgress(self):
  460. w = self.worktree
  461. g = os.path.join(w, '.git')
  462. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  463. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  464. or os.path.exists(os.path.join(w, '.dotest'))
  465. def IsDirty(self, consider_untracked=True):
  466. """Is the working directory modified in some way?
  467. """
  468. self.work_git.update_index('-q',
  469. '--unmerged',
  470. '--ignore-missing',
  471. '--refresh')
  472. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  473. return True
  474. if self.work_git.DiffZ('diff-files'):
  475. return True
  476. if consider_untracked and self.work_git.LsOthers():
  477. return True
  478. return False
  479. _userident_name = None
  480. _userident_email = None
  481. @property
  482. def UserName(self):
  483. """Obtain the user's personal name.
  484. """
  485. if self._userident_name is None:
  486. self._LoadUserIdentity()
  487. return self._userident_name
  488. @property
  489. def UserEmail(self):
  490. """Obtain the user's email address. This is very likely
  491. to be their Gerrit login.
  492. """
  493. if self._userident_email is None:
  494. self._LoadUserIdentity()
  495. return self._userident_email
  496. def _LoadUserIdentity(self):
  497. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  498. m = re.compile("^(.*) <([^>]*)> ").match(u)
  499. if m:
  500. self._userident_name = m.group(1)
  501. self._userident_email = m.group(2)
  502. else:
  503. self._userident_name = ''
  504. self._userident_email = ''
  505. def GetRemote(self, name):
  506. """Get the configuration for a single remote.
  507. """
  508. return self.config.GetRemote(name)
  509. def GetBranch(self, name):
  510. """Get the configuration for a single branch.
  511. """
  512. return self.config.GetBranch(name)
  513. def GetBranches(self):
  514. """Get all existing local branches.
  515. """
  516. current = self.CurrentBranch
  517. all_refs = self._allrefs
  518. heads = {}
  519. for name, ref_id in all_refs.iteritems():
  520. if name.startswith(R_HEADS):
  521. name = name[len(R_HEADS):]
  522. b = self.GetBranch(name)
  523. b.current = name == current
  524. b.published = None
  525. b.revision = ref_id
  526. heads[name] = b
  527. for name, ref_id in all_refs.iteritems():
  528. if name.startswith(R_PUB):
  529. name = name[len(R_PUB):]
  530. b = heads.get(name)
  531. if b:
  532. b.published = ref_id
  533. return heads
  534. def MatchesGroups(self, manifest_groups):
  535. """Returns true if the manifest groups specified at init should cause
  536. this project to be synced.
  537. Prefixing a manifest group with "-" inverts the meaning of a group.
  538. All projects are implicitly labelled with "all".
  539. labels are resolved in order. In the example case of
  540. project_groups: "all,group1,group2"
  541. manifest_groups: "-group1,group2"
  542. the project will be matched.
  543. """
  544. expanded_manifest_groups = manifest_groups or ['all', '-notdefault']
  545. expanded_project_groups = ['all'] + (self.groups or [])
  546. matched = False
  547. for group in expanded_manifest_groups:
  548. if group.startswith('-') and group[1:] in expanded_project_groups:
  549. matched = False
  550. elif group in expanded_project_groups:
  551. matched = True
  552. return matched
  553. ## Status Display ##
  554. def HasChanges(self):
  555. """Returns true if there are uncommitted changes.
  556. """
  557. self.work_git.update_index('-q',
  558. '--unmerged',
  559. '--ignore-missing',
  560. '--refresh')
  561. if self.IsRebaseInProgress():
  562. return True
  563. if self.work_git.DiffZ('diff-index', '--cached', HEAD):
  564. return True
  565. if self.work_git.DiffZ('diff-files'):
  566. return True
  567. if self.work_git.LsOthers():
  568. return True
  569. return False
  570. def PrintWorkTreeStatus(self, output_redir=None):
  571. """Prints the status of the repository to stdout.
  572. Args:
  573. output: If specified, redirect the output to this object.
  574. """
  575. if not os.path.isdir(self.worktree):
  576. if output_redir == None:
  577. output_redir = sys.stdout
  578. print(file=output_redir)
  579. print('project %s/' % self.relpath, file=output_redir)
  580. print(' missing (run "repo sync")', file=output_redir)
  581. return
  582. self.work_git.update_index('-q',
  583. '--unmerged',
  584. '--ignore-missing',
  585. '--refresh')
  586. rb = self.IsRebaseInProgress()
  587. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  588. df = self.work_git.DiffZ('diff-files')
  589. do = self.work_git.LsOthers()
  590. if not rb and not di and not df and not do and not self.CurrentBranch:
  591. return 'CLEAN'
  592. out = StatusColoring(self.config)
  593. if not output_redir == None:
  594. out.redirect(output_redir)
  595. out.project('project %-40s', self.relpath + '/')
  596. branch = self.CurrentBranch
  597. if branch is None:
  598. out.nobranch('(*** NO BRANCH ***)')
  599. else:
  600. out.branch('branch %s', branch)
  601. out.nl()
  602. if rb:
  603. out.important('prior sync failed; rebase still in progress')
  604. out.nl()
  605. paths = list()
  606. paths.extend(di.keys())
  607. paths.extend(df.keys())
  608. paths.extend(do)
  609. paths = list(set(paths))
  610. paths.sort()
  611. for p in paths:
  612. try:
  613. i = di[p]
  614. except KeyError:
  615. i = None
  616. try:
  617. f = df[p]
  618. except KeyError:
  619. f = None
  620. if i:
  621. i_status = i.status.upper()
  622. else:
  623. i_status = '-'
  624. if f:
  625. f_status = f.status.lower()
  626. else:
  627. f_status = '-'
  628. if i and i.src_path:
  629. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  630. i.src_path, p, i.level)
  631. else:
  632. line = ' %s%s\t%s' % (i_status, f_status, p)
  633. if i and not f:
  634. out.added('%s', line)
  635. elif (i and f) or (not i and f):
  636. out.changed('%s', line)
  637. elif not i and not f:
  638. out.untracked('%s', line)
  639. else:
  640. out.write('%s', line)
  641. out.nl()
  642. return 'DIRTY'
  643. def PrintWorkTreeDiff(self, absolute_paths=False):
  644. """Prints the status of the repository to stdout.
  645. """
  646. out = DiffColoring(self.config)
  647. cmd = ['diff']
  648. if out.is_on:
  649. cmd.append('--color')
  650. cmd.append(HEAD)
  651. if absolute_paths:
  652. cmd.append('--src-prefix=a/%s/' % self.relpath)
  653. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  654. cmd.append('--')
  655. p = GitCommand(self,
  656. cmd,
  657. capture_stdout = True,
  658. capture_stderr = True)
  659. has_diff = False
  660. for line in p.process.stdout:
  661. if not has_diff:
  662. out.nl()
  663. out.project('project %s/' % self.relpath)
  664. out.nl()
  665. has_diff = True
  666. print(line[:-1])
  667. p.Wait()
  668. ## Publish / Upload ##
  669. def WasPublished(self, branch, all_refs=None):
  670. """Was the branch published (uploaded) for code review?
  671. If so, returns the SHA-1 hash of the last published
  672. state for the branch.
  673. """
  674. key = R_PUB + branch
  675. if all_refs is None:
  676. try:
  677. return self.bare_git.rev_parse(key)
  678. except GitError:
  679. return None
  680. else:
  681. try:
  682. return all_refs[key]
  683. except KeyError:
  684. return None
  685. def CleanPublishedCache(self, all_refs=None):
  686. """Prunes any stale published refs.
  687. """
  688. if all_refs is None:
  689. all_refs = self._allrefs
  690. heads = set()
  691. canrm = {}
  692. for name, ref_id in all_refs.iteritems():
  693. if name.startswith(R_HEADS):
  694. heads.add(name)
  695. elif name.startswith(R_PUB):
  696. canrm[name] = ref_id
  697. for name, ref_id in canrm.iteritems():
  698. n = name[len(R_PUB):]
  699. if R_HEADS + n not in heads:
  700. self.bare_git.DeleteRef(name, ref_id)
  701. def GetUploadableBranches(self, selected_branch=None):
  702. """List any branches which can be uploaded for review.
  703. """
  704. heads = {}
  705. pubed = {}
  706. for name, ref_id in self._allrefs.iteritems():
  707. if name.startswith(R_HEADS):
  708. heads[name[len(R_HEADS):]] = ref_id
  709. elif name.startswith(R_PUB):
  710. pubed[name[len(R_PUB):]] = ref_id
  711. ready = []
  712. for branch, ref_id in heads.iteritems():
  713. if branch in pubed and pubed[branch] == ref_id:
  714. continue
  715. if selected_branch and branch != selected_branch:
  716. continue
  717. rb = self.GetUploadableBranch(branch)
  718. if rb:
  719. ready.append(rb)
  720. return ready
  721. def GetUploadableBranch(self, branch_name):
  722. """Get a single uploadable branch, or None.
  723. """
  724. branch = self.GetBranch(branch_name)
  725. base = branch.LocalMerge
  726. if branch.LocalMerge:
  727. rb = ReviewableBranch(self, branch, base)
  728. if rb.commits:
  729. return rb
  730. return None
  731. def UploadForReview(self, branch=None,
  732. people=([],[]),
  733. auto_topic=False,
  734. draft=False):
  735. """Uploads the named branch for code review.
  736. """
  737. if branch is None:
  738. branch = self.CurrentBranch
  739. if branch is None:
  740. raise GitError('not currently on a branch')
  741. branch = self.GetBranch(branch)
  742. if not branch.LocalMerge:
  743. raise GitError('branch %s does not track a remote' % branch.name)
  744. if not branch.remote.review:
  745. raise GitError('remote %s has no review url' % branch.remote.name)
  746. dest_branch = branch.merge
  747. if not dest_branch.startswith(R_HEADS):
  748. dest_branch = R_HEADS + dest_branch
  749. if not branch.remote.projectname:
  750. branch.remote.projectname = self.name
  751. branch.remote.Save()
  752. url = branch.remote.ReviewUrl(self.UserEmail)
  753. if url is None:
  754. raise UploadError('review not configured')
  755. cmd = ['push']
  756. if url.startswith('ssh://'):
  757. rp = ['gerrit receive-pack']
  758. for e in people[0]:
  759. rp.append('--reviewer=%s' % sq(e))
  760. for e in people[1]:
  761. rp.append('--cc=%s' % sq(e))
  762. cmd.append('--receive-pack=%s' % " ".join(rp))
  763. cmd.append(url)
  764. if dest_branch.startswith(R_HEADS):
  765. dest_branch = dest_branch[len(R_HEADS):]
  766. upload_type = 'for'
  767. if draft:
  768. upload_type = 'drafts'
  769. ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
  770. dest_branch)
  771. if auto_topic:
  772. ref_spec = ref_spec + '/' + branch.name
  773. cmd.append(ref_spec)
  774. if GitCommand(self, cmd, bare = True).Wait() != 0:
  775. raise UploadError('Upload failed')
  776. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  777. self.bare_git.UpdateRef(R_PUB + branch.name,
  778. R_HEADS + branch.name,
  779. message = msg)
  780. ## Sync ##
  781. def Sync_NetworkHalf(self,
  782. quiet=False,
  783. is_new=None,
  784. current_branch_only=False,
  785. clone_bundle=True):
  786. """Perform only the network IO portion of the sync process.
  787. Local working directory/branch state is not affected.
  788. """
  789. if is_new is None:
  790. is_new = not self.Exists
  791. if is_new:
  792. self._InitGitDir()
  793. self._InitRemote()
  794. if is_new:
  795. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  796. try:
  797. fd = open(alt, 'rb')
  798. try:
  799. alt_dir = fd.readline().rstrip()
  800. finally:
  801. fd.close()
  802. except IOError:
  803. alt_dir = None
  804. else:
  805. alt_dir = None
  806. if clone_bundle \
  807. and alt_dir is None \
  808. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  809. is_new = False
  810. if not current_branch_only:
  811. if self.sync_c:
  812. current_branch_only = True
  813. elif not self.manifest._loaded:
  814. # Manifest cannot check defaults until it syncs.
  815. current_branch_only = False
  816. elif self.manifest.default.sync_c:
  817. current_branch_only = True
  818. if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  819. current_branch_only=current_branch_only):
  820. return False
  821. if self.worktree:
  822. self._InitMRef()
  823. else:
  824. self._InitMirrorHead()
  825. try:
  826. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  827. except OSError:
  828. pass
  829. return True
  830. def PostRepoUpgrade(self):
  831. self._InitHooks()
  832. def _CopyFiles(self):
  833. for copyfile in self.copyfiles:
  834. copyfile._Copy()
  835. def GetRevisionId(self, all_refs=None):
  836. if self.revisionId:
  837. return self.revisionId
  838. rem = self.GetRemote(self.remote.name)
  839. rev = rem.ToLocal(self.revisionExpr)
  840. if all_refs is not None and rev in all_refs:
  841. return all_refs[rev]
  842. try:
  843. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  844. except GitError:
  845. raise ManifestInvalidRevisionError(
  846. 'revision %s in %s not found' % (self.revisionExpr,
  847. self.name))
  848. def Sync_LocalHalf(self, syncbuf):
  849. """Perform only the local IO portion of the sync process.
  850. Network access is not required.
  851. """
  852. all_refs = self.bare_ref.all
  853. self.CleanPublishedCache(all_refs)
  854. revid = self.GetRevisionId(all_refs)
  855. def _doff():
  856. self._FastForward(revid)
  857. self._CopyFiles()
  858. self._InitWorkTree()
  859. head = self.work_git.GetHead()
  860. if head.startswith(R_HEADS):
  861. branch = head[len(R_HEADS):]
  862. try:
  863. head = all_refs[head]
  864. except KeyError:
  865. head = None
  866. else:
  867. branch = None
  868. if branch is None or syncbuf.detach_head:
  869. # Currently on a detached HEAD. The user is assumed to
  870. # not have any local modifications worth worrying about.
  871. #
  872. if self.IsRebaseInProgress():
  873. syncbuf.fail(self, _PriorSyncFailedError())
  874. return
  875. if head == revid:
  876. # No changes; don't do anything further.
  877. # Except if the head needs to be detached
  878. #
  879. if not syncbuf.detach_head:
  880. return
  881. else:
  882. lost = self._revlist(not_rev(revid), HEAD)
  883. if lost:
  884. syncbuf.info(self, "discarding %d commits", len(lost))
  885. try:
  886. self._Checkout(revid, quiet=True)
  887. except GitError as e:
  888. syncbuf.fail(self, e)
  889. return
  890. self._CopyFiles()
  891. return
  892. if head == revid:
  893. # No changes; don't do anything further.
  894. #
  895. return
  896. branch = self.GetBranch(branch)
  897. if not branch.LocalMerge:
  898. # The current branch has no tracking configuration.
  899. # Jump off it to a detached HEAD.
  900. #
  901. syncbuf.info(self,
  902. "leaving %s; does not track upstream",
  903. branch.name)
  904. try:
  905. self._Checkout(revid, quiet=True)
  906. except GitError as e:
  907. syncbuf.fail(self, e)
  908. return
  909. self._CopyFiles()
  910. return
  911. upstream_gain = self._revlist(not_rev(HEAD), revid)
  912. pub = self.WasPublished(branch.name, all_refs)
  913. if pub:
  914. not_merged = self._revlist(not_rev(revid), pub)
  915. if not_merged:
  916. if upstream_gain:
  917. # The user has published this branch and some of those
  918. # commits are not yet merged upstream. We do not want
  919. # to rewrite the published commits so we punt.
  920. #
  921. syncbuf.fail(self,
  922. "branch %s is published (but not merged) and is now %d commits behind"
  923. % (branch.name, len(upstream_gain)))
  924. return
  925. elif pub == head:
  926. # All published commits are merged, and thus we are a
  927. # strict subset. We can fast-forward safely.
  928. #
  929. syncbuf.later1(self, _doff)
  930. return
  931. # Examine the local commits not in the remote. Find the
  932. # last one attributed to this user, if any.
  933. #
  934. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  935. last_mine = None
  936. cnt_mine = 0
  937. for commit in local_changes:
  938. commit_id, committer_email = commit.split(' ', 1)
  939. if committer_email == self.UserEmail:
  940. last_mine = commit_id
  941. cnt_mine += 1
  942. if not upstream_gain and cnt_mine == len(local_changes):
  943. return
  944. if self.IsDirty(consider_untracked=False):
  945. syncbuf.fail(self, _DirtyError())
  946. return
  947. # If the upstream switched on us, warn the user.
  948. #
  949. if branch.merge != self.revisionExpr:
  950. if branch.merge and self.revisionExpr:
  951. syncbuf.info(self,
  952. 'manifest switched %s...%s',
  953. branch.merge,
  954. self.revisionExpr)
  955. elif branch.merge:
  956. syncbuf.info(self,
  957. 'manifest no longer tracks %s',
  958. branch.merge)
  959. if cnt_mine < len(local_changes):
  960. # Upstream rebased. Not everything in HEAD
  961. # was created by this user.
  962. #
  963. syncbuf.info(self,
  964. "discarding %d commits removed from upstream",
  965. len(local_changes) - cnt_mine)
  966. branch.remote = self.GetRemote(self.remote.name)
  967. if not ID_RE.match(self.revisionExpr):
  968. # in case of manifest sync the revisionExpr might be a SHA1
  969. branch.merge = self.revisionExpr
  970. branch.Save()
  971. if cnt_mine > 0 and self.rebase:
  972. def _dorebase():
  973. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  974. self._CopyFiles()
  975. syncbuf.later2(self, _dorebase)
  976. elif local_changes:
  977. try:
  978. self._ResetHard(revid)
  979. self._CopyFiles()
  980. except GitError as e:
  981. syncbuf.fail(self, e)
  982. return
  983. else:
  984. syncbuf.later1(self, _doff)
  985. def AddCopyFile(self, src, dest, absdest):
  986. # dest should already be an absolute path, but src is project relative
  987. # make src an absolute path
  988. abssrc = os.path.join(self.worktree, src)
  989. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  990. def AddAnnotation(self, name, value, keep):
  991. self.annotations.append(_Annotation(name, value, keep))
  992. def DownloadPatchSet(self, change_id, patch_id):
  993. """Download a single patch set of a single change to FETCH_HEAD.
  994. """
  995. remote = self.GetRemote(self.remote.name)
  996. cmd = ['fetch', remote.name]
  997. cmd.append('refs/changes/%2.2d/%d/%d' \
  998. % (change_id % 100, change_id, patch_id))
  999. cmd.extend(map(str, remote.fetch))
  1000. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1001. return None
  1002. return DownloadedChange(self,
  1003. self.GetRevisionId(),
  1004. change_id,
  1005. patch_id,
  1006. self.bare_git.rev_parse('FETCH_HEAD'))
  1007. ## Branch Management ##
  1008. def StartBranch(self, name):
  1009. """Create a new branch off the manifest's revision.
  1010. """
  1011. head = self.work_git.GetHead()
  1012. if head == (R_HEADS + name):
  1013. return True
  1014. all_refs = self.bare_ref.all
  1015. if (R_HEADS + name) in all_refs:
  1016. return GitCommand(self,
  1017. ['checkout', name, '--'],
  1018. capture_stdout = True,
  1019. capture_stderr = True).Wait() == 0
  1020. branch = self.GetBranch(name)
  1021. branch.remote = self.GetRemote(self.remote.name)
  1022. branch.merge = self.revisionExpr
  1023. revid = self.GetRevisionId(all_refs)
  1024. if head.startswith(R_HEADS):
  1025. try:
  1026. head = all_refs[head]
  1027. except KeyError:
  1028. head = None
  1029. if revid and head and revid == head:
  1030. ref = os.path.join(self.gitdir, R_HEADS + name)
  1031. try:
  1032. os.makedirs(os.path.dirname(ref))
  1033. except OSError:
  1034. pass
  1035. _lwrite(ref, '%s\n' % revid)
  1036. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1037. 'ref: %s%s\n' % (R_HEADS, name))
  1038. branch.Save()
  1039. return True
  1040. if GitCommand(self,
  1041. ['checkout', '-b', branch.name, revid],
  1042. capture_stdout = True,
  1043. capture_stderr = True).Wait() == 0:
  1044. branch.Save()
  1045. return True
  1046. return False
  1047. def CheckoutBranch(self, name):
  1048. """Checkout a local topic branch.
  1049. Args:
  1050. name: The name of the branch to checkout.
  1051. Returns:
  1052. True if the checkout succeeded; False if it didn't; None if the branch
  1053. didn't exist.
  1054. """
  1055. rev = R_HEADS + name
  1056. head = self.work_git.GetHead()
  1057. if head == rev:
  1058. # Already on the branch
  1059. #
  1060. return True
  1061. all_refs = self.bare_ref.all
  1062. try:
  1063. revid = all_refs[rev]
  1064. except KeyError:
  1065. # Branch does not exist in this project
  1066. #
  1067. return None
  1068. if head.startswith(R_HEADS):
  1069. try:
  1070. head = all_refs[head]
  1071. except KeyError:
  1072. head = None
  1073. if head == revid:
  1074. # Same revision; just update HEAD to point to the new
  1075. # target branch, but otherwise take no other action.
  1076. #
  1077. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1078. 'ref: %s%s\n' % (R_HEADS, name))
  1079. return True
  1080. return GitCommand(self,
  1081. ['checkout', name, '--'],
  1082. capture_stdout = True,
  1083. capture_stderr = True).Wait() == 0
  1084. def AbandonBranch(self, name):
  1085. """Destroy a local topic branch.
  1086. Args:
  1087. name: The name of the branch to abandon.
  1088. Returns:
  1089. True if the abandon succeeded; False if it didn't; None if the branch
  1090. didn't exist.
  1091. """
  1092. rev = R_HEADS + name
  1093. all_refs = self.bare_ref.all
  1094. if rev not in all_refs:
  1095. # Doesn't exist
  1096. return None
  1097. head = self.work_git.GetHead()
  1098. if head == rev:
  1099. # We can't destroy the branch while we are sitting
  1100. # on it. Switch to a detached HEAD.
  1101. #
  1102. head = all_refs[head]
  1103. revid = self.GetRevisionId(all_refs)
  1104. if head == revid:
  1105. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1106. '%s\n' % revid)
  1107. else:
  1108. self._Checkout(revid, quiet=True)
  1109. return GitCommand(self,
  1110. ['branch', '-D', name],
  1111. capture_stdout = True,
  1112. capture_stderr = True).Wait() == 0
  1113. def PruneHeads(self):
  1114. """Prune any topic branches already merged into upstream.
  1115. """
  1116. cb = self.CurrentBranch
  1117. kill = []
  1118. left = self._allrefs
  1119. for name in left.keys():
  1120. if name.startswith(R_HEADS):
  1121. name = name[len(R_HEADS):]
  1122. if cb is None or name != cb:
  1123. kill.append(name)
  1124. rev = self.GetRevisionId(left)
  1125. if cb is not None \
  1126. and not self._revlist(HEAD + '...' + rev) \
  1127. and not self.IsDirty(consider_untracked = False):
  1128. self.work_git.DetachHead(HEAD)
  1129. kill.append(cb)
  1130. if kill:
  1131. old = self.bare_git.GetHead()
  1132. if old is None:
  1133. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1134. try:
  1135. self.bare_git.DetachHead(rev)
  1136. b = ['branch', '-d']
  1137. b.extend(kill)
  1138. b = GitCommand(self, b, bare=True,
  1139. capture_stdout=True,
  1140. capture_stderr=True)
  1141. b.Wait()
  1142. finally:
  1143. self.bare_git.SetHead(old)
  1144. left = self._allrefs
  1145. for branch in kill:
  1146. if (R_HEADS + branch) not in left:
  1147. self.CleanPublishedCache()
  1148. break
  1149. if cb and cb not in kill:
  1150. kill.append(cb)
  1151. kill.sort()
  1152. kept = []
  1153. for branch in kill:
  1154. if (R_HEADS + branch) in left:
  1155. branch = self.GetBranch(branch)
  1156. base = branch.LocalMerge
  1157. if not base:
  1158. base = rev
  1159. kept.append(ReviewableBranch(self, branch, base))
  1160. return kept
  1161. ## Direct Git Commands ##
  1162. def _RemoteFetch(self, name=None,
  1163. current_branch_only=False,
  1164. initial=False,
  1165. quiet=False,
  1166. alt_dir=None):
  1167. is_sha1 = False
  1168. tag_name = None
  1169. def CheckForSha1():
  1170. try:
  1171. # if revision (sha or tag) is not present then following function
  1172. # throws an error.
  1173. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1174. return True
  1175. except GitError:
  1176. # There is no such persistent revision. We have to fetch it.
  1177. return False
  1178. if current_branch_only:
  1179. if ID_RE.match(self.revisionExpr) is not None:
  1180. is_sha1 = True
  1181. elif self.revisionExpr.startswith(R_TAGS):
  1182. # this is a tag and its sha1 value should never change
  1183. tag_name = self.revisionExpr[len(R_TAGS):]
  1184. if is_sha1 or tag_name is not None:
  1185. if CheckForSha1():
  1186. return True
  1187. if is_sha1 and (not self.upstream or ID_RE.match(self.upstream)):
  1188. current_branch_only = False
  1189. if not name:
  1190. name = self.remote.name
  1191. ssh_proxy = False
  1192. remote = self.GetRemote(name)
  1193. if remote.PreConnectFetch():
  1194. ssh_proxy = True
  1195. if initial:
  1196. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1197. ref_dir = os.path.dirname(alt_dir)
  1198. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1199. remote = self.GetRemote(name)
  1200. all_refs = self.bare_ref.all
  1201. ids = set(all_refs.values())
  1202. tmp = set()
  1203. for r, ref_id in GitRefs(ref_dir).all.iteritems():
  1204. if r not in all_refs:
  1205. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1206. all_refs[r] = ref_id
  1207. ids.add(ref_id)
  1208. continue
  1209. if ref_id in ids:
  1210. continue
  1211. r = 'refs/_alt/%s' % ref_id
  1212. all_refs[r] = ref_id
  1213. ids.add(ref_id)
  1214. tmp.add(r)
  1215. ref_names = list(all_refs.keys())
  1216. ref_names.sort()
  1217. tmp_packed = ''
  1218. old_packed = ''
  1219. for r in ref_names:
  1220. line = '%s %s\n' % (all_refs[r], r)
  1221. tmp_packed += line
  1222. if r not in tmp:
  1223. old_packed += line
  1224. _lwrite(packed_refs, tmp_packed)
  1225. else:
  1226. alt_dir = None
  1227. cmd = ['fetch']
  1228. # The --depth option only affects the initial fetch; after that we'll do
  1229. # full fetches of changes.
  1230. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1231. if depth and initial:
  1232. cmd.append('--depth=%s' % depth)
  1233. if quiet:
  1234. cmd.append('--quiet')
  1235. if not self.worktree:
  1236. cmd.append('--update-head-ok')
  1237. cmd.append(name)
  1238. if not current_branch_only:
  1239. # Fetch whole repo
  1240. cmd.append('--tags')
  1241. cmd.append((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*'))
  1242. elif tag_name is not None:
  1243. cmd.append('tag')
  1244. cmd.append(tag_name)
  1245. else:
  1246. branch = self.revisionExpr
  1247. if is_sha1:
  1248. branch = self.upstream
  1249. if branch.startswith(R_HEADS):
  1250. branch = branch[len(R_HEADS):]
  1251. cmd.append((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch))
  1252. ok = False
  1253. for _i in range(2):
  1254. ret = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait()
  1255. if ret == 0:
  1256. ok = True
  1257. break
  1258. elif current_branch_only and is_sha1 and ret == 128:
  1259. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1260. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1261. # abort the optimization attempt and do a full sync.
  1262. break
  1263. time.sleep(random.randint(30, 45))
  1264. if initial:
  1265. if alt_dir:
  1266. if old_packed != '':
  1267. _lwrite(packed_refs, old_packed)
  1268. else:
  1269. os.remove(packed_refs)
  1270. self.bare_git.pack_refs('--all', '--prune')
  1271. if is_sha1 and current_branch_only and self.upstream:
  1272. # We just synced the upstream given branch; verify we
  1273. # got what we wanted, else trigger a second run of all
  1274. # refs.
  1275. if not CheckForSha1():
  1276. return self._RemoteFetch(name=name, current_branch_only=False,
  1277. initial=False, quiet=quiet, alt_dir=alt_dir)
  1278. return ok
  1279. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1280. if initial and self.manifest.manifestProject.config.GetString('repo.depth'):
  1281. return False
  1282. remote = self.GetRemote(self.remote.name)
  1283. bundle_url = remote.url + '/clone.bundle'
  1284. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1285. if GetSchemeFromUrl(bundle_url) in ('persistent-http', 'persistent-https'):
  1286. bundle_url = bundle_url[len('persistent-'):]
  1287. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1288. return False
  1289. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1290. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1291. exist_dst = os.path.exists(bundle_dst)
  1292. exist_tmp = os.path.exists(bundle_tmp)
  1293. if not initial and not exist_dst and not exist_tmp:
  1294. return False
  1295. if not exist_dst:
  1296. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1297. if not exist_dst:
  1298. return False
  1299. cmd = ['fetch']
  1300. if quiet:
  1301. cmd.append('--quiet')
  1302. if not self.worktree:
  1303. cmd.append('--update-head-ok')
  1304. cmd.append(bundle_dst)
  1305. for f in remote.fetch:
  1306. cmd.append(str(f))
  1307. cmd.append('refs/tags/*:refs/tags/*')
  1308. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1309. if os.path.exists(bundle_dst):
  1310. os.remove(bundle_dst)
  1311. if os.path.exists(bundle_tmp):
  1312. os.remove(bundle_tmp)
  1313. return ok
  1314. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1315. if os.path.exists(dstPath):
  1316. os.remove(dstPath)
  1317. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1318. if quiet:
  1319. cmd += ['--silent']
  1320. if os.path.exists(tmpPath):
  1321. size = os.stat(tmpPath).st_size
  1322. if size >= 1024:
  1323. cmd += ['--continue-at', '%d' % (size,)]
  1324. else:
  1325. os.remove(tmpPath)
  1326. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1327. cmd += ['--proxy', os.environ['http_proxy']]
  1328. cmd += [srcUrl]
  1329. if IsTrace():
  1330. Trace('%s', ' '.join(cmd))
  1331. try:
  1332. proc = subprocess.Popen(cmd)
  1333. except OSError:
  1334. return False
  1335. curlret = proc.wait()
  1336. if curlret == 22:
  1337. # From curl man page:
  1338. # 22: HTTP page not retrieved. The requested url was not found or
  1339. # returned another error with the HTTP error code being 400 or above.
  1340. # This return code only appears if -f, --fail is used.
  1341. if not quiet:
  1342. print("Server does not provide clone.bundle; ignoring.",
  1343. file=sys.stderr)
  1344. return False
  1345. if os.path.exists(tmpPath):
  1346. if curlret == 0 and os.stat(tmpPath).st_size > 16:
  1347. os.rename(tmpPath, dstPath)
  1348. return True
  1349. else:
  1350. os.remove(tmpPath)
  1351. return False
  1352. else:
  1353. return False
  1354. def _Checkout(self, rev, quiet=False):
  1355. cmd = ['checkout']
  1356. if quiet:
  1357. cmd.append('-q')
  1358. cmd.append(rev)
  1359. cmd.append('--')
  1360. if GitCommand(self, cmd).Wait() != 0:
  1361. if self._allrefs:
  1362. raise GitError('%s checkout %s ' % (self.name, rev))
  1363. def _CherryPick(self, rev, quiet=False):
  1364. cmd = ['cherry-pick']
  1365. cmd.append(rev)
  1366. cmd.append('--')
  1367. if GitCommand(self, cmd).Wait() != 0:
  1368. if self._allrefs:
  1369. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1370. def _Revert(self, rev, quiet=False):
  1371. cmd = ['revert']
  1372. cmd.append('--no-edit')
  1373. cmd.append(rev)
  1374. cmd.append('--')
  1375. if GitCommand(self, cmd).Wait() != 0:
  1376. if self._allrefs:
  1377. raise GitError('%s revert %s ' % (self.name, rev))
  1378. def _ResetHard(self, rev, quiet=True):
  1379. cmd = ['reset', '--hard']
  1380. if quiet:
  1381. cmd.append('-q')
  1382. cmd.append(rev)
  1383. if GitCommand(self, cmd).Wait() != 0:
  1384. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1385. def _Rebase(self, upstream, onto = None):
  1386. cmd = ['rebase']
  1387. if onto is not None:
  1388. cmd.extend(['--onto', onto])
  1389. cmd.append(upstream)
  1390. if GitCommand(self, cmd).Wait() != 0:
  1391. raise GitError('%s rebase %s ' % (self.name, upstream))
  1392. def _FastForward(self, head, ffonly=False):
  1393. cmd = ['merge', head]
  1394. if ffonly:
  1395. cmd.append("--ff-only")
  1396. if GitCommand(self, cmd).Wait() != 0:
  1397. raise GitError('%s merge %s ' % (self.name, head))
  1398. def _InitGitDir(self):
  1399. if not os.path.exists(self.gitdir):
  1400. os.makedirs(self.gitdir)
  1401. self.bare_git.init()
  1402. mp = self.manifest.manifestProject
  1403. ref_dir = mp.config.GetString('repo.reference')
  1404. if ref_dir:
  1405. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1406. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1407. self.relpath + '.git')
  1408. if os.path.exists(mirror_git):
  1409. ref_dir = mirror_git
  1410. elif os.path.exists(repo_git):
  1411. ref_dir = repo_git
  1412. else:
  1413. ref_dir = None
  1414. if ref_dir:
  1415. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1416. os.path.join(ref_dir, 'objects') + '\n')
  1417. if self.manifest.IsMirror:
  1418. self.config.SetString('core.bare', 'true')
  1419. else:
  1420. self.config.SetString('core.bare', None)
  1421. hooks = self._gitdir_path('hooks')
  1422. try:
  1423. to_rm = os.listdir(hooks)
  1424. except OSError:
  1425. to_rm = []
  1426. for old_hook in to_rm:
  1427. os.remove(os.path.join(hooks, old_hook))
  1428. self._InitHooks()
  1429. m = self.manifest.manifestProject.config
  1430. for key in ['user.name', 'user.email']:
  1431. if m.Has(key, include_defaults = False):
  1432. self.config.SetString(key, m.GetString(key))
  1433. def _InitHooks(self):
  1434. hooks = self._gitdir_path('hooks')
  1435. if not os.path.exists(hooks):
  1436. os.makedirs(hooks)
  1437. for stock_hook in _ProjectHooks():
  1438. name = os.path.basename(stock_hook)
  1439. if name in ('commit-msg',) and not self.remote.review \
  1440. and not self is self.manifest.manifestProject:
  1441. # Don't install a Gerrit Code Review hook if this
  1442. # project does not appear to use it for reviews.
  1443. #
  1444. # Since the manifest project is one of those, but also
  1445. # managed through gerrit, it's excluded
  1446. continue
  1447. dst = os.path.join(hooks, name)
  1448. if os.path.islink(dst):
  1449. continue
  1450. if os.path.exists(dst):
  1451. if filecmp.cmp(stock_hook, dst, shallow=False):
  1452. os.remove(dst)
  1453. else:
  1454. _error("%s: Not replacing %s hook", self.relpath, name)
  1455. continue
  1456. try:
  1457. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1458. except OSError as e:
  1459. if e.errno == errno.EPERM:
  1460. raise GitError('filesystem must support symlinks')
  1461. else:
  1462. raise
  1463. def _InitRemote(self):
  1464. if self.remote.url:
  1465. remote = self.GetRemote(self.remote.name)
  1466. remote.url = self.remote.url
  1467. remote.review = self.remote.review
  1468. remote.projectname = self.name
  1469. if self.worktree:
  1470. remote.ResetFetch(mirror=False)
  1471. else:
  1472. remote.ResetFetch(mirror=True)
  1473. remote.Save()
  1474. def _InitMRef(self):
  1475. if self.manifest.branch:
  1476. self._InitAnyMRef(R_M + self.manifest.branch)
  1477. def _InitMirrorHead(self):
  1478. self._InitAnyMRef(HEAD)
  1479. def _InitAnyMRef(self, ref):
  1480. cur = self.bare_ref.symref(ref)
  1481. if self.revisionId:
  1482. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1483. msg = 'manifest set to %s' % self.revisionId
  1484. dst = self.revisionId + '^0'
  1485. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1486. else:
  1487. remote = self.GetRemote(self.remote.name)
  1488. dst = remote.ToLocal(self.revisionExpr)
  1489. if cur != dst:
  1490. msg = 'manifest set to %s' % self.revisionExpr
  1491. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1492. def _InitWorkTree(self):
  1493. dotgit = os.path.join(self.worktree, '.git')
  1494. if not os.path.exists(dotgit):
  1495. os.makedirs(dotgit)
  1496. for name in ['config',
  1497. 'description',
  1498. 'hooks',
  1499. 'info',
  1500. 'logs',
  1501. 'objects',
  1502. 'packed-refs',
  1503. 'refs',
  1504. 'rr-cache',
  1505. 'svn']:
  1506. try:
  1507. src = os.path.join(self.gitdir, name)
  1508. dst = os.path.join(dotgit, name)
  1509. if os.path.islink(dst) or not os.path.exists(dst):
  1510. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  1511. else:
  1512. raise GitError('cannot overwrite a local work tree')
  1513. except OSError as e:
  1514. if e.errno == errno.EPERM:
  1515. raise GitError('filesystem must support symlinks')
  1516. else:
  1517. raise
  1518. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1519. cmd = ['read-tree', '--reset', '-u']
  1520. cmd.append('-v')
  1521. cmd.append(HEAD)
  1522. if GitCommand(self, cmd).Wait() != 0:
  1523. raise GitError("cannot initialize work tree")
  1524. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1525. if not os.path.exists(rr_cache):
  1526. os.makedirs(rr_cache)
  1527. self._CopyFiles()
  1528. def _gitdir_path(self, path):
  1529. return os.path.join(self.gitdir, path)
  1530. def _revlist(self, *args, **kw):
  1531. a = []
  1532. a.extend(args)
  1533. a.append('--')
  1534. return self.work_git.rev_list(*a, **kw)
  1535. @property
  1536. def _allrefs(self):
  1537. return self.bare_ref.all
  1538. class _GitGetByExec(object):
  1539. def __init__(self, project, bare):
  1540. self._project = project
  1541. self._bare = bare
  1542. def LsOthers(self):
  1543. p = GitCommand(self._project,
  1544. ['ls-files',
  1545. '-z',
  1546. '--others',
  1547. '--exclude-standard'],
  1548. bare = False,
  1549. capture_stdout = True,
  1550. capture_stderr = True)
  1551. if p.Wait() == 0:
  1552. out = p.stdout
  1553. if out:
  1554. return out[:-1].split('\0') # pylint: disable=W1401
  1555. # Backslash is not anomalous
  1556. return []
  1557. def DiffZ(self, name, *args):
  1558. cmd = [name]
  1559. cmd.append('-z')
  1560. cmd.extend(args)
  1561. p = GitCommand(self._project,
  1562. cmd,
  1563. bare = False,
  1564. capture_stdout = True,
  1565. capture_stderr = True)
  1566. try:
  1567. out = p.process.stdout.read()
  1568. r = {}
  1569. if out:
  1570. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  1571. while out:
  1572. try:
  1573. info = out.next()
  1574. path = out.next()
  1575. except StopIteration:
  1576. break
  1577. class _Info(object):
  1578. def __init__(self, path, omode, nmode, oid, nid, state):
  1579. self.path = path
  1580. self.src_path = None
  1581. self.old_mode = omode
  1582. self.new_mode = nmode
  1583. self.old_id = oid
  1584. self.new_id = nid
  1585. if len(state) == 1:
  1586. self.status = state
  1587. self.level = None
  1588. else:
  1589. self.status = state[:1]
  1590. self.level = state[1:]
  1591. while self.level.startswith('0'):
  1592. self.level = self.level[1:]
  1593. info = info[1:].split(' ')
  1594. info = _Info(path, *info)
  1595. if info.status in ('R', 'C'):
  1596. info.src_path = info.path
  1597. info.path = out.next()
  1598. r[info.path] = info
  1599. return r
  1600. finally:
  1601. p.Wait()
  1602. def GetHead(self):
  1603. if self._bare:
  1604. path = os.path.join(self._project.gitdir, HEAD)
  1605. else:
  1606. path = os.path.join(self._project.worktree, '.git', HEAD)
  1607. fd = open(path, 'rb')
  1608. try:
  1609. line = fd.read()
  1610. finally:
  1611. fd.close()
  1612. if line.startswith('ref: '):
  1613. return line[5:-1]
  1614. return line[:-1]
  1615. def SetHead(self, ref, message=None):
  1616. cmdv = []
  1617. if message is not None:
  1618. cmdv.extend(['-m', message])
  1619. cmdv.append(HEAD)
  1620. cmdv.append(ref)
  1621. self.symbolic_ref(*cmdv)
  1622. def DetachHead(self, new, message=None):
  1623. cmdv = ['--no-deref']
  1624. if message is not None:
  1625. cmdv.extend(['-m', message])
  1626. cmdv.append(HEAD)
  1627. cmdv.append(new)
  1628. self.update_ref(*cmdv)
  1629. def UpdateRef(self, name, new, old=None,
  1630. message=None,
  1631. detach=False):
  1632. cmdv = []
  1633. if message is not None:
  1634. cmdv.extend(['-m', message])
  1635. if detach:
  1636. cmdv.append('--no-deref')
  1637. cmdv.append(name)
  1638. cmdv.append(new)
  1639. if old is not None:
  1640. cmdv.append(old)
  1641. self.update_ref(*cmdv)
  1642. def DeleteRef(self, name, old=None):
  1643. if not old:
  1644. old = self.rev_parse(name)
  1645. self.update_ref('-d', name, old)
  1646. self._project.bare_ref.deleted(name)
  1647. def rev_list(self, *args, **kw):
  1648. if 'format' in kw:
  1649. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1650. else:
  1651. cmdv = ['rev-list']
  1652. cmdv.extend(args)
  1653. p = GitCommand(self._project,
  1654. cmdv,
  1655. bare = self._bare,
  1656. capture_stdout = True,
  1657. capture_stderr = True)
  1658. r = []
  1659. for line in p.process.stdout:
  1660. if line[-1] == '\n':
  1661. line = line[:-1]
  1662. r.append(line)
  1663. if p.Wait() != 0:
  1664. raise GitError('%s rev-list %s: %s' % (
  1665. self._project.name,
  1666. str(args),
  1667. p.stderr))
  1668. return r
  1669. def __getattr__(self, name):
  1670. """Allow arbitrary git commands using pythonic syntax.
  1671. This allows you to do things like:
  1672. git_obj.rev_parse('HEAD')
  1673. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1674. run. We'll replace the '_' with a '-' and try to run a git command.
  1675. Any other positional arguments will be passed to the git command, and the
  1676. following keyword arguments are supported:
  1677. config: An optional dict of git config options to be passed with '-c'.
  1678. Args:
  1679. name: The name of the git command to call. Any '_' characters will
  1680. be replaced with '-'.
  1681. Returns:
  1682. A callable object that will try to call git with the named command.
  1683. """
  1684. name = name.replace('_', '-')
  1685. def runner(*args, **kwargs):
  1686. cmdv = []
  1687. config = kwargs.pop('config', None)
  1688. for k in kwargs:
  1689. raise TypeError('%s() got an unexpected keyword argument %r'
  1690. % (name, k))
  1691. if config is not None:
  1692. if not git_require((1, 7, 2)):
  1693. raise ValueError('cannot set config on command line for %s()'
  1694. % name)
  1695. for k, v in config.iteritems():
  1696. cmdv.append('-c')
  1697. cmdv.append('%s=%s' % (k, v))
  1698. cmdv.append(name)
  1699. cmdv.extend(args)
  1700. p = GitCommand(self._project,
  1701. cmdv,
  1702. bare = self._bare,
  1703. capture_stdout = True,
  1704. capture_stderr = True)
  1705. if p.Wait() != 0:
  1706. raise GitError('%s %s: %s' % (
  1707. self._project.name,
  1708. name,
  1709. p.stderr))
  1710. r = p.stdout
  1711. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1712. return r[:-1]
  1713. return r
  1714. return runner
  1715. class _PriorSyncFailedError(Exception):
  1716. def __str__(self):
  1717. return 'prior sync failed; rebase still in progress'
  1718. class _DirtyError(Exception):
  1719. def __str__(self):
  1720. return 'contains uncommitted changes'
  1721. class _InfoMessage(object):
  1722. def __init__(self, project, text):
  1723. self.project = project
  1724. self.text = text
  1725. def Print(self, syncbuf):
  1726. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1727. syncbuf.out.nl()
  1728. class _Failure(object):
  1729. def __init__(self, project, why):
  1730. self.project = project
  1731. self.why = why
  1732. def Print(self, syncbuf):
  1733. syncbuf.out.fail('error: %s/: %s',
  1734. self.project.relpath,
  1735. str(self.why))
  1736. syncbuf.out.nl()
  1737. class _Later(object):
  1738. def __init__(self, project, action):
  1739. self.project = project
  1740. self.action = action
  1741. def Run(self, syncbuf):
  1742. out = syncbuf.out
  1743. out.project('project %s/', self.project.relpath)
  1744. out.nl()
  1745. try:
  1746. self.action()
  1747. out.nl()
  1748. return True
  1749. except GitError:
  1750. out.nl()
  1751. return False
  1752. class _SyncColoring(Coloring):
  1753. def __init__(self, config):
  1754. Coloring.__init__(self, config, 'reposync')
  1755. self.project = self.printer('header', attr = 'bold')
  1756. self.info = self.printer('info')
  1757. self.fail = self.printer('fail', fg='red')
  1758. class SyncBuffer(object):
  1759. def __init__(self, config, detach_head=False):
  1760. self._messages = []
  1761. self._failures = []
  1762. self._later_queue1 = []
  1763. self._later_queue2 = []
  1764. self.out = _SyncColoring(config)
  1765. self.out.redirect(sys.stderr)
  1766. self.detach_head = detach_head
  1767. self.clean = True
  1768. def info(self, project, fmt, *args):
  1769. self._messages.append(_InfoMessage(project, fmt % args))
  1770. def fail(self, project, err=None):
  1771. self._failures.append(_Failure(project, err))
  1772. self.clean = False
  1773. def later1(self, project, what):
  1774. self._later_queue1.append(_Later(project, what))
  1775. def later2(self, project, what):
  1776. self._later_queue2.append(_Later(project, what))
  1777. def Finish(self):
  1778. self._PrintMessages()
  1779. self._RunLater()
  1780. self._PrintMessages()
  1781. return self.clean
  1782. def _RunLater(self):
  1783. for q in ['_later_queue1', '_later_queue2']:
  1784. if not self._RunQueue(q):
  1785. return
  1786. def _RunQueue(self, queue):
  1787. for m in getattr(self, queue):
  1788. if not m.Run(self):
  1789. self.clean = False
  1790. return False
  1791. setattr(self, queue, [])
  1792. return True
  1793. def _PrintMessages(self):
  1794. for m in self._messages:
  1795. m.Print(self)
  1796. for m in self._failures:
  1797. m.Print(self)
  1798. self._messages = []
  1799. self._failures = []
  1800. class MetaProject(Project):
  1801. """A special project housed under .repo.
  1802. """
  1803. def __init__(self, manifest, name, gitdir, worktree):
  1804. Project.__init__(self,
  1805. manifest = manifest,
  1806. name = name,
  1807. gitdir = gitdir,
  1808. worktree = worktree,
  1809. remote = RemoteSpec('origin'),
  1810. relpath = '.repo/%s' % name,
  1811. revisionExpr = 'refs/heads/master',
  1812. revisionId = None,
  1813. groups = None)
  1814. def PreSync(self):
  1815. if self.Exists:
  1816. cb = self.CurrentBranch
  1817. if cb:
  1818. base = self.GetBranch(cb).merge
  1819. if base:
  1820. self.revisionExpr = base
  1821. self.revisionId = None
  1822. def MetaBranchSwitch(self, target):
  1823. """ Prepare MetaProject for manifest branch switch
  1824. """
  1825. # detach and delete manifest branch, allowing a new
  1826. # branch to take over
  1827. syncbuf = SyncBuffer(self.config, detach_head = True)
  1828. self.Sync_LocalHalf(syncbuf)
  1829. syncbuf.Finish()
  1830. return GitCommand(self,
  1831. ['update-ref', '-d', 'refs/heads/default'],
  1832. capture_stdout = True,
  1833. capture_stderr = True).Wait() == 0
  1834. @property
  1835. def LastFetch(self):
  1836. try:
  1837. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  1838. return os.path.getmtime(fh)
  1839. except OSError:
  1840. return 0
  1841. @property
  1842. def HasChanges(self):
  1843. """Has the remote received new commits not yet checked out?
  1844. """
  1845. if not self.remote or not self.revisionExpr:
  1846. return False
  1847. all_refs = self.bare_ref.all
  1848. revid = self.GetRevisionId(all_refs)
  1849. head = self.work_git.GetHead()
  1850. if head.startswith(R_HEADS):
  1851. try:
  1852. head = all_refs[head]
  1853. except KeyError:
  1854. head = None
  1855. if revid == head:
  1856. return False
  1857. elif self._revlist(not_rev(HEAD), revid):
  1858. return True
  1859. return False