project.py 107 KB

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