project.py 106 KB

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