project.py 63 KB

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