gclient.py 180 KB

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