project.py 93 KB

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