project.py 62 KB

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