project.py 71 KB

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