gclient.py 165 KB

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