project.py 62 KB

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