project.py 91 KB

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