project.py 75 KB

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