project.py 62 KB

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