project.py 110 KB

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