project.py 115 KB

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