project.py 95 KB

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