gclient.py 176 KB

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