project.py 71 KB

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