project.py 62 KB

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