project.py 105 KB

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