project.py 94 KB

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