project.py 94 KB

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