project.py 117 KB

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