project.py 64 KB

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