gclient.py 164 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Meta checkout dependency manager for Git."""
  6. # Files
  7. # .gclient : Current client configuration, written by 'config' command.
  8. # Format is a Python script defining 'solutions', a list whose
  9. # entries each are maps binding the strings "name" and "url"
  10. # to strings specifying the name and location of the client
  11. # module, as well as "custom_deps" to a map similar to the
  12. # deps section of the DEPS file below, as well as
  13. # "custom_hooks" to a list similar to the hooks sections of
  14. # the DEPS file below.
  15. # .gclient_entries : A cache constructed by 'update' command. Format is a
  16. # Python script defining 'entries', a list of the names
  17. # of all modules in the client
  18. # <module>/DEPS : Python script defining var 'deps' as a map from each
  19. # requisite submodule name to a URL where it can be found (via
  20. # one SCM)
  21. #
  22. # Hooks
  23. # .gclient and DEPS files may optionally contain a list named "hooks" to
  24. # allow custom actions to be performed based on files that have changed in the
  25. # working copy as a result of a "sync"/"update" or "revert" operation. This
  26. # can be prevented by using --nohooks (hooks run by default). Hooks can also
  27. # be forced to run with the "runhooks" operation. If "sync" is run with
  28. # --force, all known but not suppressed hooks will run regardless of the state
  29. # of the working copy.
  30. #
  31. # Each item in a "hooks" list is a dict, containing these two keys:
  32. # "pattern" The associated value is a string containing a regular
  33. # expression. When a file whose pathname matches the expression
  34. # is checked out, updated, or reverted, the hook's "action" will
  35. # run.
  36. # "action" A list describing a command to run along with its arguments, if
  37. # any. An action command will run at most one time per gclient
  38. # invocation, regardless of how many files matched the pattern.
  39. # The action is executed in the same directory as the .gclient
  40. # file. If the first item in the list is the string "python",
  41. # the current Python interpreter (sys.executable) will be used
  42. # to run the command. If the list contains string
  43. # "$matching_files" it will be removed from the list and the list
  44. # will be extended by the list of matching files.
  45. # "name" An optional string specifying the group to which a hook belongs
  46. # for overriding and organizing.
  47. #
  48. # Example:
  49. # hooks = [
  50. # { "pattern": "\\.(gif|jpe?g|pr0n|png)$",
  51. # "action": ["python", "image_indexer.py", "--all"]},
  52. # { "pattern": ".",
  53. # "name": "gyp",
  54. # "action": ["python", "src/build/gyp_chromium"]},
  55. # ]
  56. #
  57. # Pre-DEPS Hooks
  58. # DEPS files may optionally contain a list named "pre_deps_hooks". These are
  59. # the same as normal hooks, except that they run before the DEPS are
  60. # processed. Pre-DEPS run with "sync" and "revert" unless the --noprehooks
  61. # flag is used.
  62. #
  63. # Specifying a target OS
  64. # An optional key named "target_os" may be added to a gclient file to specify
  65. # one or more additional operating systems that should be considered when
  66. # processing the deps_os/hooks_os dict of a DEPS file.
  67. #
  68. # Example:
  69. # target_os = [ "android" ]
  70. #
  71. # If the "target_os_only" key is also present and true, then *only* the
  72. # operating systems listed in "target_os" will be used.
  73. #
  74. # Example:
  75. # target_os = [ "ios" ]
  76. # target_os_only = True
  77. #
  78. # Specifying a target CPU
  79. # To specify a target CPU, the variables target_cpu and target_cpu_only
  80. # are available and are analogous to target_os and target_os_only.
  81. __version__ = '0.7'
  82. import copy
  83. import json
  84. import logging
  85. import optparse
  86. import os
  87. import platform
  88. import posixpath
  89. import pprint
  90. import re
  91. import sys
  92. import time
  93. import urllib.parse
  94. from collections.abc import Collection, Mapping, Sequence
  95. import detect_host_arch
  96. import fix_encoding
  97. import git_common
  98. import gclient_eval
  99. import gclient_paths
  100. import gclient_scm
  101. import gclient_utils
  102. import git_cache
  103. import metrics
  104. import metrics_utils
  105. import scm as scm_git
  106. import setup_color
  107. import subcommand
  108. import subprocess2
  109. from third_party.repo.progress import Progress
  110. # TODO: Should fix these warnings.
  111. # pylint: disable=line-too-long
  112. DEPOT_TOOLS_DIR = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
  113. # Singleton object to represent an unset cache_dir (as opposed to a disabled
  114. # one, e.g. if a spec explicitly says `cache_dir = None`.)
  115. UNSET_CACHE_DIR = object()
  116. PREVIOUS_CUSTOM_VARS_FILE = '.gclient_previous_custom_vars'
  117. PREVIOUS_SYNC_COMMITS_FILE = '.gclient_previous_sync_commits'
  118. PREVIOUS_SYNC_COMMITS = 'GCLIENT_PREVIOUS_SYNC_COMMITS'
  119. NO_SYNC_EXPERIMENT = 'no-sync'
  120. PRECOMMIT_HOOK_VAR = 'GCLIENT_PRECOMMIT'
  121. class GNException(Exception):
  122. pass
  123. def ToGNString(value):
  124. """Returns a stringified GN equivalent of the Python value."""
  125. if isinstance(value, str):
  126. if value.find('\n') >= 0:
  127. raise GNException("Trying to print a string with a newline in it.")
  128. return '"' + \
  129. value.replace('\\', '\\\\').replace('"', '\\"').replace('$', '\\$') + \
  130. '"'
  131. if isinstance(value, bool):
  132. if value:
  133. return "true"
  134. return "false"
  135. # NOTE: some type handling removed compared to chromium/src copy.
  136. raise GNException("Unsupported type when printing to GN.")
  137. class Hook(object):
  138. """Descriptor of command ran before/after sync or on demand."""
  139. def __init__(self,
  140. action,
  141. pattern=None,
  142. name=None,
  143. cwd=None,
  144. condition=None,
  145. variables=None,
  146. verbose=False,
  147. cwd_base=None):
  148. """Constructor.
  149. Arguments:
  150. action (list of str): argv of the command to run
  151. pattern (str regex): noop with git; deprecated
  152. name (str): optional name; no effect on operation
  153. cwd (str): working directory to use
  154. condition (str): condition when to run the hook
  155. variables (dict): variables for evaluating the condition
  156. """
  157. self._action = gclient_utils.freeze(action)
  158. self._pattern = pattern
  159. self._name = name
  160. self._cwd = cwd
  161. self._condition = condition
  162. self._variables = variables
  163. self._verbose = verbose
  164. self._cwd_base = cwd_base
  165. @staticmethod
  166. def from_dict(d,
  167. variables=None,
  168. verbose=False,
  169. conditions=None,
  170. cwd_base=None):
  171. """Creates a Hook instance from a dict like in the DEPS file."""
  172. # Merge any local and inherited conditions.
  173. gclient_eval.UpdateCondition(d, 'and', conditions)
  174. return Hook(
  175. d['action'],
  176. d.get('pattern'),
  177. d.get('name'),
  178. d.get('cwd'),
  179. d.get('condition'),
  180. variables=variables,
  181. # Always print the header if not printing to a TTY.
  182. verbose=verbose or not setup_color.IS_TTY,
  183. cwd_base=cwd_base)
  184. @property
  185. def action(self):
  186. return self._action
  187. @property
  188. def pattern(self):
  189. return self._pattern
  190. @property
  191. def name(self):
  192. return self._name
  193. @property
  194. def condition(self):
  195. return self._condition
  196. @property
  197. def effective_cwd(self):
  198. cwd = self._cwd_base
  199. if self._cwd:
  200. cwd = os.path.join(cwd, self._cwd)
  201. return cwd
  202. def matches(self, file_list):
  203. """Returns true if the pattern matches any of files in the list."""
  204. if not self._pattern:
  205. return True
  206. pattern = re.compile(self._pattern)
  207. return bool([f for f in file_list if pattern.search(f)])
  208. def run(self):
  209. """Executes the hook's command (provided the condition is met)."""
  210. if (self._condition and not gclient_eval.EvaluateCondition(
  211. self._condition, self._variables)):
  212. return
  213. cmd = list(self._action)
  214. if cmd[0] == 'vpython3' and _detect_host_os() == 'win':
  215. cmd[0] += '.bat'
  216. exit_code = 2
  217. try:
  218. start_time = time.time()
  219. gclient_utils.CheckCallAndFilter(cmd,
  220. cwd=self.effective_cwd,
  221. print_stdout=True,
  222. show_header=True,
  223. always_show_header=self._verbose)
  224. exit_code = 0
  225. except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
  226. # Use a discrete exit status code of 2 to indicate that a hook
  227. # action failed. Users of this script may wish to treat hook action
  228. # failures differently from VC failures.
  229. print('Error: %s' % str(e), file=sys.stderr)
  230. sys.exit(exit_code)
  231. finally:
  232. elapsed_time = time.time() - start_time
  233. metrics.collector.add_repeated(
  234. 'hooks', {
  235. 'action':
  236. gclient_utils.CommandToStr(cmd),
  237. 'name':
  238. self._name,
  239. 'cwd':
  240. os.path.relpath(os.path.normpath(self.effective_cwd),
  241. self._cwd_base),
  242. 'condition':
  243. self._condition,
  244. 'execution_time':
  245. elapsed_time,
  246. 'exit_code':
  247. exit_code,
  248. })
  249. if elapsed_time > 10:
  250. print("Hook '%s' took %.2f secs" %
  251. (gclient_utils.CommandToStr(cmd), elapsed_time))
  252. class DependencySettings(object):
  253. """Immutable configuration settings."""
  254. def __init__(self, parent, url, managed, custom_deps, custom_vars,
  255. custom_hooks, deps_file, should_process, relative, condition):
  256. # These are not mutable:
  257. self._parent = parent
  258. self._deps_file = deps_file
  259. self._url = url
  260. # The condition as string (or None). Useful to keep e.g. for flatten.
  261. self._condition = condition
  262. # 'managed' determines whether or not this dependency is synced/updated
  263. # by gclient after gclient checks it out initially. The difference
  264. # between 'managed' and 'should_process' is that the user specifies
  265. # 'managed' via the --unmanaged command-line flag or a .gclient config,
  266. # where 'should_process' is dynamically set by gclient if it goes over
  267. # its recursion limit and controls gclient's behavior so it does not
  268. # misbehave.
  269. self._managed = managed
  270. self._should_process = should_process
  271. # If this is a recursed-upon sub-dependency, and the parent has
  272. # use_relative_paths set, then this dependency should check out its own
  273. # dependencies relative to that parent's path for this, rather than
  274. # relative to the .gclient file.
  275. self._relative = relative
  276. # This is a mutable value which has the list of 'target_os' OSes listed
  277. # in the current deps file.
  278. self.local_target_os = None
  279. # These are only set in .gclient and not in DEPS files.
  280. self._custom_vars = custom_vars or {}
  281. self._custom_deps = custom_deps or {}
  282. self._custom_hooks = custom_hooks or []
  283. # Post process the url to remove trailing slashes.
  284. if isinstance(self.url, str):
  285. # urls are sometime incorrectly written as proto://host/path/@rev.
  286. # Replace it to proto://host/path@rev.
  287. self.set_url(self.url.replace('/@', '@'))
  288. elif not isinstance(self.url, (None.__class__)):
  289. raise gclient_utils.Error(
  290. ('dependency url must be either string or None, '
  291. 'instead of %s') % self.url.__class__.__name__)
  292. # Make any deps_file path platform-appropriate.
  293. if self._deps_file:
  294. for sep in ['/', '\\']:
  295. self._deps_file = self._deps_file.replace(sep, os.sep)
  296. @property
  297. def deps_file(self):
  298. return self._deps_file
  299. @property
  300. def managed(self):
  301. return self._managed
  302. @property
  303. def parent(self):
  304. return self._parent
  305. @property
  306. def root(self):
  307. """Returns the root node, a GClient object."""
  308. if not self.parent:
  309. # This line is to signal pylint that it could be a GClient instance.
  310. return self or GClient(None, None)
  311. return self.parent.root
  312. @property
  313. def should_process(self):
  314. """True if this dependency should be processed, i.e. checked out."""
  315. return self._should_process
  316. @property
  317. def custom_vars(self):
  318. return self._custom_vars.copy()
  319. @property
  320. def custom_deps(self):
  321. return self._custom_deps.copy()
  322. @property
  323. def custom_hooks(self):
  324. return self._custom_hooks[:]
  325. @property
  326. def url(self):
  327. """URL after variable expansion."""
  328. return self._url
  329. @property
  330. def condition(self):
  331. return self._condition
  332. @property
  333. def target_os(self):
  334. if self.local_target_os is not None:
  335. return tuple(set(self.local_target_os).union(self.parent.target_os))
  336. return self.parent.target_os
  337. @property
  338. def target_cpu(self):
  339. return self.parent.target_cpu
  340. def set_url(self, url):
  341. self._url = url
  342. def get_custom_deps(self, name, url):
  343. """Returns a custom deps if applicable."""
  344. if self.parent:
  345. url = self.parent.get_custom_deps(name, url)
  346. # None is a valid return value to disable a dependency.
  347. return self.custom_deps.get(name, url)
  348. class Dependency(gclient_utils.WorkItem, DependencySettings):
  349. """Object that represents a dependency checkout."""
  350. def __init__(self,
  351. parent,
  352. name,
  353. url,
  354. managed,
  355. custom_deps,
  356. custom_vars,
  357. custom_hooks,
  358. deps_file,
  359. should_process,
  360. should_recurse,
  361. relative,
  362. condition,
  363. protocol='https',
  364. git_dependencies_state=gclient_eval.DEPS,
  365. print_outbuf=False):
  366. gclient_utils.WorkItem.__init__(self, name)
  367. DependencySettings.__init__(self, parent, url, managed, custom_deps,
  368. custom_vars, custom_hooks, deps_file,
  369. should_process, relative, condition)
  370. # This is in both .gclient and DEPS files:
  371. self._deps_hooks = []
  372. self._pre_deps_hooks = []
  373. # Calculates properties:
  374. self._dependencies = []
  375. self._vars = {}
  376. # A cache of the files affected by the current operation, necessary for
  377. # hooks.
  378. self._file_list = []
  379. # List of host names from which dependencies are allowed.
  380. # Default is an empty set, meaning unspecified in DEPS file, and hence
  381. # all hosts will be allowed. Non-empty set means allowlist of hosts.
  382. # allowed_hosts var is scoped to its DEPS file, and so it isn't
  383. # recursive.
  384. self._allowed_hosts = frozenset()
  385. self._gn_args_from = None
  386. # Spec for .gni output to write (if any).
  387. self._gn_args_file = None
  388. self._gn_args = []
  389. # If it is not set to True, the dependency wasn't processed for its
  390. # child dependency, i.e. its DEPS wasn't read.
  391. self._deps_parsed = False
  392. # This dependency has been processed, i.e. checked out
  393. self._processed = False
  394. # This dependency had its pre-DEPS hooks run
  395. self._pre_deps_hooks_ran = False
  396. # This dependency had its hook run
  397. self._hooks_ran = False
  398. # This is the scm used to checkout self.url. It may be used by
  399. # dependencies to get the datetime of the revision we checked out.
  400. self._used_scm = None
  401. self._used_revision = None
  402. # The actual revision we ended up getting, or None if that information
  403. # is unavailable
  404. self._got_revision = None
  405. # Whether this dependency should use relative paths.
  406. self._use_relative_paths = False
  407. # recursedeps is a mutable value that selectively overrides the default
  408. # 'no recursion' setting on a dep-by-dep basis.
  409. #
  410. # It will be a dictionary of {deps_name: depfile_namee}
  411. self.recursedeps = {}
  412. # Whether we should process this dependency's DEPS file.
  413. self._should_recurse = should_recurse
  414. # Whether we should sync git/cipd dependencies and hooks from the
  415. # DEPS file.
  416. # This is set based on skip_sync_revisions and must be done
  417. # after the patch refs are applied.
  418. # If this is False, we will still run custom_hooks and process
  419. # custom_deps, if any.
  420. self._should_sync = True
  421. self._OverrideUrl()
  422. # This is inherited from WorkItem. We want the URL to be a resource.
  423. if self.url and isinstance(self.url, str):
  424. # The url is usually given to gclient either as https://blah@123
  425. # or just https://blah. The @123 portion is irrelevant.
  426. self.resources.append(self.url.split('@')[0])
  427. # Controls whether we want to print git's output when we first clone the
  428. # dependency
  429. self.print_outbuf = print_outbuf
  430. self.protocol = protocol
  431. self.git_dependencies_state = git_dependencies_state
  432. if not self.name and self.parent:
  433. raise gclient_utils.Error('Dependency without name')
  434. def _OverrideUrl(self):
  435. """Resolves the parsed url from the parent hierarchy."""
  436. parsed_url = self.get_custom_deps(
  437. self._name.replace(os.sep, posixpath.sep) \
  438. if self._name else self._name, self.url)
  439. if parsed_url != self.url:
  440. logging.info('Dependency(%s)._OverrideUrl(%s) -> %s', self._name,
  441. self.url, parsed_url)
  442. self.set_url(parsed_url)
  443. return
  444. if self.url is None:
  445. logging.info('Dependency(%s)._OverrideUrl(None) -> None',
  446. self._name)
  447. return
  448. if not isinstance(self.url, str):
  449. raise gclient_utils.Error('Unknown url type')
  450. # self.url is a local path
  451. path, at, rev = self.url.partition('@')
  452. if os.path.isdir(path):
  453. return
  454. # self.url is a URL
  455. parsed_url = urllib.parse.urlparse(self.url)
  456. if parsed_url[0] or re.match(r'^\w+\@[\w\.-]+\:[\w\/]+', parsed_url[2]):
  457. return
  458. # self.url is relative to the parent's URL.
  459. if not path.startswith('/'):
  460. raise gclient_utils.Error(
  461. 'relative DEPS entry \'%s\' must begin with a slash' % self.url)
  462. parent_url = self.parent.url
  463. parent_path = self.parent.url.split('@')[0]
  464. if os.path.isdir(parent_path):
  465. # Parent's URL is a local path. Get parent's URL dirname and append
  466. # self.url.
  467. parent_path = os.path.dirname(parent_path)
  468. parsed_url = parent_path + path.replace('/', os.sep) + at + rev
  469. else:
  470. # Parent's URL is a URL. Get parent's URL, strip from the last '/'
  471. # (equivalent to unix dirname) and append self.url.
  472. parsed_url = parent_url[:parent_url.rfind('/')] + self.url
  473. logging.info('Dependency(%s)._OverrideUrl(%s) -> %s', self.name,
  474. self.url, parsed_url)
  475. self.set_url(parsed_url)
  476. def PinToActualRevision(self):
  477. """Updates self.url to the revision checked out on disk."""
  478. if self.url is None:
  479. return
  480. url = None
  481. scm = self.CreateSCM()
  482. if scm.name == 'cipd':
  483. revision = scm.revinfo(None, None, None)
  484. package = self.GetExpandedPackageName()
  485. url = '%s/p/%s/+/%s' % (scm.GetActualRemoteURL(None), package,
  486. revision)
  487. if os.path.isdir(scm.checkout_path):
  488. revision = scm.revinfo(None, None, None)
  489. url = '%s@%s' % (gclient_utils.SplitUrlRevision(
  490. self.url)[0], revision)
  491. self.set_url(url)
  492. def ToLines(self):
  493. # () -> Sequence[str]
  494. """Returns strings representing the deps (info, graphviz line)"""
  495. s = []
  496. condition_part = ([' "condition": %r,' %
  497. self.condition] if self.condition else [])
  498. s.extend([
  499. ' # %s' % self.hierarchy(include_url=False),
  500. ' "%s": {' % (self.name, ),
  501. ' "url": "%s",' % (self.url, ),
  502. ] + condition_part + [
  503. ' },',
  504. '',
  505. ])
  506. return s
  507. @property
  508. def requirements(self):
  509. """Calculate the list of requirements."""
  510. requirements = set()
  511. # self.parent is implicitly a requirement. This will be recursive by
  512. # definition.
  513. if self.parent and self.parent.name:
  514. requirements.add(self.parent.name)
  515. # For a tree with at least 2 levels*, the leaf node needs to depend
  516. # on the level higher up in an orderly way.
  517. # This becomes messy for >2 depth as the DEPS file format is a
  518. # dictionary, thus unsorted, while the .gclient format is a list thus
  519. # sorted.
  520. #
  521. # Interestingly enough, the following condition only works in the case
  522. # we want: self is a 2nd level node. 3rd level node wouldn't need this
  523. # since they already have their parent as a requirement.
  524. if self.parent and self.parent.parent and not self.parent.parent.parent:
  525. requirements |= set(i.name for i in self.root.dependencies
  526. if i.name)
  527. if self.name:
  528. requirements |= set(
  529. obj.name for obj in self.root.subtree(False)
  530. if (obj is not self and obj.name
  531. and self.name.startswith(posixpath.join(obj.name, ''))))
  532. requirements = tuple(sorted(requirements))
  533. logging.info('Dependency(%s).requirements = %s' %
  534. (self.name, requirements))
  535. return requirements
  536. @property
  537. def should_recurse(self):
  538. return self._should_recurse
  539. def verify_validity(self):
  540. """Verifies that this Dependency is fine to add as a child of another one.
  541. Returns True if this entry should be added, False if it is a duplicate of
  542. another entry.
  543. """
  544. logging.info('Dependency(%s).verify_validity()' % self.name)
  545. if self.name in [s.name for s in self.parent.dependencies]:
  546. raise gclient_utils.Error(
  547. 'The same name "%s" appears multiple times in the deps section'
  548. % self.name)
  549. if not self.should_process:
  550. # Return early, no need to set requirements.
  551. return not any(d.name == self.name for d in self.root.subtree(True))
  552. # This require a full tree traversal with locks.
  553. siblings = [d for d in self.root.subtree(False) if d.name == self.name]
  554. for sibling in siblings:
  555. # Allow to have only one to be None or ''.
  556. if self.url != sibling.url and bool(self.url) == bool(sibling.url):
  557. raise gclient_utils.Error(
  558. ('Dependency %s specified more than once:\n'
  559. ' %s [%s]\n'
  560. 'vs\n'
  561. ' %s [%s]') % (self.name, sibling.hierarchy(),
  562. sibling.url, self.hierarchy(), self.url))
  563. # In theory we could keep it as a shadow of the other one. In
  564. # practice, simply ignore it.
  565. logging.warning("Won't process duplicate dependency %s" % sibling)
  566. return False
  567. return True
  568. def _postprocess_deps(self, deps, rel_prefix):
  569. # type: (Mapping[str, Mapping[str, str]], str) ->
  570. # Mapping[str, Mapping[str, str]]
  571. """Performs post-processing of deps compared to what's in the DEPS file."""
  572. # If we don't need to sync, only process custom_deps, if any.
  573. if not self._should_sync:
  574. if not self.custom_deps:
  575. return {}
  576. processed_deps = {}
  577. for dep_name, dep_info in self.custom_deps.items():
  578. if dep_info and not dep_info.endswith('@unmanaged'):
  579. if dep_name in deps:
  580. # custom_deps that should override an existing deps gets
  581. # applied in the Dependency itself with _OverrideUrl().
  582. processed_deps[dep_name] = deps[dep_name]
  583. else:
  584. processed_deps[dep_name] = {
  585. 'url': dep_info,
  586. 'dep_type': 'git'
  587. }
  588. else:
  589. processed_deps = dict(deps)
  590. # If a line is in custom_deps, but not in the solution, we want to
  591. # append this line to the solution.
  592. for dep_name, dep_info in self.custom_deps.items():
  593. # Don't add it to the solution for the values of "None" and
  594. # "unmanaged" in order to force these kinds of custom_deps to
  595. # act as revision overrides (via revision_overrides). Having
  596. # them function as revision overrides allows them to be applied
  597. # to recursive dependencies. https://crbug.com/1031185
  598. if (dep_name not in processed_deps and dep_info
  599. and not dep_info.endswith('@unmanaged')):
  600. processed_deps[dep_name] = {
  601. 'url': dep_info,
  602. 'dep_type': 'git'
  603. }
  604. # Make child deps conditional on any parent conditions. This ensures
  605. # that, when flattened, recursed entries have the correct restrictions,
  606. # even if not explicitly set in the recursed DEPS file. For instance, if
  607. # "src/ios_foo" is conditional on "checkout_ios=True", then anything
  608. # recursively included by "src/ios_foo/DEPS" should also require
  609. # "checkout_ios=True".
  610. if self.condition:
  611. for value in processed_deps.values():
  612. gclient_eval.UpdateCondition(value, 'and', self.condition)
  613. if not rel_prefix:
  614. return processed_deps
  615. logging.warning('use_relative_paths enabled.')
  616. rel_deps = {}
  617. for d, url in processed_deps.items():
  618. # normpath is required to allow DEPS to use .. in their
  619. # dependency local path.
  620. # We are following the same pattern when use_relative_paths = False,
  621. # which uses slashes.
  622. rel_deps[os.path.normpath(os.path.join(rel_prefix, d)).replace(
  623. os.path.sep, '/')] = url
  624. logging.warning('Updating deps by prepending %s.', rel_prefix)
  625. return rel_deps
  626. def _deps_to_objects(self, deps, use_relative_paths):
  627. # type: (Mapping[str, Mapping[str, str]], bool) -> Sequence[Dependency]
  628. """Convert a deps dict to a list of Dependency objects."""
  629. deps_to_add = []
  630. cached_conditions = {}
  631. for name, dep_value in deps.items():
  632. should_process = self.should_process
  633. if dep_value is None:
  634. continue
  635. condition = dep_value.get('condition')
  636. dep_type = dep_value.get('dep_type')
  637. if condition and not self._get_option('process_all_deps', False):
  638. if condition not in cached_conditions:
  639. cached_conditions[
  640. condition] = gclient_eval.EvaluateCondition(
  641. condition, self.get_vars())
  642. should_process = should_process and cached_conditions[condition]
  643. # The following option is only set by the 'revinfo' command.
  644. if self._get_option('ignore_dep_type', None) == dep_type:
  645. continue
  646. if dep_type == 'cipd':
  647. cipd_root = self.GetCipdRoot()
  648. for package in dep_value.get('packages', []):
  649. deps_to_add.append(
  650. CipdDependency(parent=self,
  651. name=name,
  652. dep_value=package,
  653. cipd_root=cipd_root,
  654. custom_vars=self.custom_vars,
  655. should_process=should_process,
  656. relative=use_relative_paths,
  657. condition=condition))
  658. else:
  659. url = dep_value.get('url')
  660. deps_to_add.append(
  661. GitDependency(
  662. parent=self,
  663. name=name,
  664. # Update URL with scheme in protocol_override
  665. url=GitDependency.updateProtocol(url, self.protocol),
  666. managed=True,
  667. custom_deps=None,
  668. custom_vars=self.custom_vars,
  669. custom_hooks=None,
  670. deps_file=self.recursedeps.get(name, self.deps_file),
  671. should_process=should_process,
  672. should_recurse=name in self.recursedeps,
  673. relative=use_relative_paths,
  674. condition=condition,
  675. protocol=self.protocol,
  676. git_dependencies_state=self.git_dependencies_state))
  677. # TODO(crbug.com/1341285): Understand why we need this and remove
  678. # it if we don't.
  679. deps_to_add.sort(key=lambda x: x.name)
  680. return deps_to_add
  681. def ParseDepsFile(self):
  682. # type: () -> None
  683. """Parses the DEPS file for this dependency."""
  684. assert not self.deps_parsed
  685. assert not self.dependencies
  686. deps_content = None
  687. # First try to locate the configured deps file. If it's missing,
  688. # fallback to DEPS.
  689. deps_files = [self.deps_file]
  690. if 'DEPS' not in deps_files:
  691. deps_files.append('DEPS')
  692. for deps_file in deps_files:
  693. filepath = os.path.join(self.root.root_dir, self.name, deps_file)
  694. if os.path.isfile(filepath):
  695. logging.info('ParseDepsFile(%s): %s file found at %s',
  696. self.name, deps_file, filepath)
  697. break
  698. logging.info('ParseDepsFile(%s): No %s file found at %s', self.name,
  699. deps_file, filepath)
  700. if os.path.isfile(filepath):
  701. deps_content = gclient_utils.FileRead(filepath)
  702. logging.debug('ParseDepsFile(%s) read:\n%s', self.name,
  703. deps_content)
  704. local_scope = {}
  705. if deps_content:
  706. try:
  707. local_scope = gclient_eval.Parse(deps_content, filepath,
  708. self.get_vars(),
  709. self.get_builtin_vars())
  710. except SyntaxError as e:
  711. gclient_utils.SyntaxErrorToError(filepath, e)
  712. if 'git_dependencies' in local_scope:
  713. self.git_dependencies_state = local_scope['git_dependencies']
  714. if 'allowed_hosts' in local_scope:
  715. try:
  716. self._allowed_hosts = frozenset(
  717. local_scope.get('allowed_hosts'))
  718. except TypeError: # raised if non-iterable
  719. pass
  720. if not self._allowed_hosts:
  721. logging.warning("allowed_hosts is specified but empty %s",
  722. self._allowed_hosts)
  723. raise gclient_utils.Error(
  724. 'ParseDepsFile(%s): allowed_hosts must be absent '
  725. 'or a non-empty iterable' % self.name)
  726. self._gn_args_from = local_scope.get('gclient_gn_args_from')
  727. self._gn_args_file = local_scope.get('gclient_gn_args_file')
  728. self._gn_args = local_scope.get('gclient_gn_args', [])
  729. # It doesn't make sense to set all of these, since setting gn_args_from
  730. # to another DEPS will make gclient ignore any other local gn_args*
  731. # settings.
  732. assert not (self._gn_args_from and self._gn_args_file), \
  733. 'Only specify one of "gclient_gn_args_from" or ' \
  734. '"gclient_gn_args_file + gclient_gn_args".'
  735. self._vars = local_scope.get('vars', {})
  736. if self.parent:
  737. for key, value in self.parent.get_vars().items():
  738. if key in self._vars:
  739. self._vars[key] = value
  740. # Since we heavily post-process things, freeze ones which should
  741. # reflect original state of DEPS.
  742. self._vars = gclient_utils.freeze(self._vars)
  743. # If use_relative_paths is set in the DEPS file, regenerate
  744. # the dictionary using paths relative to the directory containing
  745. # the DEPS file. Also update recursedeps if use_relative_paths is
  746. # enabled.
  747. # If the deps file doesn't set use_relative_paths, but the parent did
  748. # (and therefore set self.relative on this Dependency object), then we
  749. # want to modify the deps and recursedeps by prepending the parent
  750. # directory of this dependency.
  751. self._use_relative_paths = local_scope.get('use_relative_paths', False)
  752. rel_prefix = None
  753. if self._use_relative_paths:
  754. rel_prefix = self.name
  755. elif self._relative:
  756. rel_prefix = os.path.dirname(self.name)
  757. if 'recursion' in local_scope:
  758. logging.warning('%s: Ignoring recursion = %d.', self.name,
  759. local_scope['recursion'])
  760. if 'recursedeps' in local_scope:
  761. for ent in local_scope['recursedeps']:
  762. if isinstance(ent, str):
  763. self.recursedeps[ent] = self.deps_file
  764. else: # (depname, depsfilename)
  765. self.recursedeps[ent[0]] = ent[1]
  766. logging.warning('Found recursedeps %r.', repr(self.recursedeps))
  767. if rel_prefix:
  768. logging.warning('Updating recursedeps by prepending %s.',
  769. rel_prefix)
  770. rel_deps = {}
  771. for depname, options in self.recursedeps.items():
  772. rel_deps[os.path.normpath(os.path.join(rel_prefix,
  773. depname)).replace(
  774. os.path.sep,
  775. '/')] = options
  776. self.recursedeps = rel_deps
  777. # To get gn_args from another DEPS, that DEPS must be recursed into.
  778. if self._gn_args_from:
  779. assert self.recursedeps and self._gn_args_from in self.recursedeps, \
  780. 'The "gclient_gn_args_from" value must be in recursedeps.'
  781. # If present, save 'target_os' in the local_target_os property.
  782. if 'target_os' in local_scope:
  783. self.local_target_os = local_scope['target_os']
  784. deps = local_scope.get('deps', {})
  785. # If dependencies are configured within git submodules, add them to
  786. # deps. We don't add for SYNC since we expect submodules to be in sync.
  787. if self.git_dependencies_state == gclient_eval.SUBMODULES:
  788. deps.update(self.ParseGitSubmodules())
  789. deps_to_add = self._deps_to_objects(
  790. self._postprocess_deps(deps, rel_prefix), self._use_relative_paths)
  791. # compute which working directory should be used for hooks
  792. if local_scope.get('use_relative_hooks', False):
  793. print('use_relative_hooks is deprecated, please remove it from '
  794. '%s DEPS. (it was merged in use_relative_paths)' % self.name,
  795. file=sys.stderr)
  796. hooks_cwd = self.root.root_dir
  797. if self._use_relative_paths:
  798. hooks_cwd = os.path.join(hooks_cwd, self.name)
  799. elif self._relative:
  800. hooks_cwd = os.path.join(hooks_cwd, os.path.dirname(self.name))
  801. logging.warning('Using hook base working directory: %s.', hooks_cwd)
  802. # Only add all hooks if we should sync, otherwise just add custom hooks.
  803. # override named sets of hooks by the custom hooks
  804. hooks_to_run = []
  805. if self._should_sync:
  806. hook_names_to_suppress = [
  807. c.get('name', '') for c in self.custom_hooks
  808. ]
  809. for hook in local_scope.get('hooks', []):
  810. if hook.get('name', '') not in hook_names_to_suppress:
  811. hooks_to_run.append(hook)
  812. # add the replacements and any additions
  813. for hook in self.custom_hooks:
  814. if 'action' in hook:
  815. hooks_to_run.append(hook)
  816. if self.should_recurse and deps_to_add:
  817. self._pre_deps_hooks = [
  818. Hook.from_dict(hook,
  819. variables=self.get_vars(),
  820. verbose=True,
  821. conditions=self.condition,
  822. cwd_base=hooks_cwd)
  823. for hook in local_scope.get('pre_deps_hooks', [])
  824. ]
  825. self.add_dependencies_and_close(deps_to_add,
  826. hooks_to_run,
  827. hooks_cwd=hooks_cwd)
  828. logging.info('ParseDepsFile(%s) done' % self.name)
  829. def ParseGitSubmodules(self):
  830. # type: () -> Mapping[str, str]
  831. """
  832. Parses git submodules and returns a dict of path to DEPS git url entries.
  833. e.g {<path>: <url>@<commit_hash>}
  834. """
  835. cwd = os.path.join(self.root.root_dir, self.name)
  836. filepath = os.path.join(cwd, '.gitmodules')
  837. if not os.path.isfile(filepath):
  838. logging.warning('ParseGitSubmodules(): No .gitmodules found at %s',
  839. filepath)
  840. return {}
  841. # Get .gitmodules fields
  842. gitmodules_entries = subprocess2.check_output(
  843. ['git', 'config', '--file', filepath, '-l']).decode('utf-8')
  844. gitmodules = {}
  845. for entry in gitmodules_entries.splitlines():
  846. key, value = entry.split('=', maxsplit=1)
  847. # git config keys consist of section.name.key, e.g.,
  848. # submodule.foo.path
  849. section, submodule_key = key.split('.', maxsplit=1)
  850. # Only parse [submodule "foo"] sections from .gitmodules.
  851. if section.strip() != 'submodule':
  852. continue
  853. # The name of the submodule can contain '.', hence split from the
  854. # back.
  855. submodule, sub_key = submodule_key.rsplit('.', maxsplit=1)
  856. if submodule not in gitmodules:
  857. gitmodules[submodule] = {}
  858. if sub_key in ('url', 'gclient-condition', 'path'):
  859. gitmodules[submodule][sub_key] = value
  860. paths = [module['path'] for module in gitmodules.values()]
  861. commit_hashes = scm_git.GIT.GetSubmoduleCommits(cwd, paths)
  862. # Structure git submodules into a dict of DEPS git url entries.
  863. submodules = {}
  864. for module in gitmodules.values():
  865. if self._use_relative_paths:
  866. path = module['path']
  867. else:
  868. path = f'{self.name}/{module["path"]}'
  869. # TODO(crbug.com/1471685): Temporary hack. In case of applied
  870. # patches where the changes are staged but not committed, any
  871. # gitlinks from the patch are not returned by `git ls-tree`. The
  872. # path won't be found in commit_hashes. Use a temporary '0000000'
  873. # value that will be replaced with w/e is found in DEPS later.
  874. submodules[path] = {
  875. 'dep_type':
  876. 'git',
  877. 'url':
  878. '{}@{}'.format(module['url'],
  879. commit_hashes.get(module['path'], '0000000'))
  880. }
  881. if 'gclient-condition' in module:
  882. submodules[path]['condition'] = module['gclient-condition']
  883. return submodules
  884. def _get_option(self, attr, default):
  885. obj = self
  886. while not hasattr(obj, '_options'):
  887. obj = obj.parent
  888. return getattr(obj._options, attr, default)
  889. def add_dependencies_and_close(self, deps_to_add, hooks, hooks_cwd=None):
  890. """Adds the dependencies, hooks and mark the parsing as done."""
  891. if hooks_cwd == None:
  892. hooks_cwd = self.root.root_dir
  893. for dep in deps_to_add:
  894. if dep.verify_validity():
  895. self.add_dependency(dep)
  896. self._mark_as_parsed([
  897. Hook.from_dict(h,
  898. variables=self.get_vars(),
  899. verbose=self.root._options.verbose,
  900. conditions=self.condition,
  901. cwd_base=hooks_cwd) for h in hooks
  902. ])
  903. def findDepsFromNotAllowedHosts(self):
  904. """Returns a list of dependencies from not allowed hosts.
  905. If allowed_hosts is not set, allows all hosts and returns empty list.
  906. """
  907. if not self._allowed_hosts:
  908. return []
  909. bad_deps = []
  910. for dep in self._dependencies:
  911. # Don't enforce this for custom_deps.
  912. if dep.name in self._custom_deps:
  913. continue
  914. if isinstance(dep.url, str):
  915. parsed_url = urllib.parse.urlparse(dep.url)
  916. if parsed_url.netloc and parsed_url.netloc not in self._allowed_hosts:
  917. bad_deps.append(dep)
  918. return bad_deps
  919. def FuzzyMatchUrl(self, candidates):
  920. # type: (Union[Mapping[str, str], Collection[str]]) -> Optional[str]
  921. """Attempts to find this dependency in the list of candidates.
  922. It looks first for the URL of this dependency in the list of
  923. candidates. If it doesn't succeed, and the URL ends in '.git', it will try
  924. looking for the URL minus '.git'. Finally it will try to look for the name
  925. of the dependency.
  926. Args:
  927. candidates: list, dict. The list of candidates in which to look for this
  928. dependency. It can contain URLs as above, or dependency names like
  929. "src/some/dep".
  930. Returns:
  931. If this dependency is not found in the list of candidates, returns None.
  932. Otherwise, it returns under which name did we find this dependency:
  933. - Its parsed url: "https://example.com/src.git'
  934. - Its parsed url minus '.git': "https://example.com/src"
  935. - Its name: "src"
  936. """
  937. if self.url:
  938. origin, _ = gclient_utils.SplitUrlRevision(self.url)
  939. match = gclient_utils.FuzzyMatchRepo(origin, candidates)
  940. if match:
  941. return match
  942. if self.name in candidates:
  943. return self.name
  944. return None
  945. # Arguments number differs from overridden method
  946. # pylint: disable=arguments-differ
  947. def run(
  948. self,
  949. revision_overrides, # type: Mapping[str, str]
  950. command, # type: str
  951. args, # type: Sequence[str]
  952. work_queue, # type: ExecutionQueue
  953. options, # type: optparse.Values
  954. patch_refs, # type: Mapping[str, str]
  955. target_branches, # type: Mapping[str, str]
  956. skip_sync_revisions, # type: Mapping[str, str]
  957. ):
  958. # type: () -> None
  959. """Runs |command| then parse the DEPS file."""
  960. logging.info('Dependency(%s).run()' % self.name)
  961. assert self._file_list == []
  962. # When running runhooks, there's no need to consult the SCM.
  963. # All known hooks are expected to run unconditionally regardless of
  964. # working copy state, so skip the SCM status check.
  965. run_scm = command not in ('flatten', 'runhooks', 'recurse', 'validate',
  966. None)
  967. file_list = [] if not options.nohooks else None
  968. revision_override = revision_overrides.pop(
  969. self.FuzzyMatchUrl(revision_overrides), None)
  970. if not revision_override and not self.managed:
  971. revision_override = 'unmanaged'
  972. if run_scm and self.url:
  973. # Create a shallow copy to mutate revision.
  974. options = copy.copy(options)
  975. options.revision = revision_override
  976. self._used_revision = options.revision
  977. self._used_scm = self.CreateSCM(out_cb=work_queue.out_cb)
  978. if command != 'update' or self.GetScmName() != 'git':
  979. self._got_revision = self._used_scm.RunCommand(
  980. command, options, args, file_list)
  981. else:
  982. try:
  983. start = time.time()
  984. sync_status = metrics_utils.SYNC_STATUS_FAILURE
  985. self._got_revision = self._used_scm.RunCommand(
  986. command, options, args, file_list)
  987. sync_status = metrics_utils.SYNC_STATUS_SUCCESS
  988. finally:
  989. url, revision = gclient_utils.SplitUrlRevision(self.url)
  990. metrics.collector.add_repeated(
  991. 'git_deps', {
  992. 'path': self.name,
  993. 'url': url,
  994. 'revision': revision,
  995. 'execution_time': time.time() - start,
  996. 'sync_status': sync_status,
  997. })
  998. if isinstance(self, GitDependency) and command == 'update':
  999. patch_repo = self.url.split('@')[0]
  1000. patch_ref = patch_refs.pop(self.FuzzyMatchUrl(patch_refs), None)
  1001. target_branch = target_branches.pop(
  1002. self.FuzzyMatchUrl(target_branches), None)
  1003. if patch_ref:
  1004. latest_commit = self._used_scm.apply_patch_ref(
  1005. patch_repo, patch_ref, target_branch, options,
  1006. file_list)
  1007. else:
  1008. latest_commit = self._used_scm.revinfo(None, None, None)
  1009. existing_sync_commits = json.loads(
  1010. os.environ.get(PREVIOUS_SYNC_COMMITS, '{}'))
  1011. existing_sync_commits[self.name] = latest_commit
  1012. os.environ[PREVIOUS_SYNC_COMMITS] = json.dumps(
  1013. existing_sync_commits)
  1014. if file_list:
  1015. file_list = [
  1016. os.path.join(self.name, f.strip()) for f in file_list
  1017. ]
  1018. # TODO(phajdan.jr): We should know exactly when the paths are
  1019. # absolute. Convert all absolute paths to relative.
  1020. for i in range(len(file_list or [])):
  1021. # It depends on the command being executed (like runhooks vs
  1022. # sync).
  1023. if not os.path.isabs(file_list[i]):
  1024. continue
  1025. prefix = os.path.commonprefix(
  1026. [self.root.root_dir.lower(), file_list[i].lower()])
  1027. file_list[i] = file_list[i][len(prefix):]
  1028. # Strip any leading path separators.
  1029. while file_list[i].startswith(('\\', '/')):
  1030. file_list[i] = file_list[i][1:]
  1031. # We must check for diffs AFTER any patch_refs have been applied.
  1032. if skip_sync_revisions:
  1033. skip_sync_rev = skip_sync_revisions.pop(
  1034. self.FuzzyMatchUrl(skip_sync_revisions), None)
  1035. self._should_sync = (skip_sync_rev is None
  1036. or self._used_scm.check_diff(skip_sync_rev,
  1037. files=['DEPS']))
  1038. if not self._should_sync:
  1039. logging.debug(
  1040. 'Skipping sync for %s. No DEPS changes since last '
  1041. 'sync at %s' % (self.name, skip_sync_rev))
  1042. else:
  1043. logging.debug('DEPS changes detected for %s since last sync at '
  1044. '%s. Not skipping deps sync' %
  1045. (self.name, skip_sync_rev))
  1046. if self.should_recurse:
  1047. self.ParseDepsFile()
  1048. self._run_is_done(file_list or [])
  1049. # TODO(crbug.com/1339471): If should_recurse is false, ParseDepsFile
  1050. # never gets called meaning we never fetch hooks and dependencies. So
  1051. # there's no need to check should_recurse again here.
  1052. if self.should_recurse:
  1053. if command in ('update', 'revert') and not options.noprehooks:
  1054. self.RunPreDepsHooks()
  1055. # Parse the dependencies of this dependency.
  1056. for s in self.dependencies:
  1057. if s.should_process:
  1058. work_queue.enqueue(s)
  1059. if command == 'recurse':
  1060. # Skip file only checkout.
  1061. scm = self.GetScmName()
  1062. if not options.scm or scm in options.scm:
  1063. cwd = os.path.normpath(
  1064. os.path.join(self.root.root_dir, self.name))
  1065. # Pass in the SCM type as an env variable. Make sure we don't
  1066. # put unicode strings in the environment.
  1067. env = os.environ.copy()
  1068. if scm:
  1069. env['GCLIENT_SCM'] = str(scm)
  1070. if self.url:
  1071. env['GCLIENT_URL'] = str(self.url)
  1072. env['GCLIENT_DEP_PATH'] = str(self.name)
  1073. if options.prepend_dir and scm == 'git':
  1074. print_stdout = False
  1075. def filter_fn(line):
  1076. """Git-specific path marshaling. It is optimized for git-grep."""
  1077. def mod_path(git_pathspec):
  1078. match = re.match('^(\\S+?:)?([^\0]+)$',
  1079. git_pathspec)
  1080. modified_path = os.path.join(
  1081. self.name, match.group(2))
  1082. branch = match.group(1) or ''
  1083. return '%s%s' % (branch, modified_path)
  1084. match = re.match('^Binary file ([^\0]+) matches$', line)
  1085. if match:
  1086. print('Binary file %s matches\n' %
  1087. mod_path(match.group(1)))
  1088. return
  1089. items = line.split('\0')
  1090. if len(items) == 2 and items[1]:
  1091. print('%s : %s' % (mod_path(items[0]), items[1]))
  1092. elif len(items) >= 2:
  1093. # Multiple null bytes or a single trailing null byte
  1094. # indicate git is likely displaying filenames only
  1095. # (such as with -l)
  1096. print('\n'.join(
  1097. mod_path(path) for path in items if path))
  1098. else:
  1099. print(line)
  1100. else:
  1101. print_stdout = True
  1102. filter_fn = None
  1103. if self.url is None:
  1104. print('Skipped omitted dependency %s' % cwd,
  1105. file=sys.stderr)
  1106. elif os.path.isdir(cwd):
  1107. try:
  1108. gclient_utils.CheckCallAndFilter(
  1109. args,
  1110. cwd=cwd,
  1111. env=env,
  1112. print_stdout=print_stdout,
  1113. filter_fn=filter_fn,
  1114. )
  1115. except subprocess2.CalledProcessError:
  1116. if not options.ignore:
  1117. raise
  1118. else:
  1119. print('Skipped missing %s' % cwd, file=sys.stderr)
  1120. def GetScmName(self):
  1121. raise NotImplementedError()
  1122. def CreateSCM(self, out_cb=None):
  1123. raise NotImplementedError()
  1124. def HasGNArgsFile(self):
  1125. return self._gn_args_file is not None
  1126. def WriteGNArgsFile(self):
  1127. lines = ['# Generated from %r' % self.deps_file]
  1128. variables = self.get_vars()
  1129. for arg in self._gn_args:
  1130. value = variables[arg]
  1131. if isinstance(value, gclient_eval.ConstantString):
  1132. value = value.value
  1133. elif isinstance(value, str):
  1134. value = gclient_eval.EvaluateCondition(value, variables)
  1135. lines.append('%s = %s' % (arg, ToGNString(value)))
  1136. # When use_relative_paths is set, gn_args_file is relative to this DEPS
  1137. path_prefix = self.root.root_dir
  1138. if self._use_relative_paths:
  1139. path_prefix = os.path.join(path_prefix, self.name)
  1140. with open(os.path.join(path_prefix, self._gn_args_file), 'wb') as f:
  1141. f.write('\n'.join(lines).encode('utf-8', 'replace'))
  1142. @gclient_utils.lockedmethod
  1143. def _run_is_done(self, file_list):
  1144. # Both these are kept for hooks that are run as a separate tree
  1145. # traversal.
  1146. self._file_list = file_list
  1147. self._processed = True
  1148. def GetHooks(self, options):
  1149. """Evaluates all hooks, and return them in a flat list.
  1150. RunOnDeps() must have been called before to load the DEPS.
  1151. """
  1152. result = []
  1153. if not self.should_process or not self.should_recurse:
  1154. # Don't run the hook when it is above recursion_limit.
  1155. return result
  1156. # If "--force" was specified, run all hooks regardless of what files
  1157. # have changed.
  1158. if self.deps_hooks:
  1159. # TODO(maruel): If the user is using git, then we don't know
  1160. # what files have changed so we always run all hooks. It'd be nice
  1161. # to fix that.
  1162. result.extend(self.deps_hooks)
  1163. for s in self.dependencies:
  1164. result.extend(s.GetHooks(options))
  1165. return result
  1166. def RunHooksRecursively(self, options, progress):
  1167. assert self.hooks_ran == False
  1168. self._hooks_ran = True
  1169. hooks = self.GetHooks(options)
  1170. if progress:
  1171. progress._total = len(hooks)
  1172. for hook in hooks:
  1173. if progress:
  1174. progress.update(extra=hook.name or '')
  1175. hook.run()
  1176. if progress:
  1177. progress.end()
  1178. def RunPreDepsHooks(self):
  1179. assert self.processed
  1180. assert self.deps_parsed
  1181. assert not self.pre_deps_hooks_ran
  1182. assert not self.hooks_ran
  1183. for s in self.dependencies:
  1184. assert not s.processed
  1185. self._pre_deps_hooks_ran = True
  1186. for hook in self.pre_deps_hooks:
  1187. hook.run()
  1188. def GetCipdRoot(self):
  1189. if self.root is self:
  1190. # Let's not infinitely recurse. If this is root and isn't an
  1191. # instance of GClient, do nothing.
  1192. return None
  1193. return self.root.GetCipdRoot()
  1194. def subtree(self, include_all):
  1195. """Breadth first recursion excluding root node."""
  1196. dependencies = self.dependencies
  1197. for d in dependencies:
  1198. if d.should_process or include_all:
  1199. yield d
  1200. for d in dependencies:
  1201. for i in d.subtree(include_all):
  1202. yield i
  1203. @gclient_utils.lockedmethod
  1204. def add_dependency(self, new_dep):
  1205. self._dependencies.append(new_dep)
  1206. @gclient_utils.lockedmethod
  1207. def _mark_as_parsed(self, new_hooks):
  1208. self._deps_hooks.extend(new_hooks)
  1209. self._deps_parsed = True
  1210. @property
  1211. @gclient_utils.lockedmethod
  1212. def dependencies(self):
  1213. return tuple(self._dependencies)
  1214. @property
  1215. @gclient_utils.lockedmethod
  1216. def deps_hooks(self):
  1217. return tuple(self._deps_hooks)
  1218. @property
  1219. @gclient_utils.lockedmethod
  1220. def pre_deps_hooks(self):
  1221. return tuple(self._pre_deps_hooks)
  1222. @property
  1223. @gclient_utils.lockedmethod
  1224. def deps_parsed(self):
  1225. """This is purely for debugging purposes. It's not used anywhere."""
  1226. return self._deps_parsed
  1227. @property
  1228. @gclient_utils.lockedmethod
  1229. def processed(self):
  1230. return self._processed
  1231. @property
  1232. @gclient_utils.lockedmethod
  1233. def pre_deps_hooks_ran(self):
  1234. return self._pre_deps_hooks_ran
  1235. @property
  1236. @gclient_utils.lockedmethod
  1237. def hooks_ran(self):
  1238. return self._hooks_ran
  1239. @property
  1240. @gclient_utils.lockedmethod
  1241. def allowed_hosts(self):
  1242. return self._allowed_hosts
  1243. @property
  1244. @gclient_utils.lockedmethod
  1245. def file_list(self):
  1246. return tuple(self._file_list)
  1247. @property
  1248. def used_scm(self):
  1249. """SCMWrapper instance for this dependency or None if not processed yet."""
  1250. return self._used_scm
  1251. @property
  1252. @gclient_utils.lockedmethod
  1253. def got_revision(self):
  1254. return self._got_revision
  1255. @property
  1256. def file_list_and_children(self):
  1257. result = list(self.file_list)
  1258. for d in self.dependencies:
  1259. result.extend(d.file_list_and_children)
  1260. return tuple(result)
  1261. def __str__(self):
  1262. out = []
  1263. for i in ('name', 'url', 'custom_deps', 'custom_vars', 'deps_hooks',
  1264. 'file_list', 'should_process', 'processed', 'hooks_ran',
  1265. 'deps_parsed', 'requirements', 'allowed_hosts'):
  1266. # First try the native property if it exists.
  1267. if hasattr(self, '_' + i):
  1268. value = getattr(self, '_' + i, False)
  1269. else:
  1270. value = getattr(self, i, False)
  1271. if value:
  1272. out.append('%s: %s' % (i, value))
  1273. for d in self.dependencies:
  1274. out.extend([' ' + x for x in str(d).splitlines()])
  1275. out.append('')
  1276. return '\n'.join(out)
  1277. def __repr__(self):
  1278. return '%s: %s' % (self.name, self.url)
  1279. def hierarchy(self, include_url=True, graphviz=False):
  1280. """Returns a human-readable hierarchical reference to a Dependency."""
  1281. def format_name(d):
  1282. if include_url:
  1283. return '%s(%s)' % (d.name, d.url)
  1284. return '"%s"' % d.name # quotes required for graph dot file.
  1285. out = format_name(self)
  1286. i = self.parent
  1287. while i and i.name:
  1288. out = '%s -> %s' % (format_name(i), out)
  1289. if graphviz:
  1290. # for graphviz we just need each parent->child relationship
  1291. # listed once.
  1292. return out
  1293. i = i.parent
  1294. return out
  1295. def hierarchy_data(self):
  1296. """Returns a machine-readable hierarchical reference to a Dependency."""
  1297. d = self
  1298. out = []
  1299. while d and d.name:
  1300. out.insert(0, (d.name, d.url))
  1301. d = d.parent
  1302. return tuple(out)
  1303. def get_builtin_vars(self):
  1304. return {
  1305. 'checkout_android': 'android' in self.target_os,
  1306. 'checkout_chromeos': 'chromeos' in self.target_os,
  1307. 'checkout_fuchsia': 'fuchsia' in self.target_os,
  1308. 'checkout_ios': 'ios' in self.target_os,
  1309. 'checkout_linux': 'unix' in self.target_os,
  1310. 'checkout_mac': 'mac' in self.target_os,
  1311. 'checkout_win': 'win' in self.target_os,
  1312. 'host_os': _detect_host_os(),
  1313. 'checkout_arm': 'arm' in self.target_cpu,
  1314. 'checkout_arm64': 'arm64' in self.target_cpu,
  1315. 'checkout_x86': 'x86' in self.target_cpu,
  1316. 'checkout_mips': 'mips' in self.target_cpu,
  1317. 'checkout_mips64': 'mips64' in self.target_cpu,
  1318. 'checkout_ppc': 'ppc' in self.target_cpu,
  1319. 'checkout_s390': 's390' in self.target_cpu,
  1320. 'checkout_x64': 'x64' in self.target_cpu,
  1321. 'host_cpu': detect_host_arch.HostArch(),
  1322. }
  1323. def get_vars(self):
  1324. """Returns a dictionary of effective variable values
  1325. (DEPS file contents with applied custom_vars overrides)."""
  1326. # Variable precedence (last has highest):
  1327. # - DEPS vars
  1328. # - parents, from first to last
  1329. # - built-in
  1330. # - custom_vars overrides
  1331. result = {}
  1332. result.update(self._vars)
  1333. if self.parent:
  1334. merge_vars(result, self.parent.get_vars())
  1335. # Provide some built-in variables.
  1336. result.update(self.get_builtin_vars())
  1337. merge_vars(result, self.custom_vars)
  1338. return result
  1339. _PLATFORM_MAPPING = {
  1340. 'cygwin': 'win',
  1341. 'darwin': 'mac',
  1342. 'linux2': 'linux',
  1343. 'linux': 'linux',
  1344. 'win32': 'win',
  1345. 'aix6': 'aix',
  1346. }
  1347. def merge_vars(result, new_vars):
  1348. for k, v in new_vars.items():
  1349. if k in result:
  1350. if isinstance(result[k], gclient_eval.ConstantString):
  1351. if isinstance(v, gclient_eval.ConstantString):
  1352. result[k] = v
  1353. else:
  1354. result[k].value = v
  1355. else:
  1356. result[k] = v
  1357. else:
  1358. result[k] = v
  1359. def _detect_host_os():
  1360. if sys.platform in _PLATFORM_MAPPING:
  1361. return _PLATFORM_MAPPING[sys.platform]
  1362. try:
  1363. return os.uname().sysname.lower()
  1364. except AttributeError:
  1365. return sys.platform
  1366. class GitDependency(Dependency):
  1367. """A Dependency object that represents a single git checkout."""
  1368. _is_env_cog = None
  1369. @staticmethod
  1370. def _IsCog():
  1371. """Returns true if the env is cog"""
  1372. if GitDependency._is_env_cog is None:
  1373. GitDependency._is_env_cog = os.getcwd().startswith(
  1374. '/google/cog/cloud')
  1375. return GitDependency._is_env_cog
  1376. @staticmethod
  1377. def updateProtocol(url, protocol):
  1378. """Updates given URL's protocol"""
  1379. # only works on urls, skips local paths
  1380. if not url or not protocol or not re.match('([a-z]+)://', url) or \
  1381. re.match('file://', url):
  1382. return url
  1383. return re.sub('^([a-z]+):', protocol + ':', url)
  1384. #override
  1385. def GetScmName(self):
  1386. """Always 'git'."""
  1387. return 'git'
  1388. #override
  1389. def CreateSCM(self, out_cb=None):
  1390. """Create a Wrapper instance suitable for handling this git dependency."""
  1391. if self._IsCog():
  1392. return gclient_scm.CogWrapper()
  1393. return gclient_scm.GitWrapper(self.url,
  1394. self.root.root_dir,
  1395. self.name,
  1396. self.outbuf,
  1397. out_cb,
  1398. print_outbuf=self.print_outbuf)
  1399. class GClient(GitDependency):
  1400. """Object that represent a gclient checkout. A tree of Dependency(), one per
  1401. solution or DEPS entry."""
  1402. DEPS_OS_CHOICES = {
  1403. "aix6": "unix",
  1404. "win32": "win",
  1405. "win": "win",
  1406. "cygwin": "win",
  1407. "darwin": "mac",
  1408. "mac": "mac",
  1409. "unix": "unix",
  1410. "linux": "unix",
  1411. "linux2": "unix",
  1412. "linux3": "unix",
  1413. "android": "android",
  1414. "ios": "ios",
  1415. "fuchsia": "fuchsia",
  1416. "chromeos": "chromeos",
  1417. }
  1418. DEFAULT_CLIENT_FILE_TEXT = ("""\
  1419. solutions = [
  1420. { "name" : %(solution_name)r,
  1421. "url" : %(solution_url)r,
  1422. "deps_file" : %(deps_file)r,
  1423. "managed" : %(managed)r,
  1424. "custom_deps" : {
  1425. },
  1426. "custom_vars": %(custom_vars)r,
  1427. },
  1428. ]
  1429. """)
  1430. DEFAULT_CLIENT_CACHE_DIR_TEXT = ("""\
  1431. cache_dir = %(cache_dir)r
  1432. """)
  1433. DEFAULT_SNAPSHOT_FILE_TEXT = ("""\
  1434. # Snapshot generated with gclient revinfo --snapshot
  1435. solutions = %(solution_list)s
  1436. """)
  1437. def __init__(self, root_dir, options):
  1438. # Do not change previous behavior. Only solution level and immediate
  1439. # DEPS are processed.
  1440. self._recursion_limit = 2
  1441. super(GClient, self).__init__(parent=None,
  1442. name=None,
  1443. url=None,
  1444. managed=True,
  1445. custom_deps=None,
  1446. custom_vars=None,
  1447. custom_hooks=None,
  1448. deps_file='unused',
  1449. should_process=True,
  1450. should_recurse=True,
  1451. relative=None,
  1452. condition=None,
  1453. print_outbuf=True)
  1454. self._options = options
  1455. if options.deps_os:
  1456. enforced_os = options.deps_os.split(',')
  1457. else:
  1458. enforced_os = [self.DEPS_OS_CHOICES.get(sys.platform, 'unix')]
  1459. if 'all' in enforced_os:
  1460. enforced_os = self.DEPS_OS_CHOICES.values()
  1461. self._enforced_os = tuple(set(enforced_os))
  1462. self._enforced_cpu = (detect_host_arch.HostArch(), )
  1463. self._root_dir = root_dir
  1464. self._cipd_root = None
  1465. self.config_content = None
  1466. def _CheckConfig(self):
  1467. """Verify that the config matches the state of the existing checked-out
  1468. solutions."""
  1469. for dep in self.dependencies:
  1470. if dep.managed and dep.url:
  1471. scm = dep.CreateSCM()
  1472. actual_url = scm.GetActualRemoteURL(self._options)
  1473. if actual_url and not scm.DoesRemoteURLMatch(self._options):
  1474. mirror = scm.GetCacheMirror()
  1475. if mirror:
  1476. mirror_string = '%s (exists=%s)' % (mirror.mirror_path,
  1477. mirror.exists())
  1478. else:
  1479. mirror_string = 'not used'
  1480. raise gclient_utils.Error(
  1481. '''
  1482. Your .gclient file seems to be broken. The requested URL is different from what
  1483. is actually checked out in %(checkout_path)s.
  1484. The .gclient file contains:
  1485. URL: %(expected_url)s (%(expected_scm)s)
  1486. Cache mirror: %(mirror_string)s
  1487. The local checkout in %(checkout_path)s reports:
  1488. %(actual_url)s (%(actual_scm)s)
  1489. You should ensure that the URL listed in .gclient is correct and either change
  1490. it or fix the checkout.
  1491. ''' % {
  1492. 'checkout_path': os.path.join(
  1493. self.root_dir, dep.name),
  1494. 'expected_url': dep.url,
  1495. 'expected_scm': dep.GetScmName(),
  1496. 'mirror_string': mirror_string,
  1497. 'actual_url': actual_url,
  1498. 'actual_scm': dep.GetScmName()
  1499. })
  1500. def SetConfig(self, content):
  1501. assert not self.dependencies
  1502. config_dict = {}
  1503. self.config_content = content
  1504. try:
  1505. exec(content, config_dict)
  1506. except SyntaxError as e:
  1507. gclient_utils.SyntaxErrorToError('.gclient', e)
  1508. # Append any target OS that is not already being enforced to the tuple.
  1509. target_os = config_dict.get('target_os', [])
  1510. if config_dict.get('target_os_only', False):
  1511. self._enforced_os = tuple(set(target_os))
  1512. else:
  1513. self._enforced_os = tuple(set(self._enforced_os).union(target_os))
  1514. # Append any target CPU that is not already being enforced to the tuple.
  1515. target_cpu = config_dict.get('target_cpu', [])
  1516. if config_dict.get('target_cpu_only', False):
  1517. self._enforced_cpu = tuple(set(target_cpu))
  1518. else:
  1519. self._enforced_cpu = tuple(
  1520. set(self._enforced_cpu).union(target_cpu))
  1521. cache_dir = config_dict.get('cache_dir', UNSET_CACHE_DIR)
  1522. if cache_dir is not UNSET_CACHE_DIR:
  1523. if cache_dir:
  1524. cache_dir = os.path.join(self.root_dir, cache_dir)
  1525. cache_dir = os.path.abspath(cache_dir)
  1526. git_cache.Mirror.SetCachePath(cache_dir)
  1527. if not target_os and config_dict.get('target_os_only', False):
  1528. raise gclient_utils.Error(
  1529. 'Can\'t use target_os_only if target_os is '
  1530. 'not specified')
  1531. if not target_cpu and config_dict.get('target_cpu_only', False):
  1532. raise gclient_utils.Error(
  1533. 'Can\'t use target_cpu_only if target_cpu is '
  1534. 'not specified')
  1535. deps_to_add = []
  1536. for s in config_dict.get('solutions', []):
  1537. try:
  1538. deps_to_add.append(
  1539. GitDependency(
  1540. parent=self,
  1541. name=s['name'],
  1542. # Update URL with scheme in protocol_override
  1543. url=GitDependency.updateProtocol(
  1544. s['url'], s.get('protocol_override', None)),
  1545. managed=s.get('managed', True),
  1546. custom_deps=s.get('custom_deps', {}),
  1547. custom_vars=s.get('custom_vars', {}),
  1548. custom_hooks=s.get('custom_hooks', []),
  1549. deps_file=s.get('deps_file', 'DEPS'),
  1550. should_process=True,
  1551. should_recurse=True,
  1552. relative=None,
  1553. condition=None,
  1554. print_outbuf=True,
  1555. # Pass protocol_override down the tree for child deps to
  1556. # use.
  1557. protocol=s.get('protocol_override', None),
  1558. git_dependencies_state=self.git_dependencies_state))
  1559. except KeyError:
  1560. raise gclient_utils.Error('Invalid .gclient file. Solution is '
  1561. 'incomplete: %s' % s)
  1562. metrics.collector.add('project_urls', [
  1563. dep.FuzzyMatchUrl(metrics_utils.KNOWN_PROJECT_URLS)
  1564. for dep in deps_to_add
  1565. if dep.FuzzyMatchUrl(metrics_utils.KNOWN_PROJECT_URLS)
  1566. ])
  1567. self.add_dependencies_and_close(deps_to_add,
  1568. config_dict.get('hooks', []))
  1569. logging.info('SetConfig() done')
  1570. def SaveConfig(self):
  1571. gclient_utils.FileWrite(
  1572. os.path.join(self.root_dir, self._options.config_filename),
  1573. self.config_content)
  1574. @staticmethod
  1575. def LoadCurrentConfig(options):
  1576. # type: (optparse.Values) -> GClient
  1577. """Searches for and loads a .gclient file relative to the current working
  1578. dir."""
  1579. if options.spec:
  1580. client = GClient('.', options)
  1581. client.SetConfig(options.spec)
  1582. else:
  1583. if options.verbose:
  1584. print('Looking for %s starting from %s\n' %
  1585. (options.config_filename, os.getcwd()))
  1586. path = gclient_paths.FindGclientRoot(os.getcwd(),
  1587. options.config_filename)
  1588. if not path:
  1589. if options.verbose:
  1590. print('Couldn\'t find configuration file.')
  1591. return None
  1592. client = GClient(path, options)
  1593. client.SetConfig(
  1594. gclient_utils.FileRead(
  1595. os.path.join(path, options.config_filename)))
  1596. if (options.revisions and len(client.dependencies) > 1
  1597. and any('@' not in r for r in options.revisions)):
  1598. print((
  1599. 'You must specify the full solution name like --revision %s@%s\n'
  1600. 'when you have multiple solutions setup in your .gclient file.\n'
  1601. 'Other solutions present are: %s.') %
  1602. (client.dependencies[0].name, options.revisions[0], ', '.join(
  1603. s.name for s in client.dependencies[1:])),
  1604. file=sys.stderr)
  1605. return client
  1606. def SetDefaultConfig(self,
  1607. solution_name,
  1608. deps_file,
  1609. solution_url,
  1610. managed=True,
  1611. cache_dir=UNSET_CACHE_DIR,
  1612. custom_vars=None):
  1613. text = self.DEFAULT_CLIENT_FILE_TEXT
  1614. format_dict = {
  1615. 'solution_name': solution_name,
  1616. 'solution_url': solution_url,
  1617. 'deps_file': deps_file,
  1618. 'managed': managed,
  1619. 'custom_vars': custom_vars or {},
  1620. }
  1621. if cache_dir is not UNSET_CACHE_DIR:
  1622. text += self.DEFAULT_CLIENT_CACHE_DIR_TEXT
  1623. format_dict['cache_dir'] = cache_dir
  1624. self.SetConfig(text % format_dict)
  1625. def _SaveEntries(self):
  1626. """Creates a .gclient_entries file to record the list of unique checkouts.
  1627. The .gclient_entries file lives in the same directory as .gclient.
  1628. """
  1629. # Sometimes pprint.pformat will use {', sometimes it'll use { ' ... It
  1630. # makes testing a bit too fun.
  1631. result = 'entries = {\n'
  1632. for entry in self.root.subtree(False):
  1633. result += ' %s: %s,\n' % (pprint.pformat(
  1634. entry.name), pprint.pformat(entry.url))
  1635. result += '}\n'
  1636. file_path = os.path.join(self.root_dir, self._options.entries_filename)
  1637. logging.debug(result)
  1638. gclient_utils.FileWrite(file_path, result)
  1639. def _ReadEntries(self):
  1640. """Read the .gclient_entries file for the given client.
  1641. Returns:
  1642. A sequence of solution names, which will be empty if there is the
  1643. entries file hasn't been created yet.
  1644. """
  1645. scope = {}
  1646. filename = os.path.join(self.root_dir, self._options.entries_filename)
  1647. if not os.path.exists(filename):
  1648. return {}
  1649. try:
  1650. exec(gclient_utils.FileRead(filename), scope)
  1651. except SyntaxError as e:
  1652. gclient_utils.SyntaxErrorToError(filename, e)
  1653. return scope.get('entries', {})
  1654. def _ExtractFileJsonContents(self, default_filename):
  1655. # type: (str) -> Mapping[str,Any]
  1656. f = os.path.join(self.root_dir, default_filename)
  1657. if not os.path.exists(f):
  1658. logging.info('File %s does not exist.' % f)
  1659. return {}
  1660. with open(f, 'r') as open_f:
  1661. logging.info('Reading content from file %s' % f)
  1662. content = open_f.read().rstrip()
  1663. if content:
  1664. return json.loads(content)
  1665. return {}
  1666. def _WriteFileContents(self, default_filename, content):
  1667. # type: (str, str) -> None
  1668. f = os.path.join(self.root_dir, default_filename)
  1669. with open(f, 'w') as open_f:
  1670. logging.info('Writing to file %s' % f)
  1671. open_f.write(content)
  1672. def _EnforceSkipSyncRevisions(self, patch_refs):
  1673. # type: (Mapping[str, str]) -> Mapping[str, str]
  1674. """Checks for and enforces revisions for skipping deps syncing."""
  1675. previous_sync_commits = self._ExtractFileJsonContents(
  1676. PREVIOUS_SYNC_COMMITS_FILE)
  1677. if not previous_sync_commits:
  1678. return {}
  1679. # Current `self.dependencies` only contain solutions. If a patch_ref is
  1680. # not for a solution, then it is for a solution's dependency or recursed
  1681. # dependency which we cannot support while skipping sync.
  1682. if patch_refs:
  1683. unclaimed_prs = []
  1684. candidates = []
  1685. for dep in self.dependencies:
  1686. origin, _ = gclient_utils.SplitUrlRevision(dep.url)
  1687. candidates.extend([origin, dep.name])
  1688. for patch_repo in patch_refs:
  1689. if not gclient_utils.FuzzyMatchRepo(patch_repo, candidates):
  1690. unclaimed_prs.append(patch_repo)
  1691. if unclaimed_prs:
  1692. print(
  1693. 'We cannot skip syncs when there are --patch-refs flags for '
  1694. 'non-solution dependencies. To skip syncing, remove patch_refs '
  1695. 'for: \n%s' % '\n'.join(unclaimed_prs))
  1696. return {}
  1697. # We cannot skip syncing if there are custom_vars that differ from the
  1698. # previous run's custom_vars.
  1699. previous_custom_vars = self._ExtractFileJsonContents(
  1700. PREVIOUS_CUSTOM_VARS_FILE)
  1701. cvs_by_name = {s.name: s.custom_vars for s in self.dependencies}
  1702. skip_sync_revisions = {}
  1703. for name, commit in previous_sync_commits.items():
  1704. previous_vars = previous_custom_vars.get(name)
  1705. if previous_vars == cvs_by_name.get(name) or (
  1706. not previous_vars and not cvs_by_name.get(name)):
  1707. skip_sync_revisions[name] = commit
  1708. else:
  1709. print(
  1710. 'We cannot skip syncs when custom_vars for solutions have '
  1711. 'changed since the last sync run on this machine.\n'
  1712. '\nRemoving skip_sync_revision for:\n'
  1713. 'solution: %s, current: %r, previous: %r.' %
  1714. (name, cvs_by_name.get(name), previous_vars))
  1715. print('no-sync experiment enabled with %r' % skip_sync_revisions)
  1716. return skip_sync_revisions
  1717. # TODO(crbug.com/1340695): Remove handling revisions without '@'.
  1718. def _EnforceRevisions(self):
  1719. """Checks for revision overrides."""
  1720. revision_overrides = {}
  1721. if self._options.head:
  1722. return revision_overrides
  1723. if not self._options.revisions:
  1724. return revision_overrides
  1725. solutions_names = [s.name for s in self.dependencies]
  1726. for index, revision in enumerate(self._options.revisions):
  1727. if not '@' in revision:
  1728. # Support for --revision 123
  1729. revision = '%s@%s' % (solutions_names[index], revision)
  1730. name, rev = revision.split('@', 1)
  1731. revision_overrides[name] = rev
  1732. return revision_overrides
  1733. def _EnforcePatchRefsAndBranches(self):
  1734. # type: () -> Tuple[Mapping[str, str], Mapping[str, str]]
  1735. """Checks for patch refs."""
  1736. patch_refs = {}
  1737. target_branches = {}
  1738. if not self._options.patch_refs:
  1739. return patch_refs, target_branches
  1740. for given_patch_ref in self._options.patch_refs:
  1741. patch_repo, _, patch_ref = given_patch_ref.partition('@')
  1742. if not patch_repo or not patch_ref or ':' not in patch_ref:
  1743. raise gclient_utils.Error(
  1744. 'Wrong revision format: %s should be of the form '
  1745. 'patch_repo@target_branch:patch_ref.' % given_patch_ref)
  1746. target_branch, _, patch_ref = patch_ref.partition(':')
  1747. target_branches[patch_repo] = target_branch
  1748. patch_refs[patch_repo] = patch_ref
  1749. return patch_refs, target_branches
  1750. def _InstallPreCommitHook(self):
  1751. # On Windows, this path is written to the file as
  1752. # "dir\hooks\pre-commit.py" but it gets interpreted as
  1753. # "dirhookspre-commit.py".
  1754. gclient_hook_path = os.path.join(DEPOT_TOOLS_DIR, 'hooks',
  1755. 'pre-commit.py').replace('\\', '\\\\')
  1756. gclient_hook_content = '\n'.join((
  1757. f'{PRECOMMIT_HOOK_VAR}={gclient_hook_path}',
  1758. f'if [ -f "${PRECOMMIT_HOOK_VAR}" ]; then',
  1759. f' python3 "${PRECOMMIT_HOOK_VAR}" || exit 1',
  1760. 'fi',
  1761. ))
  1762. soln = gclient_paths.GetPrimarySolutionPath()
  1763. if not soln:
  1764. print('Could not find gclient solution.')
  1765. return
  1766. git_dir = os.path.join(soln, '.git')
  1767. if not os.path.exists(git_dir):
  1768. return
  1769. git_hooks_dir = os.path.join(git_dir, 'hooks')
  1770. os.makedirs(git_hooks_dir, exist_ok=True)
  1771. hook = os.path.join(git_dir, 'hooks', 'pre-commit')
  1772. if os.path.exists(hook):
  1773. with open(hook, 'r') as f:
  1774. content = f.read()
  1775. if PRECOMMIT_HOOK_VAR in content:
  1776. print(f'{hook} already contains the gclient pre-commit hook.')
  1777. else:
  1778. print(f'A pre-commit hook already exists at {hook}.\n'
  1779. f'Please append the following lines to the hook:\n\n'
  1780. f'{gclient_hook_content}')
  1781. return
  1782. print(f'Creating a pre-commit hook at {hook}')
  1783. with open(hook, 'w') as f:
  1784. f.write('#!/bin/sh\n')
  1785. f.write(f'{gclient_hook_content}\n')
  1786. os.chmod(hook, 0o755)
  1787. def _RemoveUnversionedGitDirs(self):
  1788. """Remove directories that are no longer part of the checkout.
  1789. Notify the user if there is an orphaned entry in their working copy.
  1790. Only delete the directory if there are no changes in it, and
  1791. delete_unversioned_trees is set to true.
  1792. Returns CIPD packages that are no longer versioned.
  1793. """
  1794. entry_names_and_sync = [(i.name, i._should_sync)
  1795. for i in self.root.subtree(False) if i.url]
  1796. entries = []
  1797. if entry_names_and_sync:
  1798. entries, _ = zip(*entry_names_and_sync)
  1799. full_entries = [
  1800. os.path.join(self.root_dir, e.replace('/', os.path.sep))
  1801. for e in entries
  1802. ]
  1803. no_sync_entries = [
  1804. name for name, should_sync in entry_names_and_sync
  1805. if not should_sync
  1806. ]
  1807. removed_cipd_entries = []
  1808. read_entries = self._ReadEntries()
  1809. # We process entries sorted in reverse to ensure a child dir is
  1810. # always deleted before its parent dir.
  1811. # This is especially important for submodules with pinned revisions
  1812. # overwritten by a vars or custom_deps. In this case, if a parent
  1813. # submodule is encountered first in the loop, it cannot tell the
  1814. # difference between modifications from the vars or actual user
  1815. # modifications that should be kept. http://crbug/1486677#c9 for
  1816. # more details.
  1817. for entry in sorted(read_entries, reverse=True):
  1818. prev_url = read_entries[entry]
  1819. if not prev_url:
  1820. # entry must have been overridden via .gclient custom_deps
  1821. continue
  1822. if any(entry.startswith(sln) for sln in no_sync_entries):
  1823. # Dependencies of solutions that skipped syncing would not
  1824. # show up in `entries`.
  1825. continue
  1826. if (':' in entry):
  1827. # This is a cipd package. Don't clean it up, but prepare for
  1828. # return
  1829. if entry not in entries:
  1830. removed_cipd_entries.append(entry)
  1831. continue
  1832. # Fix path separator on Windows.
  1833. entry_fixed = entry.replace('/', os.path.sep)
  1834. e_dir = os.path.join(self.root_dir, entry_fixed)
  1835. # Use entry and not entry_fixed there.
  1836. if (entry not in entries and
  1837. (not any(path.startswith(entry + '/') for path in entries))
  1838. and os.path.exists(e_dir)):
  1839. # The entry has been removed from DEPS.
  1840. scm = gclient_scm.GitWrapper(prev_url, self.root_dir,
  1841. entry_fixed, self.outbuf)
  1842. # Check to see if this directory is now part of a higher-up
  1843. # checkout.
  1844. scm_root = None
  1845. try:
  1846. scm_root = gclient_scm.scm.GIT.GetCheckoutRoot(
  1847. scm.checkout_path)
  1848. except subprocess2.CalledProcessError:
  1849. pass
  1850. if not scm_root:
  1851. logging.warning(
  1852. 'Could not find checkout root for %s. Unable to '
  1853. 'determine whether it is part of a higher-level '
  1854. 'checkout, so not removing.' % entry)
  1855. continue
  1856. versioned_state = None
  1857. # Check if this is a submodule or versioned directory.
  1858. if os.path.abspath(scm_root) == os.path.abspath(e_dir):
  1859. e_par_dir = os.path.join(e_dir, os.pardir)
  1860. if gclient_scm.scm.GIT.IsInsideWorkTree(e_par_dir):
  1861. par_scm_root = gclient_scm.scm.GIT.GetCheckoutRoot(
  1862. e_par_dir)
  1863. # rel_e_dir : relative path of entry w.r.t. its parent
  1864. # repo.
  1865. rel_e_dir = os.path.relpath(e_dir, par_scm_root)
  1866. versioned_state = gclient_scm.scm.GIT.IsVersioned(
  1867. par_scm_root, rel_e_dir)
  1868. # This is to handle the case of third_party/WebKit migrating
  1869. # from being a DEPS entry to being part of the main project. If
  1870. # the subproject is a Git project, we need to remove its .git
  1871. # folder. Otherwise git operations on that folder will have
  1872. # different effects depending on the current working directory.
  1873. if versioned_state == gclient_scm.scm.VERSIONED_DIR:
  1874. save_dir = scm.GetGitBackupDirPath()
  1875. # Remove any eventual stale backup dir for the same
  1876. # project.
  1877. if os.path.exists(save_dir):
  1878. gclient_utils.rmtree(save_dir)
  1879. os.rename(os.path.join(e_dir, '.git'), save_dir)
  1880. # When switching between the two states (entry/ is a
  1881. # subproject -> entry/ is part of the outer
  1882. # project), it is very likely that some files are
  1883. # changed in the checkout, unless we are jumping
  1884. # *exactly* across the commit which changed just
  1885. # DEPS. In such case we want to cleanup any eventual
  1886. # stale files (coming from the old subproject) in
  1887. # order to end up with a clean checkout.
  1888. gclient_scm.scm.GIT.CleanupDir(
  1889. par_scm_root, rel_e_dir)
  1890. assert not os.path.exists(
  1891. os.path.join(e_dir, '.git'))
  1892. print(
  1893. '\nWARNING: \'%s\' has been moved from DEPS to a higher '
  1894. 'level checkout. The git folder containing all the local'
  1895. ' branches has been saved to %s.\n'
  1896. 'If you don\'t care about its state you can safely '
  1897. 'remove that folder to free up space.' %
  1898. (entry, save_dir))
  1899. continue
  1900. if scm_root in full_entries:
  1901. logging.info(
  1902. '%s is part of a higher level checkout, not removing',
  1903. scm.GetCheckoutRoot())
  1904. continue
  1905. file_list = []
  1906. scm.status(self._options, [], file_list)
  1907. modified_files = file_list != []
  1908. if (not self._options.delete_unversioned_trees
  1909. or (modified_files and not self._options.force)):
  1910. # There are modified files in this entry. Keep warning until
  1911. # removed.
  1912. self.add_dependency(
  1913. GitDependency(
  1914. parent=self,
  1915. name=entry,
  1916. # Update URL with scheme in protocol_override
  1917. url=GitDependency.updateProtocol(
  1918. prev_url, self.protocol),
  1919. managed=False,
  1920. custom_deps={},
  1921. custom_vars={},
  1922. custom_hooks=[],
  1923. deps_file=None,
  1924. should_process=True,
  1925. should_recurse=False,
  1926. relative=None,
  1927. condition=None,
  1928. protocol=self.protocol,
  1929. git_dependencies_state=self.git_dependencies_state))
  1930. if modified_files and self._options.delete_unversioned_trees:
  1931. print(
  1932. '\nWARNING: \'%s\' is no longer part of this client.\n'
  1933. 'Despite running \'gclient sync -D\' no action was taken '
  1934. 'as there are modifications.\nIt is recommended you revert '
  1935. 'all changes or run \'gclient sync -D --force\' next '
  1936. 'time.' % entry_fixed)
  1937. else:
  1938. print(
  1939. '\nWARNING: \'%s\' is no longer part of this client.\n'
  1940. 'It is recommended that you manually remove it or use '
  1941. '\'gclient sync -D\' next time.' % entry_fixed)
  1942. else:
  1943. # Delete the entry
  1944. print('\n________ deleting \'%s\' in \'%s\'' %
  1945. (entry_fixed, self.root_dir))
  1946. gclient_utils.rmtree(e_dir)
  1947. # We restore empty directories of submodule paths.
  1948. if versioned_state == gclient_scm.scm.VERSIONED_SUBMODULE:
  1949. gclient_scm.scm.GIT.Capture(
  1950. ['restore', '--', rel_e_dir], cwd=par_scm_root)
  1951. # record the current list of entries for next time
  1952. self._SaveEntries()
  1953. return removed_cipd_entries
  1954. def RunOnDeps(self,
  1955. command,
  1956. args,
  1957. ignore_requirements=False,
  1958. progress=True):
  1959. """Runs a command on each dependency in a client and its dependencies.
  1960. Args:
  1961. command: The command to use (e.g., 'status' or 'diff')
  1962. args: list of str - extra arguments to add to the command line.
  1963. """
  1964. if not self.dependencies:
  1965. raise gclient_utils.Error('No solution specified')
  1966. revision_overrides = {}
  1967. patch_refs = {}
  1968. target_branches = {}
  1969. skip_sync_revisions = {}
  1970. # It's unnecessary to check for revision overrides for 'recurse'.
  1971. # Save a few seconds by not calling _EnforceRevisions() in that case.
  1972. if command not in ('diff', 'recurse', 'runhooks', 'status', 'revert',
  1973. 'validate'):
  1974. self._CheckConfig()
  1975. revision_overrides = self._EnforceRevisions()
  1976. if command == 'update':
  1977. patch_refs, target_branches = self._EnforcePatchRefsAndBranches()
  1978. if NO_SYNC_EXPERIMENT in self._options.experiments:
  1979. skip_sync_revisions = self._EnforceSkipSyncRevisions(patch_refs)
  1980. # Store solutions' custom_vars on memory to compare in the next run.
  1981. # All dependencies added later are inherited from the current
  1982. # self.dependencies.
  1983. custom_vars = {
  1984. dep.name: dep.custom_vars
  1985. for dep in self.dependencies if dep.custom_vars
  1986. }
  1987. if custom_vars:
  1988. self._WriteFileContents(PREVIOUS_CUSTOM_VARS_FILE,
  1989. json.dumps(custom_vars))
  1990. # Disable progress for non-tty stdout.
  1991. should_show_progress = (setup_color.IS_TTY and not self._options.verbose
  1992. and progress)
  1993. pm = None
  1994. if should_show_progress:
  1995. if command in ('update', 'revert'):
  1996. pm = Progress('Syncing projects', 1)
  1997. elif command in ('recurse', 'validate'):
  1998. pm = Progress(' '.join(args), 1)
  1999. work_queue = gclient_utils.ExecutionQueue(
  2000. self._options.jobs,
  2001. pm,
  2002. ignore_requirements=ignore_requirements,
  2003. verbose=self._options.verbose)
  2004. for s in self.dependencies:
  2005. if s.should_process:
  2006. work_queue.enqueue(s)
  2007. work_queue.flush(revision_overrides,
  2008. command,
  2009. args,
  2010. options=self._options,
  2011. patch_refs=patch_refs,
  2012. target_branches=target_branches,
  2013. skip_sync_revisions=skip_sync_revisions)
  2014. if revision_overrides:
  2015. print(
  2016. 'Please fix your script, having invalid --revision flags will soon '
  2017. 'be considered an error.',
  2018. file=sys.stderr)
  2019. if patch_refs:
  2020. raise gclient_utils.Error(
  2021. 'The following --patch-ref flags were not used. Please fix it:\n%s'
  2022. % ('\n'.join(patch_repo + '@' + patch_ref
  2023. for patch_repo, patch_ref in patch_refs.items())))
  2024. # TODO(crbug.com/1475405): Warn users if the project uses submodules and
  2025. # they have fsmonitor enabled.
  2026. if command == 'update':
  2027. # Check if any of the root dependency have submodules.
  2028. is_submoduled = any(
  2029. map(
  2030. lambda d: d.git_dependencies_state in
  2031. (gclient_eval.SUBMODULES, gclient_eval.SYNC),
  2032. self.dependencies))
  2033. if is_submoduled:
  2034. git_common.warn_submodule()
  2035. # Once all the dependencies have been processed, it's now safe to write
  2036. # out the gn_args_file and run the hooks.
  2037. removed_cipd_entries = []
  2038. if command == 'update':
  2039. for dependency in self.dependencies:
  2040. gn_args_dep = dependency
  2041. if gn_args_dep._gn_args_from:
  2042. deps_map = {
  2043. dep.name: dep
  2044. for dep in gn_args_dep.dependencies
  2045. }
  2046. gn_args_dep = deps_map.get(gn_args_dep._gn_args_from)
  2047. if gn_args_dep and gn_args_dep.HasGNArgsFile():
  2048. gn_args_dep.WriteGNArgsFile()
  2049. removed_cipd_entries = self._RemoveUnversionedGitDirs()
  2050. # Sync CIPD dependencies once removed deps are deleted. In case a git
  2051. # dependency was moved to CIPD, we want to remove the old git directory
  2052. # first and then sync the CIPD dep.
  2053. if self._cipd_root:
  2054. self._cipd_root.run(command)
  2055. # It's possible that CIPD removed some entries that are now part of
  2056. # git worktree. Try to checkout those directories
  2057. if removed_cipd_entries:
  2058. for cipd_entry in removed_cipd_entries:
  2059. cwd = os.path.join(self._root_dir, cipd_entry.split(':')[0])
  2060. cwd, tail = os.path.split(cwd)
  2061. if cwd:
  2062. try:
  2063. gclient_scm.scm.GIT.Capture(['checkout', tail],
  2064. cwd=cwd)
  2065. except (subprocess2.CalledProcessError, OSError):
  2066. # repo of the deleted cipd may also have been deleted.
  2067. pass
  2068. if not self._options.nohooks:
  2069. if should_show_progress:
  2070. pm = Progress('Running hooks', 1)
  2071. self.RunHooksRecursively(self._options, pm)
  2072. self._WriteFileContents(PREVIOUS_SYNC_COMMITS_FILE,
  2073. os.environ.get(PREVIOUS_SYNC_COMMITS, '{}'))
  2074. return 0
  2075. def PrintRevInfo(self):
  2076. if not self.dependencies:
  2077. raise gclient_utils.Error('No solution specified')
  2078. # Load all the settings.
  2079. work_queue = gclient_utils.ExecutionQueue(self._options.jobs,
  2080. None,
  2081. False,
  2082. verbose=self._options.verbose)
  2083. for s in self.dependencies:
  2084. if s.should_process:
  2085. work_queue.enqueue(s)
  2086. work_queue.flush({},
  2087. None, [],
  2088. options=self._options,
  2089. patch_refs=None,
  2090. target_branches=None,
  2091. skip_sync_revisions=None)
  2092. def ShouldPrintRevision(dep):
  2093. return (not self._options.filter
  2094. or dep.FuzzyMatchUrl(self._options.filter))
  2095. if self._options.snapshot:
  2096. json_output = []
  2097. # First level at .gclient
  2098. for d in self.dependencies:
  2099. entries = {}
  2100. def GrabDeps(dep):
  2101. """Recursively grab dependencies."""
  2102. for rec_d in dep.dependencies:
  2103. rec_d.PinToActualRevision()
  2104. if ShouldPrintRevision(rec_d):
  2105. entries[rec_d.name] = rec_d.url
  2106. GrabDeps(rec_d)
  2107. GrabDeps(d)
  2108. json_output.append({
  2109. 'name': d.name,
  2110. 'solution_url': d.url,
  2111. 'deps_file': d.deps_file,
  2112. 'managed': d.managed,
  2113. 'custom_deps': entries,
  2114. })
  2115. if self._options.output_json == '-':
  2116. print(json.dumps(json_output, indent=2, separators=(',', ': ')))
  2117. elif self._options.output_json:
  2118. with open(self._options.output_json, 'w') as f:
  2119. json.dump(json_output, f)
  2120. else:
  2121. # Print the snapshot configuration file
  2122. print(self.DEFAULT_SNAPSHOT_FILE_TEXT % {
  2123. 'solution_list': pprint.pformat(json_output, indent=2),
  2124. })
  2125. else:
  2126. entries = {}
  2127. for d in self.root.subtree(False):
  2128. if self._options.actual:
  2129. d.PinToActualRevision()
  2130. if ShouldPrintRevision(d):
  2131. entries[d.name] = d.url
  2132. if self._options.output_json:
  2133. json_output = {
  2134. name: {
  2135. 'url': rev.split('@')[0] if rev else None,
  2136. 'rev':
  2137. rev.split('@')[1] if rev and '@' in rev else None,
  2138. }
  2139. for name, rev in entries.items()
  2140. }
  2141. if self._options.output_json == '-':
  2142. print(
  2143. json.dumps(json_output,
  2144. indent=2,
  2145. separators=(',', ': ')))
  2146. else:
  2147. with open(self._options.output_json, 'w') as f:
  2148. json.dump(json_output, f)
  2149. else:
  2150. keys = sorted(entries.keys())
  2151. for x in keys:
  2152. print('%s: %s' % (x, entries[x]))
  2153. logging.info(str(self))
  2154. def ParseDepsFile(self):
  2155. """No DEPS to parse for a .gclient file."""
  2156. raise gclient_utils.Error('Internal error')
  2157. def PrintLocationAndContents(self):
  2158. # Print out the .gclient file. This is longer than if we just printed
  2159. # the client dict, but more legible, and it might contain helpful
  2160. # comments.
  2161. print('Loaded .gclient config in %s:\n%s' %
  2162. (self.root_dir, self.config_content))
  2163. def GetCipdRoot(self):
  2164. if not self._cipd_root:
  2165. self._cipd_root = gclient_scm.CipdRoot(
  2166. self.root_dir,
  2167. # TODO(jbudorick): Support other service URLs as necessary.
  2168. # Service URLs should be constant over the scope of a cipd
  2169. # root, so a var per DEPS file specifying the service URL
  2170. # should suffice.
  2171. 'https://chrome-infra-packages.appspot.com',
  2172. log_level='info' if self._options.verbose else None)
  2173. return self._cipd_root
  2174. @property
  2175. def root_dir(self):
  2176. """Root directory of gclient checkout."""
  2177. return self._root_dir
  2178. @property
  2179. def enforced_os(self):
  2180. """What deps_os entries that are to be parsed."""
  2181. return self._enforced_os
  2182. @property
  2183. def target_os(self):
  2184. return self._enforced_os
  2185. @property
  2186. def target_cpu(self):
  2187. return self._enforced_cpu
  2188. class CipdDependency(Dependency):
  2189. """A Dependency object that represents a single CIPD package."""
  2190. def __init__(self, parent, name, dep_value, cipd_root, custom_vars,
  2191. should_process, relative, condition):
  2192. package = dep_value['package']
  2193. version = dep_value['version']
  2194. url = urllib.parse.urljoin(cipd_root.service_url,
  2195. '%s@%s' % (package, version))
  2196. super(CipdDependency, self).__init__(parent=parent,
  2197. name=name + ':' + package,
  2198. url=url,
  2199. managed=None,
  2200. custom_deps=None,
  2201. custom_vars=custom_vars,
  2202. custom_hooks=None,
  2203. deps_file=None,
  2204. should_process=should_process,
  2205. should_recurse=False,
  2206. relative=relative,
  2207. condition=condition)
  2208. self._cipd_package = None
  2209. self._cipd_root = cipd_root
  2210. # CIPD wants /-separated paths, even on Windows.
  2211. native_subdir_path = os.path.relpath(
  2212. os.path.join(self.root.root_dir, name), cipd_root.root_dir)
  2213. self._cipd_subdir = posixpath.join(*native_subdir_path.split(os.sep))
  2214. self._package_name = package
  2215. self._package_version = version
  2216. #override
  2217. def run(self, revision_overrides, command, args, work_queue, options,
  2218. patch_refs, target_branches, skip_sync_revisions):
  2219. """Runs |command| then parse the DEPS file."""
  2220. logging.info('CipdDependency(%s).run()' % self.name)
  2221. if not self.should_process:
  2222. return
  2223. self._CreatePackageIfNecessary()
  2224. super(CipdDependency,
  2225. self).run(revision_overrides, command, args, work_queue, options,
  2226. patch_refs, target_branches, skip_sync_revisions)
  2227. def _CreatePackageIfNecessary(self):
  2228. # We lazily create the CIPD package to make sure that only packages
  2229. # that we want (as opposed to all packages defined in all DEPS files
  2230. # we parse) get added to the root and subsequently ensured.
  2231. if not self._cipd_package:
  2232. self._cipd_package = self._cipd_root.add_package(
  2233. self._cipd_subdir, self._package_name, self._package_version)
  2234. def ParseDepsFile(self):
  2235. """CIPD dependencies are not currently allowed to have nested deps."""
  2236. self.add_dependencies_and_close([], [])
  2237. #override
  2238. def verify_validity(self):
  2239. """CIPD dependencies allow duplicate name for packages in same directory."""
  2240. logging.info('Dependency(%s).verify_validity()' % self.name)
  2241. return True
  2242. #override
  2243. def GetScmName(self):
  2244. """Always 'cipd'."""
  2245. return 'cipd'
  2246. def GetExpandedPackageName(self):
  2247. """Return the CIPD package name with the variables evaluated."""
  2248. package = self._cipd_root.expand_package_name(self._package_name)
  2249. if package:
  2250. return package
  2251. return self._package_name
  2252. #override
  2253. def CreateSCM(self, out_cb=None):
  2254. """Create a Wrapper instance suitable for handling this CIPD dependency."""
  2255. self._CreatePackageIfNecessary()
  2256. return gclient_scm.CipdWrapper(self.url,
  2257. self.root.root_dir,
  2258. self.name,
  2259. self.outbuf,
  2260. out_cb,
  2261. root=self._cipd_root,
  2262. package=self._cipd_package)
  2263. def hierarchy(self, include_url=False, graphviz=False):
  2264. if graphviz:
  2265. return '' # graphviz lines not implemented for cipd deps.
  2266. return self.parent.hierarchy(include_url) + ' -> ' + self._cipd_subdir
  2267. def ToLines(self):
  2268. # () -> Sequence[str]
  2269. """Return a list of lines representing this in a DEPS file."""
  2270. def escape_cipd_var(package):
  2271. return package.replace('{', '{{').replace('}', '}}')
  2272. s = []
  2273. self._CreatePackageIfNecessary()
  2274. if self._cipd_package.authority_for_subdir:
  2275. condition_part = ([' "condition": %r,' %
  2276. self.condition] if self.condition else [])
  2277. s.extend([
  2278. ' # %s' % self.hierarchy(include_url=False),
  2279. ' "%s": {' % (self.name.split(':')[0], ),
  2280. ' "packages": [',
  2281. ])
  2282. for p in sorted(self._cipd_root.packages(self._cipd_subdir),
  2283. key=lambda x: x.name):
  2284. s.extend([
  2285. ' {',
  2286. ' "package": "%s",' % escape_cipd_var(p.name),
  2287. ' "version": "%s",' % p.version,
  2288. ' },',
  2289. ])
  2290. s.extend([
  2291. ' ],',
  2292. ' "dep_type": "cipd",',
  2293. ] + condition_part + [
  2294. ' },',
  2295. '',
  2296. ])
  2297. return s
  2298. #### gclient commands.
  2299. @subcommand.usage('[command] [args ...]')
  2300. @metrics.collector.collect_metrics('gclient recurse')
  2301. def CMDrecurse(parser, args):
  2302. """Operates [command args ...] on all the dependencies.
  2303. Change directory to each dependency's directory, and call [command
  2304. args ...] there. Sets GCLIENT_DEP_PATH environment variable as the
  2305. dep's relative location to root directory of the checkout.
  2306. Examples:
  2307. * `gclient recurse --no-progress -j1 sh -c 'echo "$GCLIENT_DEP_PATH"'`
  2308. print the relative path of each dependency.
  2309. * `gclient recurse --no-progress -j1 sh -c "pwd"`
  2310. print the absolute path of each dependency.
  2311. """
  2312. # Stop parsing at the first non-arg so that these go through to the command
  2313. parser.disable_interspersed_args()
  2314. parser.add_option('-s',
  2315. '--scm',
  2316. action='append',
  2317. default=[],
  2318. help='Choose scm types to operate upon.')
  2319. parser.add_option('-i',
  2320. '--ignore',
  2321. action='store_true',
  2322. help='Ignore non-zero return codes from subcommands.')
  2323. parser.add_option(
  2324. '--prepend-dir',
  2325. action='store_true',
  2326. help='Prepend relative dir for use with git <cmd> --null.')
  2327. parser.add_option(
  2328. '--no-progress',
  2329. action='store_true',
  2330. help='Disable progress bar that shows sub-command updates')
  2331. options, args = parser.parse_args(args)
  2332. if not args:
  2333. print('Need to supply a command!', file=sys.stderr)
  2334. return 1
  2335. root_and_entries = gclient_utils.GetGClientRootAndEntries()
  2336. if not root_and_entries:
  2337. print(
  2338. 'You need to run gclient sync at least once to use \'recurse\'.\n'
  2339. 'This is because .gclient_entries needs to exist and be up to date.',
  2340. file=sys.stderr)
  2341. return 1
  2342. # Normalize options.scm to a set()
  2343. scm_set = set()
  2344. for scm in options.scm:
  2345. scm_set.update(scm.split(','))
  2346. options.scm = scm_set
  2347. options.nohooks = True
  2348. client = GClient.LoadCurrentConfig(options)
  2349. if not client:
  2350. raise gclient_utils.Error(
  2351. 'client not configured; see \'gclient config\'')
  2352. return client.RunOnDeps('recurse',
  2353. args,
  2354. ignore_requirements=True,
  2355. progress=not options.no_progress)
  2356. @subcommand.usage('[args ...]')
  2357. @metrics.collector.collect_metrics('gclient fetch')
  2358. def CMDfetch(parser, args):
  2359. """Fetches upstream commits for all modules.
  2360. Completely git-specific. Simply runs 'git fetch [args ...]' for each module.
  2361. """
  2362. (options, args) = parser.parse_args(args)
  2363. return CMDrecurse(
  2364. OptionParser(),
  2365. ['--jobs=%d' % options.jobs, '--scm=git', 'git', 'fetch'] + args)
  2366. class Flattener(object):
  2367. """Flattens a gclient solution."""
  2368. def __init__(self, client, pin_all_deps=False):
  2369. """Constructor.
  2370. Arguments:
  2371. client (GClient): client to flatten
  2372. pin_all_deps (bool): whether to pin all deps, even if they're not pinned
  2373. in DEPS
  2374. """
  2375. self._client = client
  2376. self._deps_string = None
  2377. self._deps_graph_lines = None
  2378. self._deps_files = set()
  2379. self._allowed_hosts = set()
  2380. self._deps = {}
  2381. self._hooks = []
  2382. self._pre_deps_hooks = []
  2383. self._vars = {}
  2384. self._flatten(pin_all_deps=pin_all_deps)
  2385. @property
  2386. def deps_string(self):
  2387. assert self._deps_string is not None
  2388. return self._deps_string
  2389. @property
  2390. def deps_graph_lines(self):
  2391. assert self._deps_graph_lines is not None
  2392. return self._deps_graph_lines
  2393. @property
  2394. def deps_files(self):
  2395. return self._deps_files
  2396. def _pin_dep(self, dep):
  2397. """Pins a dependency to specific full revision sha.
  2398. Arguments:
  2399. dep (Dependency): dependency to process
  2400. """
  2401. if dep.url is None:
  2402. return
  2403. # Make sure the revision is always fully specified (a hash),
  2404. # as opposed to refs or tags which might change. Similarly,
  2405. # shortened shas might become ambiguous; make sure to always
  2406. # use full one for pinning.
  2407. revision = gclient_utils.SplitUrlRevision(dep.url)[1]
  2408. if not revision or not gclient_utils.IsFullGitSha(revision):
  2409. dep.PinToActualRevision()
  2410. def _flatten(self, pin_all_deps=False):
  2411. """Runs the flattener. Saves resulting DEPS string.
  2412. Arguments:
  2413. pin_all_deps (bool): whether to pin all deps, even if they're not pinned
  2414. in DEPS
  2415. """
  2416. for solution in self._client.dependencies:
  2417. self._add_dep(solution)
  2418. self._flatten_dep(solution)
  2419. if pin_all_deps:
  2420. for dep in self._deps.values():
  2421. self._pin_dep(dep)
  2422. def add_deps_file(dep):
  2423. # Only include DEPS files referenced by recursedeps.
  2424. if not dep.should_recurse:
  2425. return
  2426. deps_file = dep.deps_file
  2427. deps_path = os.path.join(self._client.root_dir, dep.name, deps_file)
  2428. if not os.path.exists(deps_path):
  2429. # gclient has a fallback that if deps_file doesn't exist, it'll
  2430. # try DEPS. Do the same here.
  2431. deps_file = 'DEPS'
  2432. deps_path = os.path.join(self._client.root_dir, dep.name,
  2433. deps_file)
  2434. if not os.path.exists(deps_path):
  2435. return
  2436. assert dep.url
  2437. self._deps_files.add((dep.url, deps_file, dep.hierarchy_data()))
  2438. for dep in self._deps.values():
  2439. add_deps_file(dep)
  2440. gn_args_dep = self._deps.get(self._client.dependencies[0]._gn_args_from,
  2441. self._client.dependencies[0])
  2442. self._deps_graph_lines = _DepsToDotGraphLines(self._deps)
  2443. self._deps_string = '\n'.join(
  2444. _GNSettingsToLines(gn_args_dep._gn_args_file, gn_args_dep._gn_args)
  2445. + _AllowedHostsToLines(self._allowed_hosts) +
  2446. _DepsToLines(self._deps) + _HooksToLines('hooks', self._hooks) +
  2447. _HooksToLines('pre_deps_hooks', self._pre_deps_hooks) +
  2448. _VarsToLines(self._vars) + [
  2449. '# %s, %s' % (url, deps_file)
  2450. for url, deps_file, _ in sorted(self._deps_files)
  2451. ] + ['']) # Ensure newline at end of file.
  2452. def _add_dep(self, dep):
  2453. """Helper to add a dependency to flattened DEPS.
  2454. Arguments:
  2455. dep (Dependency): dependency to add
  2456. """
  2457. assert dep.name not in self._deps or self._deps.get(
  2458. dep.name) == dep, (dep.name, self._deps.get(dep.name))
  2459. if dep.url:
  2460. self._deps[dep.name] = dep
  2461. def _flatten_dep(self, dep):
  2462. """Visits a dependency in order to flatten it (see CMDflatten).
  2463. Arguments:
  2464. dep (Dependency): dependency to process
  2465. """
  2466. logging.debug('_flatten_dep(%s)', dep.name)
  2467. assert dep.deps_parsed, (
  2468. "Attempted to flatten %s but it has not been processed." % dep.name)
  2469. self._allowed_hosts.update(dep.allowed_hosts)
  2470. # Only include vars explicitly listed in the DEPS files or gclient
  2471. # solution, not automatic, local overrides (i.e. not all of
  2472. # dep.get_vars()).
  2473. hierarchy = dep.hierarchy(include_url=False)
  2474. for key, value in dep._vars.items():
  2475. # Make sure there are no conflicting variables. It is fine however
  2476. # to use same variable name, as long as the value is consistent.
  2477. assert key not in self._vars or self._vars[key][1] == value, (
  2478. "dep:%s key:%s value:%s != %s" %
  2479. (dep.name, key, value, self._vars[key][1]))
  2480. self._vars[key] = (hierarchy, value)
  2481. # Override explicit custom variables.
  2482. for key, value in dep.custom_vars.items():
  2483. # Do custom_vars that don't correspond to DEPS vars ever make sense?
  2484. # DEPS conditionals shouldn't be using vars that aren't also defined
  2485. # in the DEPS (presubmit actually disallows this), so any new
  2486. # custom_var must be unused in the DEPS, so no need to add it to the
  2487. # flattened output either.
  2488. if key not in self._vars:
  2489. continue
  2490. # Don't "override" existing vars if it's actually the same value.
  2491. if self._vars[key][1] == value:
  2492. continue
  2493. # Anything else is overriding a default value from the DEPS.
  2494. self._vars[key] = (hierarchy + ' [custom_var override]', value)
  2495. self._pre_deps_hooks.extend([(dep, hook)
  2496. for hook in dep.pre_deps_hooks])
  2497. self._hooks.extend([(dep, hook) for hook in dep.deps_hooks])
  2498. for sub_dep in dep.dependencies:
  2499. self._add_dep(sub_dep)
  2500. for d in dep.dependencies:
  2501. if d.should_recurse:
  2502. self._flatten_dep(d)
  2503. @metrics.collector.collect_metrics('gclient gitmodules')
  2504. def CMDgitmodules(parser, args):
  2505. """Adds or updates Git Submodules based on the contents of the DEPS file.
  2506. This command should be run in the root directory of the repo.
  2507. It will create or update the .gitmodules file and include
  2508. `gclient-condition` values. Commits in gitlinks will also be updated.
  2509. """
  2510. parser.add_option('--output-gitmodules',
  2511. help='name of the .gitmodules file to write to',
  2512. default='.gitmodules')
  2513. parser.add_option(
  2514. '--deps-file',
  2515. help=
  2516. 'name of the deps file to parse for git dependency paths and commits.',
  2517. default='DEPS')
  2518. parser.add_option(
  2519. '--skip-dep',
  2520. action="append",
  2521. help='skip adding gitmodules for the git dependency at the given path',
  2522. default=[])
  2523. options, args = parser.parse_args(args)
  2524. deps_dir = os.path.dirname(os.path.abspath(options.deps_file))
  2525. gclient_path = gclient_paths.FindGclientRoot(deps_dir)
  2526. if not gclient_path:
  2527. logging.error(
  2528. '.gclient not found\n'
  2529. 'Make sure you are running this script from a gclient workspace.')
  2530. sys.exit(1)
  2531. deps_content = gclient_utils.FileRead(options.deps_file)
  2532. ls = gclient_eval.Parse(deps_content, options.deps_file, None, None)
  2533. prefix_length = 0
  2534. if not 'use_relative_paths' in ls or ls['use_relative_paths'] != True:
  2535. delta_path = os.path.relpath(deps_dir, os.path.abspath(gclient_path))
  2536. if delta_path:
  2537. prefix_length = len(delta_path.replace(os.path.sep, '/')) + 1
  2538. cache_info = []
  2539. # Git submodules shouldn't use .git suffix since it's not well supported.
  2540. # However, we can't update .gitmodules files since there is no guarantee
  2541. # that user has the latest version of depot_tools, and also they are not on
  2542. # some old branch which contains already contains submodules with .git.
  2543. # This check makes the transition easier.
  2544. strip_git_suffix = True
  2545. if os.path.exists(options.output_gitmodules):
  2546. dot_git_pattern = re.compile('^(\s*)url(\s*)=.*\.git$')
  2547. with open(options.output_gitmodules) as f:
  2548. strip_git_suffix = not any(dot_git_pattern.match(l) for l in f)
  2549. with open(options.output_gitmodules, 'w', newline='') as f:
  2550. for path, dep in ls.get('deps').items():
  2551. if path in options.skip_dep:
  2552. continue
  2553. if dep.get('dep_type') == 'cipd':
  2554. continue
  2555. try:
  2556. url, commit = dep['url'].split('@', maxsplit=1)
  2557. except ValueError:
  2558. logging.error('error on %s; %s, not adding it', path,
  2559. dep["url"])
  2560. continue
  2561. if prefix_length:
  2562. path = path[prefix_length:]
  2563. if strip_git_suffix:
  2564. if url.endswith('.git'):
  2565. url = url[:-4] # strip .git
  2566. url = url.rstrip('/') # remove trailing slash for consistency
  2567. cache_info += ['--cacheinfo', f'160000,{commit},{path}']
  2568. f.write(f'[submodule "{path}"]\n\tpath = {path}\n\turl = {url}\n')
  2569. if 'condition' in dep:
  2570. f.write(f'\tgclient-condition = {dep["condition"]}\n')
  2571. # Windows has limit how long, so let's chunk those calls.
  2572. if len(cache_info) >= 100:
  2573. subprocess2.call(['git', 'update-index', '--add'] + cache_info)
  2574. cache_info = []
  2575. if cache_info:
  2576. subprocess2.call(['git', 'update-index', '--add'] + cache_info)
  2577. subprocess2.call(['git', 'add', '.gitmodules'])
  2578. print('.gitmodules and gitlinks updated. Please check `git diff --staged`'
  2579. 'and commit those staged changes (`git commit` without -a)')
  2580. @metrics.collector.collect_metrics('gclient flatten')
  2581. def CMDflatten(parser, args):
  2582. """Flattens the solutions into a single DEPS file."""
  2583. parser.add_option('--output-deps', help='Path to the output DEPS file')
  2584. parser.add_option(
  2585. '--output-deps-files',
  2586. help=('Path to the output metadata about DEPS files referenced by '
  2587. 'recursedeps.'))
  2588. parser.add_option(
  2589. '--pin-all-deps',
  2590. action='store_true',
  2591. help=('Pin all deps, even if not pinned in DEPS. CAVEAT: only does so '
  2592. 'for checked out deps, NOT deps_os.'))
  2593. parser.add_option('--deps-graph-file',
  2594. help='Provide a path for the output graph file')
  2595. options, args = parser.parse_args(args)
  2596. options.nohooks = True
  2597. options.process_all_deps = True
  2598. client = GClient.LoadCurrentConfig(options)
  2599. if not client:
  2600. raise gclient_utils.Error(
  2601. 'client not configured; see \'gclient config\'')
  2602. # Only print progress if we're writing to a file. Otherwise, progress
  2603. # updates could obscure intended output.
  2604. code = client.RunOnDeps('flatten', args, progress=options.output_deps)
  2605. if code != 0:
  2606. return code
  2607. flattener = Flattener(client, pin_all_deps=options.pin_all_deps)
  2608. if options.output_deps:
  2609. with open(options.output_deps, 'w') as f:
  2610. f.write(flattener.deps_string)
  2611. else:
  2612. print(flattener.deps_string)
  2613. if options.deps_graph_file:
  2614. with open(options.deps_graph_file, 'w') as f:
  2615. f.write('\n'.join(flattener.deps_graph_lines))
  2616. deps_files = [{
  2617. 'url': d[0],
  2618. 'deps_file': d[1],
  2619. 'hierarchy': d[2]
  2620. } for d in sorted(flattener.deps_files)]
  2621. if options.output_deps_files:
  2622. with open(options.output_deps_files, 'w') as f:
  2623. json.dump(deps_files, f)
  2624. return 0
  2625. def _GNSettingsToLines(gn_args_file, gn_args):
  2626. s = []
  2627. if gn_args_file:
  2628. s.extend([
  2629. 'gclient_gn_args_file = "%s"' % gn_args_file,
  2630. 'gclient_gn_args = %r' % gn_args,
  2631. ])
  2632. return s
  2633. def _AllowedHostsToLines(allowed_hosts):
  2634. """Converts |allowed_hosts| set to list of lines for output."""
  2635. if not allowed_hosts:
  2636. return []
  2637. s = ['allowed_hosts = [']
  2638. for h in sorted(allowed_hosts):
  2639. s.append(' "%s",' % h)
  2640. s.extend([']', ''])
  2641. return s
  2642. def _DepsToLines(deps):
  2643. # type: (Mapping[str, Dependency]) -> Sequence[str]
  2644. """Converts |deps| dict to list of lines for output."""
  2645. if not deps:
  2646. return []
  2647. s = ['deps = {']
  2648. for _, dep in sorted(deps.items()):
  2649. s.extend(dep.ToLines())
  2650. s.extend(['}', ''])
  2651. return s
  2652. def _DepsToDotGraphLines(deps):
  2653. # type: (Mapping[str, Dependency]) -> Sequence[str]
  2654. """Converts |deps| dict to list of lines for dot graphs"""
  2655. if not deps:
  2656. return []
  2657. graph_lines = ["digraph {\n\trankdir=\"LR\";"]
  2658. for _, dep in sorted(deps.items()):
  2659. line = dep.hierarchy(include_url=False, graphviz=True)
  2660. if line:
  2661. graph_lines.append("\t%s" % line)
  2662. graph_lines.append("}")
  2663. return graph_lines
  2664. def _DepsOsToLines(deps_os):
  2665. """Converts |deps_os| dict to list of lines for output."""
  2666. if not deps_os:
  2667. return []
  2668. s = ['deps_os = {']
  2669. for dep_os, os_deps in sorted(deps_os.items()):
  2670. s.append(' "%s": {' % dep_os)
  2671. for name, dep in sorted(os_deps.items()):
  2672. condition_part = ([' "condition": %r,' %
  2673. dep.condition] if dep.condition else [])
  2674. s.extend([
  2675. ' # %s' % dep.hierarchy(include_url=False),
  2676. ' "%s": {' % (name, ),
  2677. ' "url": "%s",' % (dep.url, ),
  2678. ] + condition_part + [
  2679. ' },',
  2680. '',
  2681. ])
  2682. s.extend([' },', ''])
  2683. s.extend(['}', ''])
  2684. return s
  2685. def _HooksToLines(name, hooks):
  2686. """Converts |hooks| list to list of lines for output."""
  2687. if not hooks:
  2688. return []
  2689. s = ['%s = [' % name]
  2690. for dep, hook in hooks:
  2691. s.extend([
  2692. ' # %s' % dep.hierarchy(include_url=False),
  2693. ' {',
  2694. ])
  2695. if hook.name is not None:
  2696. s.append(' "name": "%s",' % hook.name)
  2697. if hook.pattern is not None:
  2698. s.append(' "pattern": "%s",' % hook.pattern)
  2699. if hook.condition is not None:
  2700. s.append(' "condition": %r,' % hook.condition)
  2701. # Flattened hooks need to be written relative to the root gclient dir
  2702. cwd = os.path.relpath(os.path.normpath(hook.effective_cwd))
  2703. s.extend([' "cwd": "%s",' % cwd] + [' "action": ['] +
  2704. [' "%s",' % arg
  2705. for arg in hook.action] + [' ]', ' },', ''])
  2706. s.extend([']', ''])
  2707. return s
  2708. def _HooksOsToLines(hooks_os):
  2709. """Converts |hooks| list to list of lines for output."""
  2710. if not hooks_os:
  2711. return []
  2712. s = ['hooks_os = {']
  2713. for hook_os, os_hooks in hooks_os.items():
  2714. s.append(' "%s": [' % hook_os)
  2715. for dep, hook in os_hooks:
  2716. s.extend([
  2717. ' # %s' % dep.hierarchy(include_url=False),
  2718. ' {',
  2719. ])
  2720. if hook.name is not None:
  2721. s.append(' "name": "%s",' % hook.name)
  2722. if hook.pattern is not None:
  2723. s.append(' "pattern": "%s",' % hook.pattern)
  2724. if hook.condition is not None:
  2725. s.append(' "condition": %r,' % hook.condition)
  2726. # Flattened hooks need to be written relative to the root gclient
  2727. # dir
  2728. cwd = os.path.relpath(os.path.normpath(hook.effective_cwd))
  2729. s.extend([' "cwd": "%s",' % cwd] + [' "action": ['] +
  2730. [' "%s",' % arg
  2731. for arg in hook.action] + [' ]', ' },', ''])
  2732. s.extend([' ],', ''])
  2733. s.extend(['}', ''])
  2734. return s
  2735. def _VarsToLines(variables):
  2736. """Converts |variables| dict to list of lines for output."""
  2737. if not variables:
  2738. return []
  2739. s = ['vars = {']
  2740. for key, tup in sorted(variables.items()):
  2741. hierarchy, value = tup
  2742. s.extend([
  2743. ' # %s' % hierarchy,
  2744. ' "%s": %r,' % (key, value),
  2745. '',
  2746. ])
  2747. s.extend(['}', ''])
  2748. return s
  2749. @metrics.collector.collect_metrics('gclient grep')
  2750. def CMDgrep(parser, args):
  2751. """Greps through git repos managed by gclient.
  2752. Runs 'git grep [args...]' for each module.
  2753. """
  2754. # We can't use optparse because it will try to parse arguments sent
  2755. # to git grep and throw an error. :-(
  2756. if not args or re.match('(-h|--help)$', args[0]):
  2757. print(
  2758. 'Usage: gclient grep [-j <N>] git-grep-args...\n\n'
  2759. 'Example: "gclient grep -j10 -A2 RefCountedBase" runs\n"git grep '
  2760. '-A2 RefCountedBase" on each of gclient\'s git\nrepos with up to '
  2761. '10 jobs.\n\nBonus: page output by appending "|& less -FRSX" to the'
  2762. ' end of your query.',
  2763. file=sys.stderr)
  2764. return 1
  2765. jobs_arg = ['--jobs=1']
  2766. if re.match(r'(-j|--jobs=)\d+$', args[0]):
  2767. jobs_arg, args = args[:1], args[1:]
  2768. elif re.match(r'(-j|--jobs)$', args[0]):
  2769. jobs_arg, args = args[:2], args[2:]
  2770. return CMDrecurse(
  2771. parser, jobs_arg + [
  2772. '--ignore', '--prepend-dir', '--no-progress', '--scm=git', 'git',
  2773. 'grep', '--null', '--color=Always'
  2774. ] + args)
  2775. @metrics.collector.collect_metrics('gclient root')
  2776. def CMDroot(parser, args):
  2777. """Outputs the solution root (or current dir if there isn't one)."""
  2778. (options, args) = parser.parse_args(args)
  2779. client = GClient.LoadCurrentConfig(options)
  2780. if client:
  2781. print(os.path.abspath(client.root_dir))
  2782. else:
  2783. print(os.path.abspath('.'))
  2784. @subcommand.usage('[url]')
  2785. @metrics.collector.collect_metrics('gclient config')
  2786. def CMDconfig(parser, args):
  2787. """Creates a .gclient file in the current directory.
  2788. This specifies the configuration for further commands. After update/sync,
  2789. top-level DEPS files in each module are read to determine dependent
  2790. modules to operate on as well. If optional [url] parameter is
  2791. provided, then configuration is read from a specified Subversion server
  2792. URL.
  2793. """
  2794. # We do a little dance with the --gclientfile option. 'gclient config' is
  2795. # the only command where it's acceptable to have both '--gclientfile' and
  2796. # '--spec' arguments. So, we temporarily stash any --gclientfile parameter
  2797. # into options.output_config_file until after the (gclientfile xor spec)
  2798. # error check.
  2799. parser.remove_option('--gclientfile')
  2800. parser.add_option('--gclientfile',
  2801. dest='output_config_file',
  2802. help='Specify an alternate .gclient file')
  2803. parser.add_option('--name',
  2804. help='overrides the default name for the solution')
  2805. parser.add_option(
  2806. '--deps-file',
  2807. default='DEPS',
  2808. help='overrides the default name for the DEPS file for the '
  2809. 'main solutions and all sub-dependencies')
  2810. parser.add_option('--unmanaged',
  2811. action='store_true',
  2812. default=False,
  2813. help='overrides the default behavior to make it possible '
  2814. 'to have the main solution untouched by gclient '
  2815. '(gclient will check out unmanaged dependencies but '
  2816. 'will never sync them)')
  2817. parser.add_option('--cache-dir',
  2818. default=UNSET_CACHE_DIR,
  2819. help='Cache all git repos into this dir and do shared '
  2820. 'clones from the cache, instead of cloning directly '
  2821. 'from the remote. Pass "None" to disable cache, even '
  2822. 'if globally enabled due to $GIT_CACHE_PATH.')
  2823. parser.add_option('--custom-var',
  2824. action='append',
  2825. dest='custom_vars',
  2826. default=[],
  2827. help='overrides variables; key=value syntax')
  2828. parser.set_defaults(config_filename=None)
  2829. (options, args) = parser.parse_args(args)
  2830. if options.output_config_file:
  2831. setattr(options, 'config_filename',
  2832. getattr(options, 'output_config_file'))
  2833. if ((options.spec and args) or len(args) > 2
  2834. or (not options.spec and not args)):
  2835. parser.error(
  2836. 'Inconsistent arguments. Use either --spec or one or 2 args')
  2837. if (options.cache_dir is not UNSET_CACHE_DIR
  2838. and options.cache_dir.lower() == 'none'):
  2839. options.cache_dir = None
  2840. custom_vars = {}
  2841. for arg in options.custom_vars:
  2842. kv = arg.split('=', 1)
  2843. if len(kv) != 2:
  2844. parser.error('Invalid --custom-var argument: %r' % arg)
  2845. custom_vars[kv[0]] = gclient_eval.EvaluateCondition(kv[1], {})
  2846. client = GClient('.', options)
  2847. if options.spec:
  2848. client.SetConfig(options.spec)
  2849. else:
  2850. base_url = args[0].rstrip('/')
  2851. if not options.name:
  2852. name = base_url.split('/')[-1]
  2853. if name.endswith('.git'):
  2854. name = name[:-4]
  2855. else:
  2856. # specify an alternate relpath for the given URL.
  2857. name = options.name
  2858. if not os.path.abspath(os.path.join(os.getcwd(), name)).startswith(
  2859. os.getcwd()):
  2860. parser.error('Do not pass a relative path for --name.')
  2861. if any(x in ('..', '.', '/', '\\') for x in name.split(os.sep)):
  2862. parser.error(
  2863. 'Do not include relative path components in --name.')
  2864. deps_file = options.deps_file
  2865. client.SetDefaultConfig(name,
  2866. deps_file,
  2867. base_url,
  2868. managed=not options.unmanaged,
  2869. cache_dir=options.cache_dir,
  2870. custom_vars=custom_vars)
  2871. client.SaveConfig()
  2872. return 0
  2873. @subcommand.epilog("""Example:
  2874. gclient pack > patch.txt
  2875. generate simple patch for configured client and dependences
  2876. """)
  2877. @metrics.collector.collect_metrics('gclient pack')
  2878. def CMDpack(parser, args):
  2879. """Generates a patch which can be applied at the root of the tree.
  2880. Internally, runs 'git diff' on each checked out module and
  2881. dependencies, and performs minimal postprocessing of the output. The
  2882. resulting patch is printed to stdout and can be applied to a freshly
  2883. checked out tree via 'patch -p0 < patchfile'.
  2884. """
  2885. parser.add_option('--deps',
  2886. dest='deps_os',
  2887. metavar='OS_LIST',
  2888. help='override deps for the specified (comma-separated) '
  2889. 'platform(s); \'all\' will process all deps_os '
  2890. 'references')
  2891. parser.remove_option('--jobs')
  2892. (options, args) = parser.parse_args(args)
  2893. # Force jobs to 1 so the stdout is not annotated with the thread ids
  2894. options.jobs = 1
  2895. client = GClient.LoadCurrentConfig(options)
  2896. if not client:
  2897. raise gclient_utils.Error(
  2898. 'client not configured; see \'gclient config\'')
  2899. if options.verbose:
  2900. client.PrintLocationAndContents()
  2901. return client.RunOnDeps('pack', args)
  2902. @metrics.collector.collect_metrics('gclient status')
  2903. def CMDstatus(parser, args):
  2904. """Shows modification status for every dependencies."""
  2905. parser.add_option('--deps',
  2906. dest='deps_os',
  2907. metavar='OS_LIST',
  2908. help='override deps for the specified (comma-separated) '
  2909. 'platform(s); \'all\' will process all deps_os '
  2910. 'references')
  2911. (options, args) = parser.parse_args(args)
  2912. client = GClient.LoadCurrentConfig(options)
  2913. if not client:
  2914. raise gclient_utils.Error(
  2915. 'client not configured; see \'gclient config\'')
  2916. if options.verbose:
  2917. client.PrintLocationAndContents()
  2918. return client.RunOnDeps('status', args)
  2919. @subcommand.epilog("""Examples:
  2920. gclient sync
  2921. update files from SCM according to current configuration,
  2922. *for modules which have changed since last update or sync*
  2923. gclient sync --force
  2924. update files from SCM according to current configuration, for
  2925. all modules (useful for recovering files deleted from local copy)
  2926. gclient sync --revision src@GIT_COMMIT_OR_REF
  2927. update src directory to GIT_COMMIT_OR_REF
  2928. JSON output format:
  2929. If the --output-json option is specified, the following document structure will
  2930. be emitted to the provided file. 'null' entries may occur for subprojects which
  2931. are present in the gclient solution, but were not processed (due to custom_deps,
  2932. os_deps, etc.)
  2933. {
  2934. "solutions" : {
  2935. "<name>": { # <name> is the posix-normalized path to the solution.
  2936. "revision": [<git id hex string>|null],
  2937. "scm": ["git"|null],
  2938. }
  2939. }
  2940. }
  2941. """)
  2942. @metrics.collector.collect_metrics('gclient sync')
  2943. def CMDsync(parser, args):
  2944. """Checkout/update all modules."""
  2945. parser.add_option('-f',
  2946. '--force',
  2947. action='store_true',
  2948. help='force update even for unchanged modules')
  2949. parser.add_option('-n',
  2950. '--nohooks',
  2951. action='store_true',
  2952. help='don\'t run hooks after the update is complete')
  2953. parser.add_option('-p',
  2954. '--noprehooks',
  2955. action='store_true',
  2956. help='don\'t run pre-DEPS hooks',
  2957. default=False)
  2958. parser.add_option('-r',
  2959. '--revision',
  2960. action='append',
  2961. dest='revisions',
  2962. metavar='REV',
  2963. default=[],
  2964. help='Enforces git ref/hash for the solutions with the '
  2965. 'format src@rev. The src@ part is optional and can be '
  2966. 'skipped. You can also specify URLs instead of paths '
  2967. 'and gclient will find the solution corresponding to '
  2968. 'the given URL. If a path is also specified, the URL '
  2969. 'takes precedence. -r can be used multiple times when '
  2970. '.gclient has multiple solutions configured, and will '
  2971. 'work even if the src@ part is skipped. Revision '
  2972. 'numbers (e.g. 31000 or r31000) are not supported.')
  2973. parser.add_option('--patch-ref',
  2974. action='append',
  2975. dest='patch_refs',
  2976. metavar='GERRIT_REF',
  2977. default=[],
  2978. help='Patches the given reference with the format '
  2979. 'dep@target-ref:patch-ref. '
  2980. 'For |dep|, you can specify URLs as well as paths, '
  2981. 'with URLs taking preference. '
  2982. '|patch-ref| will be applied to |dep|, rebased on top '
  2983. 'of what |dep| was synced to, and a soft reset will '
  2984. 'be done. Use --no-rebase-patch-ref and '
  2985. '--no-reset-patch-ref to disable this behavior. '
  2986. '|target-ref| is the target branch against which a '
  2987. 'patch was created, it is used to determine which '
  2988. 'commits from the |patch-ref| actually constitute a '
  2989. 'patch.')
  2990. parser.add_option(
  2991. '-t',
  2992. '--download-topics',
  2993. action='store_true',
  2994. help='Downloads and patches locally changes from all open '
  2995. 'Gerrit CLs that have the same topic as the changes '
  2996. 'in the specified patch_refs. Only works if atleast '
  2997. 'one --patch-ref is specified.')
  2998. parser.add_option('--with_branch_heads',
  2999. action='store_true',
  3000. help='Clone git "branch_heads" refspecs in addition to '
  3001. 'the default refspecs. This adds about 1/2GB to a '
  3002. 'full checkout. (git only)')
  3003. parser.add_option(
  3004. '--with_tags',
  3005. action='store_true',
  3006. help='Clone git tags in addition to the default refspecs.')
  3007. parser.add_option('-H',
  3008. '--head',
  3009. action='store_true',
  3010. help='DEPRECATED: only made sense with safesync urls.')
  3011. parser.add_option(
  3012. '-D',
  3013. '--delete_unversioned_trees',
  3014. action='store_true',
  3015. help='Deletes from the working copy any dependencies that '
  3016. 'have been removed since the last sync, as long as '
  3017. 'there are no local modifications. When used with '
  3018. '--force, such dependencies are removed even if they '
  3019. 'have local modifications. When used with --reset, '
  3020. 'all untracked directories are removed from the '
  3021. 'working copy, excluding those which are explicitly '
  3022. 'ignored in the repository.')
  3023. parser.add_option(
  3024. '-R',
  3025. '--reset',
  3026. action='store_true',
  3027. help='resets any local changes before updating (git only)')
  3028. parser.add_option('-M',
  3029. '--merge',
  3030. action='store_true',
  3031. help='merge upstream changes instead of trying to '
  3032. 'fast-forward or rebase')
  3033. parser.add_option('-A',
  3034. '--auto_rebase',
  3035. action='store_true',
  3036. help='Automatically rebase repositories against local '
  3037. 'checkout during update (git only).')
  3038. parser.add_option('--deps',
  3039. dest='deps_os',
  3040. metavar='OS_LIST',
  3041. help='override deps for the specified (comma-separated) '
  3042. 'platform(s); \'all\' will process all deps_os '
  3043. 'references')
  3044. parser.add_option('--process-all-deps',
  3045. action='store_true',
  3046. help='Check out all deps, even for different OS-es, '
  3047. 'or with conditions evaluating to false')
  3048. parser.add_option('--upstream',
  3049. action='store_true',
  3050. help='Make repo state match upstream branch.')
  3051. parser.add_option('--output-json',
  3052. help='Output a json document to this path containing '
  3053. 'summary information about the sync.')
  3054. parser.add_option(
  3055. '--no-history',
  3056. action='store_true',
  3057. help='GIT ONLY - Reduces the size/time of the checkout at '
  3058. 'the cost of no history. Requires Git 1.9+')
  3059. parser.add_option('--shallow',
  3060. action='store_true',
  3061. help='GIT ONLY - Do a shallow clone into the cache dir. '
  3062. 'Requires Git 1.9+')
  3063. parser.add_option('--no_bootstrap',
  3064. '--no-bootstrap',
  3065. action='store_true',
  3066. help='Don\'t bootstrap from Google Storage.')
  3067. parser.add_option('--ignore_locks',
  3068. action='store_true',
  3069. help='No longer used.')
  3070. parser.add_option('--break_repo_locks',
  3071. action='store_true',
  3072. help='No longer used.')
  3073. parser.add_option('--lock_timeout',
  3074. type='int',
  3075. default=5000,
  3076. help='GIT ONLY - Deadline (in seconds) to wait for git '
  3077. 'cache lock to become available. Default is %default.')
  3078. parser.add_option('--no-rebase-patch-ref',
  3079. action='store_false',
  3080. dest='rebase_patch_ref',
  3081. default=True,
  3082. help='Bypass rebase of the patch ref after checkout.')
  3083. parser.add_option('--no-reset-patch-ref',
  3084. action='store_false',
  3085. dest='reset_patch_ref',
  3086. default=True,
  3087. help='Bypass calling reset after patching the ref.')
  3088. parser.add_option('--experiment',
  3089. action='append',
  3090. dest='experiments',
  3091. default=[],
  3092. help='Which experiments should be enabled.')
  3093. (options, args) = parser.parse_args(args)
  3094. client = GClient.LoadCurrentConfig(options)
  3095. if not client:
  3096. raise gclient_utils.Error(
  3097. 'client not configured; see \'gclient config\'')
  3098. if options.download_topics and not options.rebase_patch_ref:
  3099. raise gclient_utils.Error(
  3100. 'Warning: You cannot download topics and not rebase each patch ref')
  3101. if options.ignore_locks:
  3102. print(
  3103. 'Warning: ignore_locks is no longer used. Please remove its usage.')
  3104. if options.break_repo_locks:
  3105. print('Warning: break_repo_locks is no longer used. Please remove its '
  3106. 'usage.')
  3107. if options.revisions and options.head:
  3108. # TODO(maruel): Make it a parser.error if it doesn't break any builder.
  3109. print('Warning: you cannot use both --head and --revision')
  3110. if options.verbose:
  3111. client.PrintLocationAndContents()
  3112. ret = client.RunOnDeps('update', args)
  3113. if options.output_json:
  3114. slns = {}
  3115. for d in client.subtree(True):
  3116. normed = d.name.replace('\\', '/').rstrip('/') + '/'
  3117. slns[normed] = {
  3118. 'revision': d.got_revision,
  3119. 'scm': d.used_scm.name if d.used_scm else None,
  3120. 'url': str(d.url) if d.url else None,
  3121. 'was_processed': d.should_process,
  3122. 'was_synced': d._should_sync,
  3123. }
  3124. with open(options.output_json, 'w') as f:
  3125. json.dump({'solutions': slns}, f)
  3126. return ret
  3127. CMDupdate = CMDsync
  3128. @metrics.collector.collect_metrics('gclient validate')
  3129. def CMDvalidate(parser, args):
  3130. """Validates the .gclient and DEPS syntax."""
  3131. options, args = parser.parse_args(args)
  3132. client = GClient.LoadCurrentConfig(options)
  3133. if not client:
  3134. raise gclient_utils.Error(
  3135. 'client not configured; see \'gclient config\'')
  3136. rv = client.RunOnDeps('validate', args)
  3137. if rv == 0:
  3138. print('validate: SUCCESS')
  3139. else:
  3140. print('validate: FAILURE')
  3141. return rv
  3142. @metrics.collector.collect_metrics('gclient diff')
  3143. def CMDdiff(parser, args):
  3144. """Displays local diff for every dependencies."""
  3145. parser.add_option('--deps',
  3146. dest='deps_os',
  3147. metavar='OS_LIST',
  3148. help='override deps for the specified (comma-separated) '
  3149. 'platform(s); \'all\' will process all deps_os '
  3150. 'references')
  3151. (options, args) = parser.parse_args(args)
  3152. client = GClient.LoadCurrentConfig(options)
  3153. if not client:
  3154. raise gclient_utils.Error(
  3155. 'client not configured; see \'gclient config\'')
  3156. if options.verbose:
  3157. client.PrintLocationAndContents()
  3158. return client.RunOnDeps('diff', args)
  3159. @metrics.collector.collect_metrics('gclient revert')
  3160. def CMDrevert(parser, args):
  3161. """Reverts all modifications in every dependencies.
  3162. That's the nuclear option to get back to a 'clean' state. It removes anything
  3163. that shows up in git status."""
  3164. parser.add_option('--deps',
  3165. dest='deps_os',
  3166. metavar='OS_LIST',
  3167. help='override deps for the specified (comma-separated) '
  3168. 'platform(s); \'all\' will process all deps_os '
  3169. 'references')
  3170. parser.add_option('-n',
  3171. '--nohooks',
  3172. action='store_true',
  3173. help='don\'t run hooks after the revert is complete')
  3174. parser.add_option('-p',
  3175. '--noprehooks',
  3176. action='store_true',
  3177. help='don\'t run pre-DEPS hooks',
  3178. default=False)
  3179. parser.add_option('--upstream',
  3180. action='store_true',
  3181. help='Make repo state match upstream branch.')
  3182. parser.add_option('--break_repo_locks',
  3183. action='store_true',
  3184. help='No longer used.')
  3185. (options, args) = parser.parse_args(args)
  3186. if options.break_repo_locks:
  3187. print(
  3188. 'Warning: break_repo_locks is no longer used. Please remove its ' +
  3189. 'usage.')
  3190. # --force is implied.
  3191. options.force = True
  3192. options.reset = False
  3193. options.delete_unversioned_trees = False
  3194. options.merge = False
  3195. client = GClient.LoadCurrentConfig(options)
  3196. if not client:
  3197. raise gclient_utils.Error(
  3198. 'client not configured; see \'gclient config\'')
  3199. return client.RunOnDeps('revert', args)
  3200. @metrics.collector.collect_metrics('gclient runhooks')
  3201. def CMDrunhooks(parser, args):
  3202. """Runs hooks for files that have been modified in the local working copy."""
  3203. parser.add_option('--deps',
  3204. dest='deps_os',
  3205. metavar='OS_LIST',
  3206. help='override deps for the specified (comma-separated) '
  3207. 'platform(s); \'all\' will process all deps_os '
  3208. 'references')
  3209. parser.add_option('-f',
  3210. '--force',
  3211. action='store_true',
  3212. default=True,
  3213. help='Deprecated. No effect.')
  3214. (options, args) = parser.parse_args(args)
  3215. client = GClient.LoadCurrentConfig(options)
  3216. if not client:
  3217. raise gclient_utils.Error(
  3218. 'client not configured; see \'gclient config\'')
  3219. if options.verbose:
  3220. client.PrintLocationAndContents()
  3221. options.force = True
  3222. options.nohooks = False
  3223. return client.RunOnDeps('runhooks', args)
  3224. # TODO(crbug.com/1481266): Collect merics for installhooks.
  3225. def CMDinstallhooks(parser, args):
  3226. """Installs gclient git hooks.
  3227. Currently only installs a pre-commit hook to drop staged gitlinks. To
  3228. bypass this pre-commit hook once it's installed, set the environment
  3229. variable SKIP_GITLINK_PRECOMMIT=1.
  3230. """
  3231. (options, args) = parser.parse_args(args)
  3232. client = GClient.LoadCurrentConfig(options)
  3233. if not client:
  3234. raise gclient_utils.Error(
  3235. 'client not configured; see \'gclient config\'')
  3236. client._InstallPreCommitHook()
  3237. return 0
  3238. @metrics.collector.collect_metrics('gclient revinfo')
  3239. def CMDrevinfo(parser, args):
  3240. """Outputs revision info mapping for the client and its dependencies.
  3241. This allows the capture of an overall 'revision' for the source tree that
  3242. can be used to reproduce the same tree in the future. It is only useful for
  3243. 'unpinned dependencies', i.e. DEPS/deps references without a git hash.
  3244. A git branch name isn't 'pinned' since the actual commit can change.
  3245. """
  3246. parser.add_option('--deps',
  3247. dest='deps_os',
  3248. metavar='OS_LIST',
  3249. help='override deps for the specified (comma-separated) '
  3250. 'platform(s); \'all\' will process all deps_os '
  3251. 'references')
  3252. parser.add_option(
  3253. '-a',
  3254. '--actual',
  3255. action='store_true',
  3256. help='gets the actual checked out revisions instead of the '
  3257. 'ones specified in the DEPS and .gclient files')
  3258. parser.add_option('-s',
  3259. '--snapshot',
  3260. action='store_true',
  3261. help='creates a snapshot .gclient file of the current '
  3262. 'version of all repositories to reproduce the tree, '
  3263. 'implies -a')
  3264. parser.add_option(
  3265. '--filter',
  3266. action='append',
  3267. dest='filter',
  3268. help='Display revision information only for the specified '
  3269. 'dependencies (filtered by URL or path).')
  3270. parser.add_option('--output-json',
  3271. help='Output a json document to this path containing '
  3272. 'information about the revisions.')
  3273. parser.add_option(
  3274. '--ignore-dep-type',
  3275. choices=['git', 'cipd'],
  3276. help='Specify to skip processing of a certain type of dep.')
  3277. (options, args) = parser.parse_args(args)
  3278. client = GClient.LoadCurrentConfig(options)
  3279. if not client:
  3280. raise gclient_utils.Error(
  3281. 'client not configured; see \'gclient config\'')
  3282. client.PrintRevInfo()
  3283. return 0
  3284. @metrics.collector.collect_metrics('gclient getdep')
  3285. def CMDgetdep(parser, args):
  3286. """Gets revision information and variable values from a DEPS file.
  3287. If key doesn't exist or is incorrectly declared, this script exits with exit
  3288. code 2."""
  3289. parser.add_option('--var',
  3290. action='append',
  3291. dest='vars',
  3292. metavar='VAR',
  3293. default=[],
  3294. help='Gets the value of a given variable.')
  3295. parser.add_option(
  3296. '-r',
  3297. '--revision',
  3298. action='append',
  3299. dest='getdep_revisions',
  3300. metavar='DEP',
  3301. default=[],
  3302. help='Gets the revision/version for the given dependency. '
  3303. 'If it is a git dependency, dep must be a path. If it '
  3304. 'is a CIPD dependency, dep must be of the form '
  3305. 'path:package.')
  3306. parser.add_option(
  3307. '--deps-file',
  3308. default='DEPS',
  3309. # TODO(ehmaldonado): Try to find the DEPS file pointed by
  3310. # .gclient first.
  3311. help='The DEPS file to be edited. Defaults to the DEPS '
  3312. 'file in the current directory.')
  3313. (options, args) = parser.parse_args(args)
  3314. if not os.path.isfile(options.deps_file):
  3315. raise gclient_utils.Error('DEPS file %s does not exist.' %
  3316. options.deps_file)
  3317. with open(options.deps_file) as f:
  3318. contents = f.read()
  3319. client = GClient.LoadCurrentConfig(options)
  3320. if client is not None:
  3321. builtin_vars = client.get_builtin_vars()
  3322. else:
  3323. logging.warning(
  3324. 'Couldn\'t find a valid gclient config. Will attempt to parse the DEPS '
  3325. 'file without support for built-in variables.')
  3326. builtin_vars = None
  3327. local_scope = gclient_eval.Exec(contents,
  3328. options.deps_file,
  3329. builtin_vars=builtin_vars)
  3330. for var in options.vars:
  3331. print(gclient_eval.GetVar(local_scope, var))
  3332. commits = {}
  3333. if local_scope.get(
  3334. 'git_dependencies'
  3335. ) == gclient_eval.SUBMODULES and options.getdep_revisions:
  3336. commits.update(
  3337. scm_git.GIT.GetSubmoduleCommits(
  3338. os.getcwd(),
  3339. [path for path in options.getdep_revisions if ':' not in path]))
  3340. for name in options.getdep_revisions:
  3341. if ':' in name:
  3342. name, _, package = name.partition(':')
  3343. if not name or not package:
  3344. parser.error(
  3345. 'Wrong CIPD format: %s:%s should be of the form path:pkg.' %
  3346. (name, package))
  3347. print(gclient_eval.GetCIPD(local_scope, name, package))
  3348. elif commits:
  3349. print(commits[name])
  3350. else:
  3351. try:
  3352. print(gclient_eval.GetRevision(local_scope, name))
  3353. except KeyError as e:
  3354. print(repr(e), file=sys.stderr)
  3355. sys.exit(2)
  3356. @metrics.collector.collect_metrics('gclient setdep')
  3357. def CMDsetdep(parser, args):
  3358. """Modifies dependency revisions and variable values in a DEPS file"""
  3359. parser.add_option('--var',
  3360. action='append',
  3361. dest='vars',
  3362. metavar='VAR=VAL',
  3363. default=[],
  3364. help='Sets a variable to the given value with the format '
  3365. 'name=value.')
  3366. parser.add_option('-r',
  3367. '--revision',
  3368. action='append',
  3369. dest='setdep_revisions',
  3370. metavar='DEP@REV',
  3371. default=[],
  3372. help='Sets the revision/version for the dependency with '
  3373. 'the format dep@rev. If it is a git dependency, dep '
  3374. 'must be a path and rev must be a git hash or '
  3375. 'reference (e.g. src/dep@deadbeef). If it is a CIPD '
  3376. 'dependency, dep must be of the form path:package and '
  3377. 'rev must be the package version '
  3378. '(e.g. src/pkg:chromium/pkg@2.1-cr0).')
  3379. parser.add_option(
  3380. '--deps-file',
  3381. default='DEPS',
  3382. # TODO(ehmaldonado): Try to find the DEPS file pointed by
  3383. # .gclient first.
  3384. help='The DEPS file to be edited. Defaults to the DEPS '
  3385. 'file in the current directory.')
  3386. (options, args) = parser.parse_args(args)
  3387. if args:
  3388. parser.error('Unused arguments: "%s"' % '" "'.join(args))
  3389. if not options.setdep_revisions and not options.vars:
  3390. parser.error(
  3391. 'You must specify at least one variable or revision to modify.')
  3392. if not os.path.isfile(options.deps_file):
  3393. raise gclient_utils.Error('DEPS file %s does not exist.' %
  3394. options.deps_file)
  3395. with open(options.deps_file) as f:
  3396. contents = f.read()
  3397. client = GClient.LoadCurrentConfig(options)
  3398. if client is not None:
  3399. builtin_vars = client.get_builtin_vars()
  3400. else:
  3401. logging.warning(
  3402. 'Couldn\'t find a valid gclient config. Will attempt to parse the DEPS '
  3403. 'file without support for built-in variables.')
  3404. builtin_vars = None
  3405. local_scope = gclient_eval.Exec(contents,
  3406. options.deps_file,
  3407. builtin_vars=builtin_vars)
  3408. # Create a set of all git submodules.
  3409. cwd = os.path.dirname(options.deps_file) or os.getcwd()
  3410. git_modules = None
  3411. if 'git_dependencies' in local_scope and local_scope[
  3412. 'git_dependencies'] in (gclient_eval.SUBMODULES, gclient_eval.SYNC):
  3413. try:
  3414. submodule_status = subprocess2.check_output(
  3415. ['git', 'submodule', 'status'], cwd=cwd).decode('utf-8')
  3416. git_modules = {l.split()[1] for l in submodule_status.splitlines()}
  3417. except subprocess2.CalledProcessError as e:
  3418. print('Warning: gitlinks won\'t be updated: ', e)
  3419. for var in options.vars:
  3420. name, _, value = var.partition('=')
  3421. if not name or not value:
  3422. parser.error(
  3423. 'Wrong var format: %s should be of the form name=value.' % var)
  3424. if name in local_scope['vars']:
  3425. gclient_eval.SetVar(local_scope, name, value)
  3426. else:
  3427. gclient_eval.AddVar(local_scope, name, value)
  3428. for revision in options.setdep_revisions:
  3429. name, _, value = revision.partition('@')
  3430. if not name or not value:
  3431. parser.error('Wrong dep format: %s should be of the form dep@rev.' %
  3432. revision)
  3433. if ':' in name:
  3434. name, _, package = name.partition(':')
  3435. if not name or not package:
  3436. parser.error(
  3437. 'Wrong CIPD format: %s:%s should be of the form path:pkg@version.'
  3438. % (name, package))
  3439. gclient_eval.SetCIPD(local_scope, name, package, value)
  3440. else:
  3441. # Update DEPS only when `git_dependencies` == DEPS or SYNC.
  3442. # git_dependencies is defaulted to DEPS when not set.
  3443. if 'git_dependencies' not in local_scope or local_scope[
  3444. 'git_dependencies'] in (gclient_eval.DEPS,
  3445. gclient_eval.SYNC):
  3446. gclient_eval.SetRevision(local_scope, name, value)
  3447. # Update git submodules when `git_dependencies` == SYNC or
  3448. # SUBMODULES.
  3449. if git_modules and 'git_dependencies' in local_scope and local_scope[
  3450. 'git_dependencies'] in (gclient_eval.SUBMODULES,
  3451. gclient_eval.SYNC):
  3452. git_module_name = name
  3453. if not 'use_relative_paths' in local_scope or \
  3454. local_scope['use_relative_paths'] != True:
  3455. deps_dir = os.path.dirname(
  3456. os.path.abspath(options.deps_file))
  3457. gclient_path = gclient_paths.FindGclientRoot(deps_dir)
  3458. delta_path = None
  3459. if gclient_path:
  3460. delta_path = os.path.relpath(
  3461. deps_dir, os.path.abspath(gclient_path))
  3462. if delta_path:
  3463. prefix_length = len(delta_path.replace(
  3464. os.path.sep, '/')) + 1
  3465. git_module_name = name[prefix_length:]
  3466. # gclient setdep should update the revision, i.e., the gitlink
  3467. # only when the submodule entry is already present within
  3468. # .gitmodules.
  3469. if git_module_name not in git_modules:
  3470. raise KeyError(
  3471. f'Could not find any dependency called "{git_module_name}" in '
  3472. f'.gitmodules.')
  3473. # Update the gitlink for the submodule.
  3474. subprocess2.call([
  3475. 'git', 'update-index', '--add', '--cacheinfo',
  3476. f'160000,{value},{git_module_name}'
  3477. ],
  3478. cwd=cwd)
  3479. with open(options.deps_file, 'wb') as f:
  3480. f.write(gclient_eval.RenderDEPSFile(local_scope).encode('utf-8'))
  3481. if git_modules:
  3482. subprocess2.call(['git', 'add', options.deps_file], cwd=cwd)
  3483. print('Changes have been staged. See changes with `git status`.\n'
  3484. 'Use `git commit -m "Manual roll"` to commit your changes. \n'
  3485. 'Run gclient sync to update your local dependency checkout.')
  3486. @metrics.collector.collect_metrics('gclient verify')
  3487. def CMDverify(parser, args):
  3488. """Verifies the DEPS file deps are only from allowed_hosts."""
  3489. (options, args) = parser.parse_args(args)
  3490. client = GClient.LoadCurrentConfig(options)
  3491. if not client:
  3492. raise gclient_utils.Error(
  3493. 'client not configured; see \'gclient config\'')
  3494. client.RunOnDeps(None, [])
  3495. # Look at each first-level dependency of this gclient only.
  3496. for dep in client.dependencies:
  3497. bad_deps = dep.findDepsFromNotAllowedHosts()
  3498. if not bad_deps:
  3499. continue
  3500. print("There are deps from not allowed hosts in file %s" %
  3501. dep.deps_file)
  3502. for bad_dep in bad_deps:
  3503. print("\t%s at %s" % (bad_dep.name, bad_dep.url))
  3504. print("allowed_hosts:", ', '.join(dep.allowed_hosts))
  3505. sys.stdout.flush()
  3506. raise gclient_utils.Error(
  3507. 'dependencies from disallowed hosts; check your DEPS file.')
  3508. return 0
  3509. @subcommand.epilog("""For more information on what metrics are we collecting and
  3510. why, please read metrics.README.md or visit https://bit.ly/2ufRS4p""")
  3511. @metrics.collector.collect_metrics('gclient metrics')
  3512. def CMDmetrics(parser, args):
  3513. """Reports, and optionally modifies, the status of metric collection."""
  3514. parser.add_option('--opt-in',
  3515. action='store_true',
  3516. dest='enable_metrics',
  3517. help='Opt-in to metrics collection.',
  3518. default=None)
  3519. parser.add_option('--opt-out',
  3520. action='store_false',
  3521. dest='enable_metrics',
  3522. help='Opt-out of metrics collection.')
  3523. options, args = parser.parse_args(args)
  3524. if args:
  3525. parser.error('Unused arguments: "%s"' % '" "'.join(args))
  3526. if not metrics.collector.config.is_googler:
  3527. print("You're not a Googler. Metrics collection is disabled for you.")
  3528. return 0
  3529. if options.enable_metrics is not None:
  3530. metrics.collector.config.opted_in = options.enable_metrics
  3531. if metrics.collector.config.opted_in is None:
  3532. print("You haven't opted in or out of metrics collection.")
  3533. elif metrics.collector.config.opted_in:
  3534. print("You have opted in. Thanks!")
  3535. else:
  3536. print("You have opted out. Please consider opting in.")
  3537. return 0
  3538. class OptionParser(optparse.OptionParser):
  3539. gclientfile_default = os.environ.get('GCLIENT_FILE', '.gclient')
  3540. def __init__(self, **kwargs):
  3541. optparse.OptionParser.__init__(self,
  3542. version='%prog ' + __version__,
  3543. **kwargs)
  3544. # Some arm boards have issues with parallel sync.
  3545. if platform.machine().startswith('arm'):
  3546. jobs = 1
  3547. else:
  3548. jobs = max(8, gclient_utils.NumLocalCpus())
  3549. self.add_option(
  3550. '-j',
  3551. '--jobs',
  3552. default=jobs,
  3553. type='int',
  3554. help='Specify how many SCM commands can run in parallel; defaults to '
  3555. '%default on this machine')
  3556. self.add_option(
  3557. '-v',
  3558. '--verbose',
  3559. action='count',
  3560. default=0,
  3561. help='Produces additional output for diagnostics. Can be used up to '
  3562. 'three times for more logging info.')
  3563. self.add_option('--gclientfile',
  3564. dest='config_filename',
  3565. help='Specify an alternate %s file' %
  3566. self.gclientfile_default)
  3567. self.add_option(
  3568. '--spec',
  3569. help='create a gclient file containing the provided string. Due to '
  3570. 'Cygwin/Python brokenness, it can\'t contain any newlines.')
  3571. self.add_option('--no-nag-max',
  3572. default=False,
  3573. action='store_true',
  3574. help='Ignored for backwards compatibility.')
  3575. def parse_args(self, args=None, _values=None):
  3576. """Integrates standard options processing."""
  3577. # Create an optparse.Values object that will store only the actual
  3578. # passed options, without the defaults.
  3579. actual_options = optparse.Values()
  3580. _, args = optparse.OptionParser.parse_args(self, args, actual_options)
  3581. # Create an optparse.Values object with the default options.
  3582. options = optparse.Values(self.get_default_values().__dict__)
  3583. # Update it with the options passed by the user.
  3584. options._update_careful(actual_options.__dict__)
  3585. # Store the options passed by the user in an _actual_options attribute.
  3586. # We store only the keys, and not the values, since the values can
  3587. # contain arbitrary information, which might be PII.
  3588. metrics.collector.add('arguments', list(actual_options.__dict__))
  3589. levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
  3590. logging.basicConfig(
  3591. level=levels[min(options.verbose,
  3592. len(levels) - 1)],
  3593. format='%(module)s(%(lineno)d) %(funcName)s:%(message)s')
  3594. if options.config_filename and options.spec:
  3595. self.error('Cannot specify both --gclientfile and --spec')
  3596. if (options.config_filename and options.config_filename !=
  3597. os.path.basename(options.config_filename)):
  3598. self.error('--gclientfile target must be a filename, not a path')
  3599. if not options.config_filename:
  3600. options.config_filename = self.gclientfile_default
  3601. options.entries_filename = options.config_filename + '_entries'
  3602. if options.jobs < 1:
  3603. self.error('--jobs must be 1 or higher')
  3604. # These hacks need to die.
  3605. if not hasattr(options, 'revisions'):
  3606. # GClient.RunOnDeps expects it even if not applicable.
  3607. options.revisions = []
  3608. if not hasattr(options, 'experiments'):
  3609. options.experiments = []
  3610. if not hasattr(options, 'head'):
  3611. options.head = None
  3612. if not hasattr(options, 'nohooks'):
  3613. options.nohooks = True
  3614. if not hasattr(options, 'noprehooks'):
  3615. options.noprehooks = True
  3616. if not hasattr(options, 'deps_os'):
  3617. options.deps_os = None
  3618. if not hasattr(options, 'force'):
  3619. options.force = None
  3620. return (options, args)
  3621. def disable_buffering():
  3622. # Make stdout auto-flush so buildbot doesn't kill us during lengthy
  3623. # operations. Python as a strong tendency to buffer sys.stdout.
  3624. sys.stdout = gclient_utils.MakeFileAutoFlush(sys.stdout)
  3625. # Make stdout annotated with the thread ids.
  3626. sys.stdout = gclient_utils.MakeFileAnnotated(sys.stdout)
  3627. def path_contains_tilde():
  3628. for element in os.environ['PATH'].split(os.pathsep):
  3629. if element.startswith('~') and os.path.abspath(
  3630. os.path.realpath(
  3631. os.path.expanduser(element))) == DEPOT_TOOLS_DIR:
  3632. return True
  3633. return False
  3634. def can_run_gclient_and_helpers():
  3635. if sys.version_info[0] < 3:
  3636. print('\nYour python version %s is unsupported, please upgrade.\n' %
  3637. sys.version.split(' ', 1)[0],
  3638. file=sys.stderr)
  3639. return False
  3640. if not sys.executable:
  3641. print('\nPython cannot find the location of it\'s own executable.\n',
  3642. file=sys.stderr)
  3643. return False
  3644. if path_contains_tilde():
  3645. print(
  3646. '\nYour PATH contains a literal "~", which works in some shells ' +
  3647. 'but will break when python tries to run subprocesses. ' +
  3648. 'Replace the "~" with $HOME.\n' + 'See https://crbug.com/952865.\n',
  3649. file=sys.stderr)
  3650. return False
  3651. return True
  3652. def main(argv):
  3653. """Doesn't parse the arguments here, just find the right subcommand to
  3654. execute."""
  3655. if not can_run_gclient_and_helpers():
  3656. return 2
  3657. fix_encoding.fix_encoding()
  3658. disable_buffering()
  3659. setup_color.init()
  3660. dispatcher = subcommand.CommandDispatcher(__name__)
  3661. try:
  3662. return dispatcher.execute(OptionParser(), argv)
  3663. except KeyboardInterrupt:
  3664. gclient_utils.GClientChildren.KillAllRemainingChildren()
  3665. raise
  3666. except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
  3667. print('Error: %s' % str(e), file=sys.stderr)
  3668. return 1
  3669. finally:
  3670. gclient_utils.PrintWarnings()
  3671. return 0
  3672. if '__main__' == __name__:
  3673. with metrics.collector.print_notice_and_exit():
  3674. sys.exit(main(sys.argv[1:]))
  3675. # vim: ts=2:sw=2:tw=80:et: