project.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411
  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. else:
  839. self._UpdateHooks()
  840. self._InitRemote()
  841. if is_new:
  842. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  843. try:
  844. fd = open(alt, 'rb')
  845. try:
  846. alt_dir = fd.readline().rstrip()
  847. finally:
  848. fd.close()
  849. except IOError:
  850. alt_dir = None
  851. else:
  852. alt_dir = None
  853. if clone_bundle \
  854. and alt_dir is None \
  855. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  856. is_new = False
  857. if not current_branch_only:
  858. if self.sync_c:
  859. current_branch_only = True
  860. elif not self.manifest._loaded:
  861. # Manifest cannot check defaults until it syncs.
  862. current_branch_only = False
  863. elif self.manifest.default.sync_c:
  864. current_branch_only = True
  865. if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  866. current_branch_only=current_branch_only,
  867. no_tags=no_tags):
  868. return False
  869. if self.worktree:
  870. self._InitMRef()
  871. else:
  872. self._InitMirrorHead()
  873. try:
  874. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  875. except OSError:
  876. pass
  877. return True
  878. def PostRepoUpgrade(self):
  879. self._InitHooks()
  880. def _CopyFiles(self):
  881. for copyfile in self.copyfiles:
  882. copyfile._Copy()
  883. def GetRevisionId(self, all_refs=None):
  884. if self.revisionId:
  885. return self.revisionId
  886. rem = self.GetRemote(self.remote.name)
  887. rev = rem.ToLocal(self.revisionExpr)
  888. if all_refs is not None and rev in all_refs:
  889. return all_refs[rev]
  890. try:
  891. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  892. except GitError:
  893. raise ManifestInvalidRevisionError(
  894. 'revision %s in %s not found' % (self.revisionExpr,
  895. self.name))
  896. def Sync_LocalHalf(self, syncbuf):
  897. """Perform only the local IO portion of the sync process.
  898. Network access is not required.
  899. """
  900. all_refs = self.bare_ref.all
  901. self.CleanPublishedCache(all_refs)
  902. revid = self.GetRevisionId(all_refs)
  903. def _doff():
  904. self._FastForward(revid)
  905. self._CopyFiles()
  906. self._InitWorkTree()
  907. head = self.work_git.GetHead()
  908. if head.startswith(R_HEADS):
  909. branch = head[len(R_HEADS):]
  910. try:
  911. head = all_refs[head]
  912. except KeyError:
  913. head = None
  914. else:
  915. branch = None
  916. if branch is None or syncbuf.detach_head:
  917. # Currently on a detached HEAD. The user is assumed to
  918. # not have any local modifications worth worrying about.
  919. #
  920. if self.IsRebaseInProgress():
  921. syncbuf.fail(self, _PriorSyncFailedError())
  922. return
  923. if head == revid:
  924. # No changes; don't do anything further.
  925. # Except if the head needs to be detached
  926. #
  927. if not syncbuf.detach_head:
  928. return
  929. else:
  930. lost = self._revlist(not_rev(revid), HEAD)
  931. if lost:
  932. syncbuf.info(self, "discarding %d commits", len(lost))
  933. try:
  934. self._Checkout(revid, quiet=True)
  935. except GitError as e:
  936. syncbuf.fail(self, e)
  937. return
  938. self._CopyFiles()
  939. return
  940. if head == revid:
  941. # No changes; don't do anything further.
  942. #
  943. return
  944. branch = self.GetBranch(branch)
  945. if not branch.LocalMerge:
  946. # The current branch has no tracking configuration.
  947. # Jump off it to a detached HEAD.
  948. #
  949. syncbuf.info(self,
  950. "leaving %s; does not track upstream",
  951. branch.name)
  952. try:
  953. self._Checkout(revid, quiet=True)
  954. except GitError as e:
  955. syncbuf.fail(self, e)
  956. return
  957. self._CopyFiles()
  958. return
  959. upstream_gain = self._revlist(not_rev(HEAD), revid)
  960. pub = self.WasPublished(branch.name, all_refs)
  961. if pub:
  962. not_merged = self._revlist(not_rev(revid), pub)
  963. if not_merged:
  964. if upstream_gain:
  965. # The user has published this branch and some of those
  966. # commits are not yet merged upstream. We do not want
  967. # to rewrite the published commits so we punt.
  968. #
  969. syncbuf.fail(self,
  970. "branch %s is published (but not merged) and is now %d commits behind"
  971. % (branch.name, len(upstream_gain)))
  972. return
  973. elif pub == head:
  974. # All published commits are merged, and thus we are a
  975. # strict subset. We can fast-forward safely.
  976. #
  977. syncbuf.later1(self, _doff)
  978. return
  979. # Examine the local commits not in the remote. Find the
  980. # last one attributed to this user, if any.
  981. #
  982. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  983. last_mine = None
  984. cnt_mine = 0
  985. for commit in local_changes:
  986. commit_id, committer_email = commit.split(' ', 1)
  987. if committer_email == self.UserEmail:
  988. last_mine = commit_id
  989. cnt_mine += 1
  990. if not upstream_gain and cnt_mine == len(local_changes):
  991. return
  992. if self.IsDirty(consider_untracked=False):
  993. syncbuf.fail(self, _DirtyError())
  994. return
  995. # If the upstream switched on us, warn the user.
  996. #
  997. if branch.merge != self.revisionExpr:
  998. if branch.merge and self.revisionExpr:
  999. syncbuf.info(self,
  1000. 'manifest switched %s...%s',
  1001. branch.merge,
  1002. self.revisionExpr)
  1003. elif branch.merge:
  1004. syncbuf.info(self,
  1005. 'manifest no longer tracks %s',
  1006. branch.merge)
  1007. if cnt_mine < len(local_changes):
  1008. # Upstream rebased. Not everything in HEAD
  1009. # was created by this user.
  1010. #
  1011. syncbuf.info(self,
  1012. "discarding %d commits removed from upstream",
  1013. len(local_changes) - cnt_mine)
  1014. branch.remote = self.GetRemote(self.remote.name)
  1015. if not ID_RE.match(self.revisionExpr):
  1016. # in case of manifest sync the revisionExpr might be a SHA1
  1017. branch.merge = self.revisionExpr
  1018. branch.Save()
  1019. if cnt_mine > 0 and self.rebase:
  1020. def _dorebase():
  1021. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  1022. self._CopyFiles()
  1023. syncbuf.later2(self, _dorebase)
  1024. elif local_changes:
  1025. try:
  1026. self._ResetHard(revid)
  1027. self._CopyFiles()
  1028. except GitError as e:
  1029. syncbuf.fail(self, e)
  1030. return
  1031. else:
  1032. syncbuf.later1(self, _doff)
  1033. def AddCopyFile(self, src, dest, absdest):
  1034. # dest should already be an absolute path, but src is project relative
  1035. # make src an absolute path
  1036. abssrc = os.path.join(self.worktree, src)
  1037. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1038. def AddAnnotation(self, name, value, keep):
  1039. self.annotations.append(_Annotation(name, value, keep))
  1040. def DownloadPatchSet(self, change_id, patch_id):
  1041. """Download a single patch set of a single change to FETCH_HEAD.
  1042. """
  1043. remote = self.GetRemote(self.remote.name)
  1044. cmd = ['fetch', remote.name]
  1045. cmd.append('refs/changes/%2.2d/%d/%d' \
  1046. % (change_id % 100, change_id, patch_id))
  1047. cmd.extend(list(map(str, remote.fetch)))
  1048. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1049. return None
  1050. return DownloadedChange(self,
  1051. self.GetRevisionId(),
  1052. change_id,
  1053. patch_id,
  1054. self.bare_git.rev_parse('FETCH_HEAD'))
  1055. ## Branch Management ##
  1056. def StartBranch(self, name):
  1057. """Create a new branch off the manifest's revision.
  1058. """
  1059. head = self.work_git.GetHead()
  1060. if head == (R_HEADS + name):
  1061. return True
  1062. all_refs = self.bare_ref.all
  1063. if (R_HEADS + name) in all_refs:
  1064. return GitCommand(self,
  1065. ['checkout', name, '--'],
  1066. capture_stdout = True,
  1067. capture_stderr = True).Wait() == 0
  1068. branch = self.GetBranch(name)
  1069. branch.remote = self.GetRemote(self.remote.name)
  1070. branch.merge = self.revisionExpr
  1071. revid = self.GetRevisionId(all_refs)
  1072. if head.startswith(R_HEADS):
  1073. try:
  1074. head = all_refs[head]
  1075. except KeyError:
  1076. head = None
  1077. if revid and head and revid == head:
  1078. ref = os.path.join(self.gitdir, R_HEADS + name)
  1079. try:
  1080. os.makedirs(os.path.dirname(ref))
  1081. except OSError:
  1082. pass
  1083. _lwrite(ref, '%s\n' % revid)
  1084. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1085. 'ref: %s%s\n' % (R_HEADS, name))
  1086. branch.Save()
  1087. return True
  1088. if GitCommand(self,
  1089. ['checkout', '-b', branch.name, revid],
  1090. capture_stdout = True,
  1091. capture_stderr = True).Wait() == 0:
  1092. branch.Save()
  1093. return True
  1094. return False
  1095. def CheckoutBranch(self, name):
  1096. """Checkout a local topic branch.
  1097. Args:
  1098. name: The name of the branch to checkout.
  1099. Returns:
  1100. True if the checkout succeeded; False if it didn't; None if the branch
  1101. didn't exist.
  1102. """
  1103. rev = R_HEADS + name
  1104. head = self.work_git.GetHead()
  1105. if head == rev:
  1106. # Already on the branch
  1107. #
  1108. return True
  1109. all_refs = self.bare_ref.all
  1110. try:
  1111. revid = all_refs[rev]
  1112. except KeyError:
  1113. # Branch does not exist in this project
  1114. #
  1115. return None
  1116. if head.startswith(R_HEADS):
  1117. try:
  1118. head = all_refs[head]
  1119. except KeyError:
  1120. head = None
  1121. if head == revid:
  1122. # Same revision; just update HEAD to point to the new
  1123. # target branch, but otherwise take no other action.
  1124. #
  1125. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1126. 'ref: %s%s\n' % (R_HEADS, name))
  1127. return True
  1128. return GitCommand(self,
  1129. ['checkout', name, '--'],
  1130. capture_stdout = True,
  1131. capture_stderr = True).Wait() == 0
  1132. def AbandonBranch(self, name):
  1133. """Destroy a local topic branch.
  1134. Args:
  1135. name: The name of the branch to abandon.
  1136. Returns:
  1137. True if the abandon succeeded; False if it didn't; None if the branch
  1138. didn't exist.
  1139. """
  1140. rev = R_HEADS + name
  1141. all_refs = self.bare_ref.all
  1142. if rev not in all_refs:
  1143. # Doesn't exist
  1144. return None
  1145. head = self.work_git.GetHead()
  1146. if head == rev:
  1147. # We can't destroy the branch while we are sitting
  1148. # on it. Switch to a detached HEAD.
  1149. #
  1150. head = all_refs[head]
  1151. revid = self.GetRevisionId(all_refs)
  1152. if head == revid:
  1153. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1154. '%s\n' % revid)
  1155. else:
  1156. self._Checkout(revid, quiet=True)
  1157. return GitCommand(self,
  1158. ['branch', '-D', name],
  1159. capture_stdout = True,
  1160. capture_stderr = True).Wait() == 0
  1161. def PruneHeads(self):
  1162. """Prune any topic branches already merged into upstream.
  1163. """
  1164. cb = self.CurrentBranch
  1165. kill = []
  1166. left = self._allrefs
  1167. for name in left.keys():
  1168. if name.startswith(R_HEADS):
  1169. name = name[len(R_HEADS):]
  1170. if cb is None or name != cb:
  1171. kill.append(name)
  1172. rev = self.GetRevisionId(left)
  1173. if cb is not None \
  1174. and not self._revlist(HEAD + '...' + rev) \
  1175. and not self.IsDirty(consider_untracked = False):
  1176. self.work_git.DetachHead(HEAD)
  1177. kill.append(cb)
  1178. if kill:
  1179. old = self.bare_git.GetHead()
  1180. if old is None:
  1181. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1182. try:
  1183. self.bare_git.DetachHead(rev)
  1184. b = ['branch', '-d']
  1185. b.extend(kill)
  1186. b = GitCommand(self, b, bare=True,
  1187. capture_stdout=True,
  1188. capture_stderr=True)
  1189. b.Wait()
  1190. finally:
  1191. self.bare_git.SetHead(old)
  1192. left = self._allrefs
  1193. for branch in kill:
  1194. if (R_HEADS + branch) not in left:
  1195. self.CleanPublishedCache()
  1196. break
  1197. if cb and cb not in kill:
  1198. kill.append(cb)
  1199. kill.sort()
  1200. kept = []
  1201. for branch in kill:
  1202. if (R_HEADS + branch) in left:
  1203. branch = self.GetBranch(branch)
  1204. base = branch.LocalMerge
  1205. if not base:
  1206. base = rev
  1207. kept.append(ReviewableBranch(self, branch, base))
  1208. return kept
  1209. ## Submodule Management ##
  1210. def GetRegisteredSubprojects(self):
  1211. result = []
  1212. def rec(subprojects):
  1213. if not subprojects:
  1214. return
  1215. result.extend(subprojects)
  1216. for p in subprojects:
  1217. rec(p.subprojects)
  1218. rec(self.subprojects)
  1219. return result
  1220. def _GetSubmodules(self):
  1221. # Unfortunately we cannot call `git submodule status --recursive` here
  1222. # because the working tree might not exist yet, and it cannot be used
  1223. # without a working tree in its current implementation.
  1224. def get_submodules(gitdir, rev):
  1225. # Parse .gitmodules for submodule sub_paths and sub_urls
  1226. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1227. if not sub_paths:
  1228. return []
  1229. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1230. # revision of submodule repository
  1231. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1232. submodules = []
  1233. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1234. try:
  1235. sub_rev = sub_revs[sub_path]
  1236. except KeyError:
  1237. # Ignore non-exist submodules
  1238. continue
  1239. submodules.append((sub_rev, sub_path, sub_url))
  1240. return submodules
  1241. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1242. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1243. def parse_gitmodules(gitdir, rev):
  1244. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1245. try:
  1246. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1247. bare = True, gitdir = gitdir)
  1248. except GitError:
  1249. return [], []
  1250. if p.Wait() != 0:
  1251. return [], []
  1252. gitmodules_lines = []
  1253. fd, temp_gitmodules_path = tempfile.mkstemp()
  1254. try:
  1255. os.write(fd, p.stdout)
  1256. os.close(fd)
  1257. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1258. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1259. bare = True, gitdir = gitdir)
  1260. if p.Wait() != 0:
  1261. return [], []
  1262. gitmodules_lines = p.stdout.split('\n')
  1263. except GitError:
  1264. return [], []
  1265. finally:
  1266. os.remove(temp_gitmodules_path)
  1267. names = set()
  1268. paths = {}
  1269. urls = {}
  1270. for line in gitmodules_lines:
  1271. if not line:
  1272. continue
  1273. m = re_path.match(line)
  1274. if m:
  1275. names.add(m.group(1))
  1276. paths[m.group(1)] = m.group(2)
  1277. continue
  1278. m = re_url.match(line)
  1279. if m:
  1280. names.add(m.group(1))
  1281. urls[m.group(1)] = m.group(2)
  1282. continue
  1283. names = sorted(names)
  1284. return ([paths.get(name, '') for name in names],
  1285. [urls.get(name, '') for name in names])
  1286. def git_ls_tree(gitdir, rev, paths):
  1287. cmd = ['ls-tree', rev, '--']
  1288. cmd.extend(paths)
  1289. try:
  1290. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1291. bare = True, gitdir = gitdir)
  1292. except GitError:
  1293. return []
  1294. if p.Wait() != 0:
  1295. return []
  1296. objects = {}
  1297. for line in p.stdout.split('\n'):
  1298. if not line.strip():
  1299. continue
  1300. object_rev, object_path = line.split()[2:4]
  1301. objects[object_path] = object_rev
  1302. return objects
  1303. try:
  1304. rev = self.GetRevisionId()
  1305. except GitError:
  1306. return []
  1307. return get_submodules(self.gitdir, rev)
  1308. def GetDerivedSubprojects(self):
  1309. result = []
  1310. if not self.Exists:
  1311. # If git repo does not exist yet, querying its submodules will
  1312. # mess up its states; so return here.
  1313. return result
  1314. for rev, path, url in self._GetSubmodules():
  1315. name = self.manifest.GetSubprojectName(self, path)
  1316. project = self.manifest.projects.get(name)
  1317. if project:
  1318. result.extend(project.GetDerivedSubprojects())
  1319. continue
  1320. relpath, worktree, gitdir = self.manifest.GetSubprojectPaths(self, path)
  1321. remote = RemoteSpec(self.remote.name,
  1322. url = url,
  1323. review = self.remote.review)
  1324. subproject = Project(manifest = self.manifest,
  1325. name = name,
  1326. remote = remote,
  1327. gitdir = gitdir,
  1328. worktree = worktree,
  1329. relpath = relpath,
  1330. revisionExpr = self.revisionExpr,
  1331. revisionId = rev,
  1332. rebase = self.rebase,
  1333. groups = self.groups,
  1334. sync_c = self.sync_c,
  1335. sync_s = self.sync_s,
  1336. parent = self,
  1337. is_derived = True)
  1338. result.append(subproject)
  1339. result.extend(subproject.GetDerivedSubprojects())
  1340. return result
  1341. ## Direct Git Commands ##
  1342. def _RemoteFetch(self, name=None,
  1343. current_branch_only=False,
  1344. initial=False,
  1345. quiet=False,
  1346. alt_dir=None,
  1347. no_tags=False):
  1348. is_sha1 = False
  1349. tag_name = None
  1350. def CheckForSha1():
  1351. try:
  1352. # if revision (sha or tag) is not present then following function
  1353. # throws an error.
  1354. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1355. return True
  1356. except GitError:
  1357. # There is no such persistent revision. We have to fetch it.
  1358. return False
  1359. if current_branch_only:
  1360. if ID_RE.match(self.revisionExpr) is not None:
  1361. is_sha1 = True
  1362. elif self.revisionExpr.startswith(R_TAGS):
  1363. # this is a tag and its sha1 value should never change
  1364. tag_name = self.revisionExpr[len(R_TAGS):]
  1365. if is_sha1 or tag_name is not None:
  1366. if CheckForSha1():
  1367. return True
  1368. if is_sha1 and (not self.upstream or ID_RE.match(self.upstream)):
  1369. current_branch_only = False
  1370. if not name:
  1371. name = self.remote.name
  1372. ssh_proxy = False
  1373. remote = self.GetRemote(name)
  1374. if remote.PreConnectFetch():
  1375. ssh_proxy = True
  1376. if initial:
  1377. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1378. ref_dir = os.path.dirname(alt_dir)
  1379. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1380. remote = self.GetRemote(name)
  1381. all_refs = self.bare_ref.all
  1382. ids = set(all_refs.values())
  1383. tmp = set()
  1384. for r, ref_id in GitRefs(ref_dir).all.items():
  1385. if r not in all_refs:
  1386. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1387. all_refs[r] = ref_id
  1388. ids.add(ref_id)
  1389. continue
  1390. if ref_id in ids:
  1391. continue
  1392. r = 'refs/_alt/%s' % ref_id
  1393. all_refs[r] = ref_id
  1394. ids.add(ref_id)
  1395. tmp.add(r)
  1396. tmp_packed = ''
  1397. old_packed = ''
  1398. for r in sorted(all_refs):
  1399. line = '%s %s\n' % (all_refs[r], r)
  1400. tmp_packed += line
  1401. if r not in tmp:
  1402. old_packed += line
  1403. _lwrite(packed_refs, tmp_packed)
  1404. else:
  1405. alt_dir = None
  1406. cmd = ['fetch']
  1407. # The --depth option only affects the initial fetch; after that we'll do
  1408. # full fetches of changes.
  1409. if self.clone_depth:
  1410. depth = self.clone_depth
  1411. else:
  1412. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1413. if depth and initial:
  1414. cmd.append('--depth=%s' % depth)
  1415. if quiet:
  1416. cmd.append('--quiet')
  1417. if not self.worktree:
  1418. cmd.append('--update-head-ok')
  1419. cmd.append(name)
  1420. if not current_branch_only:
  1421. # Fetch whole repo
  1422. # If using depth then we should not get all the tags since they may
  1423. # be outside of the depth.
  1424. if no_tags or depth:
  1425. cmd.append('--no-tags')
  1426. else:
  1427. cmd.append('--tags')
  1428. cmd.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1429. elif tag_name is not None:
  1430. cmd.append('tag')
  1431. cmd.append(tag_name)
  1432. else:
  1433. branch = self.revisionExpr
  1434. if is_sha1:
  1435. branch = self.upstream
  1436. if branch.startswith(R_HEADS):
  1437. branch = branch[len(R_HEADS):]
  1438. cmd.append(str((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch)))
  1439. ok = False
  1440. for _i in range(2):
  1441. ret = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait()
  1442. if ret == 0:
  1443. ok = True
  1444. break
  1445. elif current_branch_only and is_sha1 and ret == 128:
  1446. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1447. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1448. # abort the optimization attempt and do a full sync.
  1449. break
  1450. time.sleep(random.randint(30, 45))
  1451. if initial:
  1452. if alt_dir:
  1453. if old_packed != '':
  1454. _lwrite(packed_refs, old_packed)
  1455. else:
  1456. os.remove(packed_refs)
  1457. self.bare_git.pack_refs('--all', '--prune')
  1458. if is_sha1 and current_branch_only and self.upstream:
  1459. # We just synced the upstream given branch; verify we
  1460. # got what we wanted, else trigger a second run of all
  1461. # refs.
  1462. if not CheckForSha1():
  1463. return self._RemoteFetch(name=name, current_branch_only=False,
  1464. initial=False, quiet=quiet, alt_dir=alt_dir)
  1465. return ok
  1466. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1467. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1468. return False
  1469. remote = self.GetRemote(self.remote.name)
  1470. bundle_url = remote.url + '/clone.bundle'
  1471. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1472. if GetSchemeFromUrl(bundle_url) in ('persistent-http', 'persistent-https'):
  1473. bundle_url = bundle_url[len('persistent-'):]
  1474. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1475. return False
  1476. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1477. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1478. exist_dst = os.path.exists(bundle_dst)
  1479. exist_tmp = os.path.exists(bundle_tmp)
  1480. if not initial and not exist_dst and not exist_tmp:
  1481. return False
  1482. if not exist_dst:
  1483. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1484. if not exist_dst:
  1485. return False
  1486. cmd = ['fetch']
  1487. if quiet:
  1488. cmd.append('--quiet')
  1489. if not self.worktree:
  1490. cmd.append('--update-head-ok')
  1491. cmd.append(bundle_dst)
  1492. for f in remote.fetch:
  1493. cmd.append(str(f))
  1494. cmd.append('refs/tags/*:refs/tags/*')
  1495. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1496. if os.path.exists(bundle_dst):
  1497. os.remove(bundle_dst)
  1498. if os.path.exists(bundle_tmp):
  1499. os.remove(bundle_tmp)
  1500. return ok
  1501. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1502. if os.path.exists(dstPath):
  1503. os.remove(dstPath)
  1504. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1505. if quiet:
  1506. cmd += ['--silent']
  1507. if os.path.exists(tmpPath):
  1508. size = os.stat(tmpPath).st_size
  1509. if size >= 1024:
  1510. cmd += ['--continue-at', '%d' % (size,)]
  1511. else:
  1512. os.remove(tmpPath)
  1513. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1514. cmd += ['--proxy', os.environ['http_proxy']]
  1515. cookiefile = GitConfig.ForUser().GetString('http.cookiefile')
  1516. if cookiefile:
  1517. cmd += ['--cookie', cookiefile]
  1518. cmd += [srcUrl]
  1519. if IsTrace():
  1520. Trace('%s', ' '.join(cmd))
  1521. try:
  1522. proc = subprocess.Popen(cmd)
  1523. except OSError:
  1524. return False
  1525. curlret = proc.wait()
  1526. if curlret == 22:
  1527. # From curl man page:
  1528. # 22: HTTP page not retrieved. The requested url was not found or
  1529. # returned another error with the HTTP error code being 400 or above.
  1530. # This return code only appears if -f, --fail is used.
  1531. if not quiet:
  1532. print("Server does not provide clone.bundle; ignoring.",
  1533. file=sys.stderr)
  1534. return False
  1535. if os.path.exists(tmpPath):
  1536. if curlret == 0 and os.stat(tmpPath).st_size > 16:
  1537. os.rename(tmpPath, dstPath)
  1538. return True
  1539. else:
  1540. os.remove(tmpPath)
  1541. return False
  1542. else:
  1543. return False
  1544. def _Checkout(self, rev, quiet=False):
  1545. cmd = ['checkout']
  1546. if quiet:
  1547. cmd.append('-q')
  1548. cmd.append(rev)
  1549. cmd.append('--')
  1550. if GitCommand(self, cmd).Wait() != 0:
  1551. if self._allrefs:
  1552. raise GitError('%s checkout %s ' % (self.name, rev))
  1553. def _CherryPick(self, rev, quiet=False):
  1554. cmd = ['cherry-pick']
  1555. cmd.append(rev)
  1556. cmd.append('--')
  1557. if GitCommand(self, cmd).Wait() != 0:
  1558. if self._allrefs:
  1559. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1560. def _Revert(self, rev, quiet=False):
  1561. cmd = ['revert']
  1562. cmd.append('--no-edit')
  1563. cmd.append(rev)
  1564. cmd.append('--')
  1565. if GitCommand(self, cmd).Wait() != 0:
  1566. if self._allrefs:
  1567. raise GitError('%s revert %s ' % (self.name, rev))
  1568. def _ResetHard(self, rev, quiet=True):
  1569. cmd = ['reset', '--hard']
  1570. if quiet:
  1571. cmd.append('-q')
  1572. cmd.append(rev)
  1573. if GitCommand(self, cmd).Wait() != 0:
  1574. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1575. def _Rebase(self, upstream, onto = None):
  1576. cmd = ['rebase']
  1577. if onto is not None:
  1578. cmd.extend(['--onto', onto])
  1579. cmd.append(upstream)
  1580. if GitCommand(self, cmd).Wait() != 0:
  1581. raise GitError('%s rebase %s ' % (self.name, upstream))
  1582. def _FastForward(self, head, ffonly=False):
  1583. cmd = ['merge', head]
  1584. if ffonly:
  1585. cmd.append("--ff-only")
  1586. if GitCommand(self, cmd).Wait() != 0:
  1587. raise GitError('%s merge %s ' % (self.name, head))
  1588. def _InitGitDir(self):
  1589. if not os.path.exists(self.gitdir):
  1590. os.makedirs(self.gitdir)
  1591. self.bare_git.init()
  1592. mp = self.manifest.manifestProject
  1593. ref_dir = mp.config.GetString('repo.reference')
  1594. if ref_dir:
  1595. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1596. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1597. self.relpath + '.git')
  1598. if os.path.exists(mirror_git):
  1599. ref_dir = mirror_git
  1600. elif os.path.exists(repo_git):
  1601. ref_dir = repo_git
  1602. else:
  1603. ref_dir = None
  1604. if ref_dir:
  1605. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1606. os.path.join(ref_dir, 'objects') + '\n')
  1607. self._UpdateHooks()
  1608. m = self.manifest.manifestProject.config
  1609. for key in ['user.name', 'user.email']:
  1610. if m.Has(key, include_defaults = False):
  1611. self.config.SetString(key, m.GetString(key))
  1612. if self.manifest.IsMirror:
  1613. self.config.SetString('core.bare', 'true')
  1614. else:
  1615. self.config.SetString('core.bare', None)
  1616. def _UpdateHooks(self):
  1617. if os.path.exists(self.gitdir):
  1618. # Always recreate hooks since they can have been changed
  1619. # since the latest update.
  1620. hooks = self._gitdir_path('hooks')
  1621. try:
  1622. to_rm = os.listdir(hooks)
  1623. except OSError:
  1624. to_rm = []
  1625. for old_hook in to_rm:
  1626. os.remove(os.path.join(hooks, old_hook))
  1627. self._InitHooks()
  1628. def _InitHooks(self):
  1629. hooks = self._gitdir_path('hooks')
  1630. if not os.path.exists(hooks):
  1631. os.makedirs(hooks)
  1632. for stock_hook in _ProjectHooks():
  1633. name = os.path.basename(stock_hook)
  1634. if name in ('commit-msg',) and not self.remote.review \
  1635. and not self is self.manifest.manifestProject:
  1636. # Don't install a Gerrit Code Review hook if this
  1637. # project does not appear to use it for reviews.
  1638. #
  1639. # Since the manifest project is one of those, but also
  1640. # managed through gerrit, it's excluded
  1641. continue
  1642. dst = os.path.join(hooks, name)
  1643. if os.path.islink(dst):
  1644. continue
  1645. if os.path.exists(dst):
  1646. if filecmp.cmp(stock_hook, dst, shallow=False):
  1647. os.remove(dst)
  1648. else:
  1649. _error("%s: Not replacing %s hook", self.relpath, name)
  1650. continue
  1651. try:
  1652. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1653. except OSError as e:
  1654. if e.errno == errno.EPERM:
  1655. raise GitError('filesystem must support symlinks')
  1656. else:
  1657. raise
  1658. def _InitRemote(self):
  1659. if self.remote.url:
  1660. remote = self.GetRemote(self.remote.name)
  1661. remote.url = self.remote.url
  1662. remote.review = self.remote.review
  1663. remote.projectname = self.name
  1664. if self.worktree:
  1665. remote.ResetFetch(mirror=False)
  1666. else:
  1667. remote.ResetFetch(mirror=True)
  1668. remote.Save()
  1669. def _InitMRef(self):
  1670. if self.manifest.branch:
  1671. self._InitAnyMRef(R_M + self.manifest.branch)
  1672. def _InitMirrorHead(self):
  1673. self._InitAnyMRef(HEAD)
  1674. def _InitAnyMRef(self, ref):
  1675. cur = self.bare_ref.symref(ref)
  1676. if self.revisionId:
  1677. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1678. msg = 'manifest set to %s' % self.revisionId
  1679. dst = self.revisionId + '^0'
  1680. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1681. else:
  1682. remote = self.GetRemote(self.remote.name)
  1683. dst = remote.ToLocal(self.revisionExpr)
  1684. if cur != dst:
  1685. msg = 'manifest set to %s' % self.revisionExpr
  1686. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1687. def _InitWorkTree(self):
  1688. dotgit = os.path.join(self.worktree, '.git')
  1689. if not os.path.exists(dotgit):
  1690. os.makedirs(dotgit)
  1691. for name in ['config',
  1692. 'description',
  1693. 'hooks',
  1694. 'info',
  1695. 'logs',
  1696. 'objects',
  1697. 'packed-refs',
  1698. 'refs',
  1699. 'rr-cache',
  1700. 'svn']:
  1701. try:
  1702. src = os.path.join(self.gitdir, name)
  1703. dst = os.path.join(dotgit, name)
  1704. if os.path.islink(dst) or not os.path.exists(dst):
  1705. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  1706. else:
  1707. raise GitError('cannot overwrite a local work tree')
  1708. except OSError as e:
  1709. if e.errno == errno.EPERM:
  1710. raise GitError('filesystem must support symlinks')
  1711. else:
  1712. raise
  1713. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1714. cmd = ['read-tree', '--reset', '-u']
  1715. cmd.append('-v')
  1716. cmd.append(HEAD)
  1717. if GitCommand(self, cmd).Wait() != 0:
  1718. raise GitError("cannot initialize work tree")
  1719. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1720. if not os.path.exists(rr_cache):
  1721. os.makedirs(rr_cache)
  1722. self._CopyFiles()
  1723. def _gitdir_path(self, path):
  1724. return os.path.join(self.gitdir, path)
  1725. def _revlist(self, *args, **kw):
  1726. a = []
  1727. a.extend(args)
  1728. a.append('--')
  1729. return self.work_git.rev_list(*a, **kw)
  1730. @property
  1731. def _allrefs(self):
  1732. return self.bare_ref.all
  1733. class _GitGetByExec(object):
  1734. def __init__(self, project, bare):
  1735. self._project = project
  1736. self._bare = bare
  1737. def LsOthers(self):
  1738. p = GitCommand(self._project,
  1739. ['ls-files',
  1740. '-z',
  1741. '--others',
  1742. '--exclude-standard'],
  1743. bare = False,
  1744. capture_stdout = True,
  1745. capture_stderr = True)
  1746. if p.Wait() == 0:
  1747. out = p.stdout
  1748. if out:
  1749. return out[:-1].split('\0') # pylint: disable=W1401
  1750. # Backslash is not anomalous
  1751. return []
  1752. def DiffZ(self, name, *args):
  1753. cmd = [name]
  1754. cmd.append('-z')
  1755. cmd.extend(args)
  1756. p = GitCommand(self._project,
  1757. cmd,
  1758. bare = False,
  1759. capture_stdout = True,
  1760. capture_stderr = True)
  1761. try:
  1762. out = p.process.stdout.read()
  1763. r = {}
  1764. if out:
  1765. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  1766. while out:
  1767. try:
  1768. info = out.next()
  1769. path = out.next()
  1770. except StopIteration:
  1771. break
  1772. class _Info(object):
  1773. def __init__(self, path, omode, nmode, oid, nid, state):
  1774. self.path = path
  1775. self.src_path = None
  1776. self.old_mode = omode
  1777. self.new_mode = nmode
  1778. self.old_id = oid
  1779. self.new_id = nid
  1780. if len(state) == 1:
  1781. self.status = state
  1782. self.level = None
  1783. else:
  1784. self.status = state[:1]
  1785. self.level = state[1:]
  1786. while self.level.startswith('0'):
  1787. self.level = self.level[1:]
  1788. info = info[1:].split(' ')
  1789. info = _Info(path, *info)
  1790. if info.status in ('R', 'C'):
  1791. info.src_path = info.path
  1792. info.path = out.next()
  1793. r[info.path] = info
  1794. return r
  1795. finally:
  1796. p.Wait()
  1797. def GetHead(self):
  1798. if self._bare:
  1799. path = os.path.join(self._project.gitdir, HEAD)
  1800. else:
  1801. path = os.path.join(self._project.worktree, '.git', HEAD)
  1802. try:
  1803. fd = open(path, 'rb')
  1804. except IOError:
  1805. raise NoManifestException(path)
  1806. try:
  1807. line = fd.read()
  1808. finally:
  1809. fd.close()
  1810. try:
  1811. line = line.decode()
  1812. except AttributeError:
  1813. pass
  1814. if line.startswith('ref: '):
  1815. return line[5:-1]
  1816. return line[:-1]
  1817. def SetHead(self, ref, message=None):
  1818. cmdv = []
  1819. if message is not None:
  1820. cmdv.extend(['-m', message])
  1821. cmdv.append(HEAD)
  1822. cmdv.append(ref)
  1823. self.symbolic_ref(*cmdv)
  1824. def DetachHead(self, new, message=None):
  1825. cmdv = ['--no-deref']
  1826. if message is not None:
  1827. cmdv.extend(['-m', message])
  1828. cmdv.append(HEAD)
  1829. cmdv.append(new)
  1830. self.update_ref(*cmdv)
  1831. def UpdateRef(self, name, new, old=None,
  1832. message=None,
  1833. detach=False):
  1834. cmdv = []
  1835. if message is not None:
  1836. cmdv.extend(['-m', message])
  1837. if detach:
  1838. cmdv.append('--no-deref')
  1839. cmdv.append(name)
  1840. cmdv.append(new)
  1841. if old is not None:
  1842. cmdv.append(old)
  1843. self.update_ref(*cmdv)
  1844. def DeleteRef(self, name, old=None):
  1845. if not old:
  1846. old = self.rev_parse(name)
  1847. self.update_ref('-d', name, old)
  1848. self._project.bare_ref.deleted(name)
  1849. def rev_list(self, *args, **kw):
  1850. if 'format' in kw:
  1851. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1852. else:
  1853. cmdv = ['rev-list']
  1854. cmdv.extend(args)
  1855. p = GitCommand(self._project,
  1856. cmdv,
  1857. bare = self._bare,
  1858. capture_stdout = True,
  1859. capture_stderr = True)
  1860. r = []
  1861. for line in p.process.stdout:
  1862. if line[-1] == '\n':
  1863. line = line[:-1]
  1864. r.append(line)
  1865. if p.Wait() != 0:
  1866. raise GitError('%s rev-list %s: %s' % (
  1867. self._project.name,
  1868. str(args),
  1869. p.stderr))
  1870. return r
  1871. def __getattr__(self, name):
  1872. """Allow arbitrary git commands using pythonic syntax.
  1873. This allows you to do things like:
  1874. git_obj.rev_parse('HEAD')
  1875. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1876. run. We'll replace the '_' with a '-' and try to run a git command.
  1877. Any other positional arguments will be passed to the git command, and the
  1878. following keyword arguments are supported:
  1879. config: An optional dict of git config options to be passed with '-c'.
  1880. Args:
  1881. name: The name of the git command to call. Any '_' characters will
  1882. be replaced with '-'.
  1883. Returns:
  1884. A callable object that will try to call git with the named command.
  1885. """
  1886. name = name.replace('_', '-')
  1887. def runner(*args, **kwargs):
  1888. cmdv = []
  1889. config = kwargs.pop('config', None)
  1890. for k in kwargs:
  1891. raise TypeError('%s() got an unexpected keyword argument %r'
  1892. % (name, k))
  1893. if config is not None:
  1894. if not git_require((1, 7, 2)):
  1895. raise ValueError('cannot set config on command line for %s()'
  1896. % name)
  1897. for k, v in config.items():
  1898. cmdv.append('-c')
  1899. cmdv.append('%s=%s' % (k, v))
  1900. cmdv.append(name)
  1901. cmdv.extend(args)
  1902. p = GitCommand(self._project,
  1903. cmdv,
  1904. bare = self._bare,
  1905. capture_stdout = True,
  1906. capture_stderr = True)
  1907. if p.Wait() != 0:
  1908. raise GitError('%s %s: %s' % (
  1909. self._project.name,
  1910. name,
  1911. p.stderr))
  1912. r = p.stdout
  1913. try:
  1914. r = r.decode()
  1915. except AttributeError:
  1916. pass
  1917. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1918. return r[:-1]
  1919. return r
  1920. return runner
  1921. class _PriorSyncFailedError(Exception):
  1922. def __str__(self):
  1923. return 'prior sync failed; rebase still in progress'
  1924. class _DirtyError(Exception):
  1925. def __str__(self):
  1926. return 'contains uncommitted changes'
  1927. class _InfoMessage(object):
  1928. def __init__(self, project, text):
  1929. self.project = project
  1930. self.text = text
  1931. def Print(self, syncbuf):
  1932. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1933. syncbuf.out.nl()
  1934. class _Failure(object):
  1935. def __init__(self, project, why):
  1936. self.project = project
  1937. self.why = why
  1938. def Print(self, syncbuf):
  1939. syncbuf.out.fail('error: %s/: %s',
  1940. self.project.relpath,
  1941. str(self.why))
  1942. syncbuf.out.nl()
  1943. class _Later(object):
  1944. def __init__(self, project, action):
  1945. self.project = project
  1946. self.action = action
  1947. def Run(self, syncbuf):
  1948. out = syncbuf.out
  1949. out.project('project %s/', self.project.relpath)
  1950. out.nl()
  1951. try:
  1952. self.action()
  1953. out.nl()
  1954. return True
  1955. except GitError:
  1956. out.nl()
  1957. return False
  1958. class _SyncColoring(Coloring):
  1959. def __init__(self, config):
  1960. Coloring.__init__(self, config, 'reposync')
  1961. self.project = self.printer('header', attr = 'bold')
  1962. self.info = self.printer('info')
  1963. self.fail = self.printer('fail', fg='red')
  1964. class SyncBuffer(object):
  1965. def __init__(self, config, detach_head=False):
  1966. self._messages = []
  1967. self._failures = []
  1968. self._later_queue1 = []
  1969. self._later_queue2 = []
  1970. self.out = _SyncColoring(config)
  1971. self.out.redirect(sys.stderr)
  1972. self.detach_head = detach_head
  1973. self.clean = True
  1974. def info(self, project, fmt, *args):
  1975. self._messages.append(_InfoMessage(project, fmt % args))
  1976. def fail(self, project, err=None):
  1977. self._failures.append(_Failure(project, err))
  1978. self.clean = False
  1979. def later1(self, project, what):
  1980. self._later_queue1.append(_Later(project, what))
  1981. def later2(self, project, what):
  1982. self._later_queue2.append(_Later(project, what))
  1983. def Finish(self):
  1984. self._PrintMessages()
  1985. self._RunLater()
  1986. self._PrintMessages()
  1987. return self.clean
  1988. def _RunLater(self):
  1989. for q in ['_later_queue1', '_later_queue2']:
  1990. if not self._RunQueue(q):
  1991. return
  1992. def _RunQueue(self, queue):
  1993. for m in getattr(self, queue):
  1994. if not m.Run(self):
  1995. self.clean = False
  1996. return False
  1997. setattr(self, queue, [])
  1998. return True
  1999. def _PrintMessages(self):
  2000. for m in self._messages:
  2001. m.Print(self)
  2002. for m in self._failures:
  2003. m.Print(self)
  2004. self._messages = []
  2005. self._failures = []
  2006. class MetaProject(Project):
  2007. """A special project housed under .repo.
  2008. """
  2009. def __init__(self, manifest, name, gitdir, worktree):
  2010. Project.__init__(self,
  2011. manifest = manifest,
  2012. name = name,
  2013. gitdir = gitdir,
  2014. worktree = worktree,
  2015. remote = RemoteSpec('origin'),
  2016. relpath = '.repo/%s' % name,
  2017. revisionExpr = 'refs/heads/master',
  2018. revisionId = None,
  2019. groups = None)
  2020. def PreSync(self):
  2021. if self.Exists:
  2022. cb = self.CurrentBranch
  2023. if cb:
  2024. base = self.GetBranch(cb).merge
  2025. if base:
  2026. self.revisionExpr = base
  2027. self.revisionId = None
  2028. def MetaBranchSwitch(self, target):
  2029. """ Prepare MetaProject for manifest branch switch
  2030. """
  2031. # detach and delete manifest branch, allowing a new
  2032. # branch to take over
  2033. syncbuf = SyncBuffer(self.config, detach_head = True)
  2034. self.Sync_LocalHalf(syncbuf)
  2035. syncbuf.Finish()
  2036. return GitCommand(self,
  2037. ['update-ref', '-d', 'refs/heads/default'],
  2038. capture_stdout = True,
  2039. capture_stderr = True).Wait() == 0
  2040. @property
  2041. def LastFetch(self):
  2042. try:
  2043. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2044. return os.path.getmtime(fh)
  2045. except OSError:
  2046. return 0
  2047. @property
  2048. def HasChanges(self):
  2049. """Has the remote received new commits not yet checked out?
  2050. """
  2051. if not self.remote or not self.revisionExpr:
  2052. return False
  2053. all_refs = self.bare_ref.all
  2054. revid = self.GetRevisionId(all_refs)
  2055. head = self.work_git.GetHead()
  2056. if head.startswith(R_HEADS):
  2057. try:
  2058. head = all_refs[head]
  2059. except KeyError:
  2060. head = None
  2061. if revid == head:
  2062. return False
  2063. elif self._revlist(not_rev(HEAD), revid):
  2064. return True
  2065. return False