gclient.py 187 KB

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