project.py 81 KB

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