project.py 62 KB

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