project.py 64 KB

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