gclient.py 180 KB

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