gclient.py 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184
  1. #!/usr/bin/env python
  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 analagous to target_os and target_os_only.
  81. from __future__ import print_function
  82. __version__ = '0.7'
  83. import collections
  84. import copy
  85. import json
  86. import logging
  87. import optparse
  88. import os
  89. import platform
  90. import posixpath
  91. import pprint
  92. import re
  93. import sys
  94. import time
  95. try:
  96. import urlparse
  97. except ImportError: # For Py3 compatibility
  98. import urllib.parse as urlparse
  99. import detect_host_arch
  100. import fix_encoding
  101. import gclient_eval
  102. import gclient_scm
  103. import gclient_paths
  104. import gclient_utils
  105. import git_cache
  106. import metrics
  107. import metrics_utils
  108. from third_party.repo.progress import Progress
  109. import subcommand
  110. import subprocess2
  111. import setup_color
  112. from third_party import six
  113. # Check for people accidentally running this script with Python3 - an
  114. # increasingly common error on Windows 10 due to the store version of Python.
  115. if sys.version_info.major >= 3 and not 'GCLIENT_TEST' in os.environ:
  116. print("Warning: gclient doesn't yet support Python 3 and may not work "
  117. "correctly.", file=sys.stderr)
  118. # TODO(crbug.com/953884): Remove this when python3 migration is done.
  119. if six.PY3:
  120. # pylint: disable=redefined-builtin
  121. basestring = str
  122. DEPOT_TOOLS_DIR = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
  123. # Singleton object to represent an unset cache_dir (as opposed to a disabled
  124. # one, e.g. if a spec explicitly says `cache_dir = None`.)
  125. UNSET_CACHE_DIR = object()
  126. class GNException(Exception):
  127. pass
  128. def ToGNString(value, allow_dicts = True):
  129. """Returns a stringified GN equivalent of the Python value.
  130. allow_dicts indicates if this function will allow converting dictionaries
  131. to GN scopes. This is only possible at the top level, you can't nest a
  132. GN scope in a list, so this should be set to False for recursive calls."""
  133. if isinstance(value, basestring):
  134. if value.find('\n') >= 0:
  135. raise GNException("Trying to print a string with a newline in it.")
  136. return '"' + \
  137. value.replace('\\', '\\\\').replace('"', '\\"').replace('$', '\\$') + \
  138. '"'
  139. if sys.version_info.major == 2 and isinstance(value, unicode):
  140. return ToGNString(value.encode('utf-8'))
  141. if isinstance(value, bool):
  142. if value:
  143. return "true"
  144. return "false"
  145. # NOTE: some type handling removed compared to chromium/src copy.
  146. raise GNException("Unsupported type when printing to GN.")
  147. class Hook(object):
  148. """Descriptor of command ran before/after sync or on demand."""
  149. def __init__(self, action, pattern=None, name=None, cwd=None, condition=None,
  150. variables=None, verbose=False, cwd_base=None):
  151. """Constructor.
  152. Arguments:
  153. action (list of basestring): argv of the command to run
  154. pattern (basestring regex): noop with git; deprecated
  155. name (basestring): optional name; no effect on operation
  156. cwd (basestring): working directory to use
  157. condition (basestring): condition when to run the hook
  158. variables (dict): variables for evaluating the condition
  159. """
  160. self._action = gclient_utils.freeze(action)
  161. self._pattern = pattern
  162. self._name = name
  163. self._cwd = cwd
  164. self._condition = condition
  165. self._variables = variables
  166. self._verbose = verbose
  167. self._cwd_base = cwd_base
  168. @staticmethod
  169. def from_dict(d, variables=None, verbose=False, conditions=None,
  170. cwd_base=None):
  171. """Creates a Hook instance from a dict like in the DEPS file."""
  172. # Merge any local and inherited conditions.
  173. gclient_eval.UpdateCondition(d, 'and', conditions)
  174. return Hook(
  175. d['action'],
  176. d.get('pattern'),
  177. d.get('name'),
  178. d.get('cwd'),
  179. d.get('condition'),
  180. variables=variables,
  181. # Always print the header if not printing to a TTY.
  182. verbose=verbose or not setup_color.IS_TTY,
  183. cwd_base=cwd_base)
  184. @property
  185. def action(self):
  186. return self._action
  187. @property
  188. def pattern(self):
  189. return self._pattern
  190. @property
  191. def name(self):
  192. return self._name
  193. @property
  194. def condition(self):
  195. return self._condition
  196. @property
  197. def effective_cwd(self):
  198. cwd = self._cwd_base
  199. if self._cwd:
  200. cwd = os.path.join(cwd, self._cwd)
  201. return cwd
  202. def matches(self, file_list):
  203. """Returns true if the pattern matches any of files in the list."""
  204. if not self._pattern:
  205. return True
  206. pattern = re.compile(self._pattern)
  207. return bool([f for f in file_list if pattern.search(f)])
  208. def run(self):
  209. """Executes the hook's command (provided the condition is met)."""
  210. if (self._condition and
  211. not gclient_eval.EvaluateCondition(self._condition, self._variables)):
  212. return
  213. cmd = [arg for arg in self._action]
  214. if cmd[0] == 'python':
  215. cmd[0] = 'vpython'
  216. if cmd[0] == 'vpython' and _detect_host_os() == 'win':
  217. cmd[0] += '.bat'
  218. try:
  219. start_time = time.time()
  220. gclient_utils.CheckCallAndFilter(
  221. cmd, cwd=self.effective_cwd, print_stdout=True, show_header=True,
  222. always_show_header=self._verbose)
  223. except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
  224. # Use a discrete exit status code of 2 to indicate that a hook action
  225. # failed. Users of this script may wish to treat hook action failures
  226. # differently from VC failures.
  227. print('Error: %s' % str(e), file=sys.stderr)
  228. sys.exit(2)
  229. finally:
  230. elapsed_time = time.time() - start_time
  231. if elapsed_time > 10:
  232. print("Hook '%s' took %.2f secs" % (
  233. gclient_utils.CommandToStr(cmd), elapsed_time))
  234. class DependencySettings(object):
  235. """Immutable configuration settings."""
  236. def __init__(
  237. self, parent, url, managed, custom_deps, custom_vars,
  238. custom_hooks, deps_file, should_process, relative, condition):
  239. # These are not mutable:
  240. self._parent = parent
  241. self._deps_file = deps_file
  242. self._url = url
  243. # The condition as string (or None). Useful to keep e.g. for flatten.
  244. self._condition = condition
  245. # 'managed' determines whether or not this dependency is synced/updated by
  246. # gclient after gclient checks it out initially. The difference between
  247. # 'managed' and 'should_process' is that the user specifies 'managed' via
  248. # the --unmanaged command-line flag or a .gclient config, where
  249. # 'should_process' is dynamically set by gclient if it goes over its
  250. # recursion limit and controls gclient's behavior so it does not misbehave.
  251. self._managed = managed
  252. self._should_process = should_process
  253. # If this is a recursed-upon sub-dependency, and the parent has
  254. # use_relative_paths set, then this dependency should check out its own
  255. # dependencies relative to that parent's path for this, rather than
  256. # relative to the .gclient file.
  257. self._relative = relative
  258. # This is a mutable value which has the list of 'target_os' OSes listed in
  259. # the current deps file.
  260. self.local_target_os = None
  261. # These are only set in .gclient and not in DEPS files.
  262. self._custom_vars = custom_vars or {}
  263. self._custom_deps = custom_deps or {}
  264. self._custom_hooks = custom_hooks or []
  265. # Post process the url to remove trailing slashes.
  266. if isinstance(self.url, basestring):
  267. # urls are sometime incorrectly written as proto://host/path/@rev. Replace
  268. # it to proto://host/path@rev.
  269. self.set_url(self.url.replace('/@', '@'))
  270. elif not isinstance(self.url, (None.__class__)):
  271. raise gclient_utils.Error(
  272. ('dependency url must be either string or None, '
  273. 'instead of %s') % self.url.__class__.__name__)
  274. # Make any deps_file path platform-appropriate.
  275. if self._deps_file:
  276. for sep in ['/', '\\']:
  277. self._deps_file = self._deps_file.replace(sep, os.sep)
  278. @property
  279. def deps_file(self):
  280. return self._deps_file
  281. @property
  282. def managed(self):
  283. return self._managed
  284. @property
  285. def parent(self):
  286. return self._parent
  287. @property
  288. def root(self):
  289. """Returns the root node, a GClient object."""
  290. if not self.parent:
  291. # This line is to signal pylint that it could be a GClient instance.
  292. return self or GClient(None, None)
  293. return self.parent.root
  294. @property
  295. def should_process(self):
  296. """True if this dependency should be processed, i.e. checked out."""
  297. return self._should_process
  298. @property
  299. def custom_vars(self):
  300. return self._custom_vars.copy()
  301. @property
  302. def custom_deps(self):
  303. return self._custom_deps.copy()
  304. @property
  305. def custom_hooks(self):
  306. return self._custom_hooks[:]
  307. @property
  308. def url(self):
  309. """URL after variable expansion."""
  310. return self._url
  311. @property
  312. def condition(self):
  313. return self._condition
  314. @property
  315. def target_os(self):
  316. if self.local_target_os is not None:
  317. return tuple(set(self.local_target_os).union(self.parent.target_os))
  318. else:
  319. return self.parent.target_os
  320. @property
  321. def target_cpu(self):
  322. return self.parent.target_cpu
  323. def set_url(self, url):
  324. self._url = url
  325. def get_custom_deps(self, name, url):
  326. """Returns a custom deps if applicable."""
  327. if self.parent:
  328. url = self.parent.get_custom_deps(name, url)
  329. # None is a valid return value to disable a dependency.
  330. return self.custom_deps.get(name, url)
  331. class Dependency(gclient_utils.WorkItem, DependencySettings):
  332. """Object that represents a dependency checkout."""
  333. def __init__(self, parent, name, url, managed, custom_deps,
  334. custom_vars, custom_hooks, deps_file, should_process,
  335. should_recurse, relative, condition, print_outbuf=False):
  336. gclient_utils.WorkItem.__init__(self, name)
  337. DependencySettings.__init__(
  338. self, parent, url, managed, custom_deps, custom_vars,
  339. custom_hooks, deps_file, should_process, relative, condition)
  340. # This is in both .gclient and DEPS files:
  341. self._deps_hooks = []
  342. self._pre_deps_hooks = []
  343. # Calculates properties:
  344. self._dependencies = []
  345. self._vars = {}
  346. # A cache of the files affected by the current operation, necessary for
  347. # hooks.
  348. self._file_list = []
  349. # List of host names from which dependencies are allowed.
  350. # Default is an empty set, meaning unspecified in DEPS file, and hence all
  351. # hosts will be allowed. Non-empty set means whitelist of hosts.
  352. # allowed_hosts var is scoped to its DEPS file, and so it isn't recursive.
  353. self._allowed_hosts = frozenset()
  354. self._gn_args_from = None
  355. # Spec for .gni output to write (if any).
  356. self._gn_args_file = None
  357. self._gn_args = []
  358. # If it is not set to True, the dependency wasn't processed for its child
  359. # dependency, i.e. its DEPS wasn't read.
  360. self._deps_parsed = False
  361. # This dependency has been processed, i.e. checked out
  362. self._processed = False
  363. # This dependency had its pre-DEPS hooks run
  364. self._pre_deps_hooks_ran = False
  365. # This dependency had its hook run
  366. self._hooks_ran = False
  367. # This is the scm used to checkout self.url. It may be used by dependencies
  368. # to get the datetime of the revision we checked out.
  369. self._used_scm = None
  370. self._used_revision = None
  371. # The actual revision we ended up getting, or None if that information is
  372. # unavailable
  373. self._got_revision = None
  374. # recursedeps is a mutable value that selectively overrides the default
  375. # 'no recursion' setting on a dep-by-dep basis.
  376. #
  377. # It will be a dictionary of {deps_name: depfile_namee}
  378. self.recursedeps = {}
  379. # Whether we should process this dependency's DEPS file.
  380. self._should_recurse = should_recurse
  381. self._OverrideUrl()
  382. # This is inherited from WorkItem. We want the URL to be a resource.
  383. if self.url and isinstance(self.url, basestring):
  384. # The url is usually given to gclient either as https://blah@123
  385. # or just https://blah. The @123 portion is irrelevant.
  386. self.resources.append(self.url.split('@')[0])
  387. # Controls whether we want to print git's output when we first clone the
  388. # dependency
  389. self.print_outbuf = print_outbuf
  390. if not self.name and self.parent:
  391. raise gclient_utils.Error('Dependency without name')
  392. def _OverrideUrl(self):
  393. """Resolves the parsed url from the parent hierarchy."""
  394. parsed_url = self.get_custom_deps(self._name, self.url)
  395. if parsed_url != self.url:
  396. logging.info('Dependency(%s)._OverrideUrl(%s) -> %s', self._name,
  397. self.url, parsed_url)
  398. self.set_url(parsed_url)
  399. return
  400. if self.url is None:
  401. logging.info('Dependency(%s)._OverrideUrl(None) -> None', self._name)
  402. return
  403. if not isinstance(self.url, basestring):
  404. raise gclient_utils.Error('Unknown url type')
  405. # self.url is a local path
  406. path, at, rev = self.url.partition('@')
  407. if os.path.isdir(path):
  408. return
  409. # self.url is a URL
  410. parsed_url = urlparse.urlparse(self.url)
  411. if parsed_url[0] or re.match(r'^\w+\@[\w\.-]+\:[\w\/]+', parsed_url[2]):
  412. return
  413. # self.url is relative to the parent's URL.
  414. if not path.startswith('/'):
  415. raise gclient_utils.Error(
  416. 'relative DEPS entry \'%s\' must begin with a slash' % self.url)
  417. parent_url = self.parent.url
  418. parent_path = self.parent.url.split('@')[0]
  419. if os.path.isdir(parent_path):
  420. # Parent's URL is a local path. Get parent's URL dirname and append
  421. # self.url.
  422. parent_path = os.path.dirname(parent_path)
  423. parsed_url = parent_path + path.replace('/', os.sep) + at + rev
  424. else:
  425. # Parent's URL is a URL. Get parent's URL, strip from the last '/'
  426. # (equivalent to unix dirname) and append self.url.
  427. parsed_url = parent_url[:parent_url.rfind('/')] + self.url
  428. logging.info('Dependency(%s)._OverrideUrl(%s) -> %s', self.name,
  429. self.url, parsed_url)
  430. self.set_url(parsed_url)
  431. def PinToActualRevision(self):
  432. """Updates self.url to the revision checked out on disk."""
  433. if self.url is None:
  434. return
  435. url = None
  436. scm = self.CreateSCM()
  437. if os.path.isdir(scm.checkout_path):
  438. revision = scm.revinfo(None, None, None)
  439. url = '%s@%s' % (gclient_utils.SplitUrlRevision(self.url)[0], revision)
  440. self.set_url(url)
  441. def ToLines(self):
  442. s = []
  443. condition_part = ([' "condition": %r,' % self.condition]
  444. if self.condition else [])
  445. s.extend([
  446. ' # %s' % self.hierarchy(include_url=False),
  447. ' "%s": {' % (self.name,),
  448. ' "url": "%s",' % (self.url,),
  449. ] + condition_part + [
  450. ' },',
  451. '',
  452. ])
  453. return s
  454. @property
  455. def requirements(self):
  456. """Calculate the list of requirements."""
  457. requirements = set()
  458. # self.parent is implicitly a requirement. This will be recursive by
  459. # definition.
  460. if self.parent and self.parent.name:
  461. requirements.add(self.parent.name)
  462. # For a tree with at least 2 levels*, the leaf node needs to depend
  463. # on the level higher up in an orderly way.
  464. # This becomes messy for >2 depth as the DEPS file format is a dictionary,
  465. # thus unsorted, while the .gclient format is a list thus sorted.
  466. #
  467. # Interestingly enough, the following condition only works in the case we
  468. # want: self is a 2nd level node. 3nd level node wouldn't need this since
  469. # they already have their parent as a requirement.
  470. if self.parent and self.parent.parent and not self.parent.parent.parent:
  471. requirements |= set(i.name for i in self.root.dependencies if i.name)
  472. if self.name:
  473. requirements |= set(
  474. obj.name for obj in self.root.subtree(False)
  475. if (obj is not self
  476. and obj.name and
  477. self.name.startswith(posixpath.join(obj.name, ''))))
  478. requirements = tuple(sorted(requirements))
  479. logging.info('Dependency(%s).requirements = %s' % (self.name, requirements))
  480. return requirements
  481. @property
  482. def should_recurse(self):
  483. return self._should_recurse
  484. def verify_validity(self):
  485. """Verifies that this Dependency is fine to add as a child of another one.
  486. Returns True if this entry should be added, False if it is a duplicate of
  487. another entry.
  488. """
  489. logging.info('Dependency(%s).verify_validity()' % self.name)
  490. if self.name in [s.name for s in self.parent.dependencies]:
  491. raise gclient_utils.Error(
  492. 'The same name "%s" appears multiple times in the deps section' %
  493. self.name)
  494. if not self.should_process:
  495. # Return early, no need to set requirements.
  496. return not any(d.name == self.name for d in self.root.subtree(True))
  497. # This require a full tree traversal with locks.
  498. siblings = [d for d in self.root.subtree(False) if d.name == self.name]
  499. for sibling in siblings:
  500. # Allow to have only one to be None or ''.
  501. if self.url != sibling.url and bool(self.url) == bool(sibling.url):
  502. raise gclient_utils.Error(
  503. ('Dependency %s specified more than once:\n'
  504. ' %s [%s]\n'
  505. 'vs\n'
  506. ' %s [%s]') % (
  507. self.name,
  508. sibling.hierarchy(),
  509. sibling.url,
  510. self.hierarchy(),
  511. self.url))
  512. # In theory we could keep it as a shadow of the other one. In
  513. # practice, simply ignore it.
  514. logging.warn('Won\'t process duplicate dependency %s' % sibling)
  515. return False
  516. return True
  517. def _postprocess_deps(self, deps, rel_prefix):
  518. """Performs post-processing of deps compared to what's in the DEPS file."""
  519. # Make sure the dict is mutable, e.g. in case it's frozen.
  520. deps = dict(deps)
  521. # If a line is in custom_deps, but not in the solution, we want to append
  522. # this line to the solution.
  523. for dep_name, dep_info in self.custom_deps.items():
  524. if dep_name not in deps:
  525. deps[dep_name] = {'url': dep_info, 'dep_type': 'git'}
  526. # Make child deps conditional on any parent conditions. This ensures that,
  527. # when flattened, recursed entries have the correct restrictions, even if
  528. # not explicitly set in the recursed DEPS file. For instance, if
  529. # "src/ios_foo" is conditional on "checkout_ios=True", then anything
  530. # recursively included by "src/ios_foo/DEPS" should also require
  531. # "checkout_ios=True".
  532. if self.condition:
  533. for value in deps.values():
  534. gclient_eval.UpdateCondition(value, 'and', self.condition)
  535. if rel_prefix:
  536. logging.warning('use_relative_paths enabled.')
  537. rel_deps = {}
  538. for d, url in deps.items():
  539. # normpath is required to allow DEPS to use .. in their
  540. # dependency local path.
  541. rel_deps[os.path.normpath(os.path.join(rel_prefix, d))] = url
  542. logging.warning('Updating deps by prepending %s.', rel_prefix)
  543. deps = rel_deps
  544. return deps
  545. def _deps_to_objects(self, deps, use_relative_paths):
  546. """Convert a deps dict to a dict of Dependency objects."""
  547. deps_to_add = []
  548. for name, dep_value in deps.items():
  549. should_process = self.should_process
  550. if dep_value is None:
  551. continue
  552. condition = dep_value.get('condition')
  553. dep_type = dep_value.get('dep_type')
  554. if condition and not self._get_option('process_all_deps', False):
  555. should_process = should_process and gclient_eval.EvaluateCondition(
  556. condition, self.get_vars())
  557. # The following option is only set by the 'revinfo' command.
  558. if self._get_option('ignore_dep_type', None) == dep_type:
  559. continue
  560. if dep_type == 'cipd':
  561. cipd_root = self.GetCipdRoot()
  562. for package in dep_value.get('packages', []):
  563. deps_to_add.append(
  564. CipdDependency(
  565. parent=self,
  566. name=name,
  567. dep_value=package,
  568. cipd_root=cipd_root,
  569. custom_vars=self.custom_vars,
  570. should_process=should_process,
  571. relative=use_relative_paths,
  572. condition=condition))
  573. else:
  574. url = dep_value.get('url')
  575. deps_to_add.append(
  576. GitDependency(
  577. parent=self,
  578. name=name,
  579. url=url,
  580. managed=True,
  581. custom_deps=None,
  582. custom_vars=self.custom_vars,
  583. custom_hooks=None,
  584. deps_file=self.recursedeps.get(name, self.deps_file),
  585. should_process=should_process,
  586. should_recurse=name in self.recursedeps,
  587. relative=use_relative_paths,
  588. condition=condition))
  589. deps_to_add.sort(key=lambda x: x.name)
  590. return deps_to_add
  591. def ParseDepsFile(self):
  592. """Parses the DEPS file for this dependency."""
  593. assert not self.deps_parsed
  594. assert not self.dependencies
  595. deps_content = None
  596. # First try to locate the configured deps file. If it's missing, fallback
  597. # to DEPS.
  598. deps_files = [self.deps_file]
  599. if 'DEPS' not in deps_files:
  600. deps_files.append('DEPS')
  601. for deps_file in deps_files:
  602. filepath = os.path.join(self.root.root_dir, self.name, deps_file)
  603. if os.path.isfile(filepath):
  604. logging.info(
  605. 'ParseDepsFile(%s): %s file found at %s', self.name, deps_file,
  606. filepath)
  607. break
  608. logging.info(
  609. 'ParseDepsFile(%s): No %s file found at %s', self.name, deps_file,
  610. filepath)
  611. if os.path.isfile(filepath):
  612. deps_content = gclient_utils.FileRead(filepath)
  613. logging.debug('ParseDepsFile(%s) read:\n%s', self.name, deps_content)
  614. local_scope = {}
  615. if deps_content:
  616. try:
  617. local_scope = gclient_eval.Parse(
  618. deps_content, self._get_option('validate_syntax', False),
  619. filepath, self.get_vars(), self.get_builtin_vars())
  620. except SyntaxError as e:
  621. gclient_utils.SyntaxErrorToError(filepath, e)
  622. if 'allowed_hosts' in local_scope:
  623. try:
  624. self._allowed_hosts = frozenset(local_scope.get('allowed_hosts'))
  625. except TypeError: # raised if non-iterable
  626. pass
  627. if not self._allowed_hosts:
  628. logging.warning("allowed_hosts is specified but empty %s",
  629. self._allowed_hosts)
  630. raise gclient_utils.Error(
  631. 'ParseDepsFile(%s): allowed_hosts must be absent '
  632. 'or a non-empty iterable' % self.name)
  633. self._gn_args_from = local_scope.get('gclient_gn_args_from')
  634. self._gn_args_file = local_scope.get('gclient_gn_args_file')
  635. self._gn_args = local_scope.get('gclient_gn_args', [])
  636. # It doesn't make sense to set all of these, since setting gn_args_from to
  637. # another DEPS will make gclient ignore any other local gn_args* settings.
  638. assert not (self._gn_args_from and self._gn_args_file), \
  639. 'Only specify one of "gclient_gn_args_from" or ' \
  640. '"gclient_gn_args_file + gclient_gn_args".'
  641. self._vars = local_scope.get('vars', {})
  642. if self.parent:
  643. for key, value in self.parent.get_vars().items():
  644. if key in self._vars:
  645. self._vars[key] = value
  646. # Since we heavily post-process things, freeze ones which should
  647. # reflect original state of DEPS.
  648. self._vars = gclient_utils.freeze(self._vars)
  649. # If use_relative_paths is set in the DEPS file, regenerate
  650. # the dictionary using paths relative to the directory containing
  651. # the DEPS file. Also update recursedeps if use_relative_paths is
  652. # enabled.
  653. # If the deps file doesn't set use_relative_paths, but the parent did
  654. # (and therefore set self.relative on this Dependency object), then we
  655. # want to modify the deps and recursedeps by prepending the parent
  656. # directory of this dependency.
  657. use_relative_paths = local_scope.get('use_relative_paths', False)
  658. rel_prefix = None
  659. if use_relative_paths:
  660. rel_prefix = self.name
  661. elif self._relative:
  662. rel_prefix = os.path.dirname(self.name)
  663. if 'recursion' in local_scope:
  664. logging.warning(
  665. '%s: Ignoring recursion = %d.', self.name, local_scope['recursion'])
  666. if 'recursedeps' in local_scope:
  667. for ent in local_scope['recursedeps']:
  668. if isinstance(ent, basestring):
  669. self.recursedeps[ent] = self.deps_file
  670. else: # (depname, depsfilename)
  671. self.recursedeps[ent[0]] = ent[1]
  672. logging.warning('Found recursedeps %r.', repr(self.recursedeps))
  673. if rel_prefix:
  674. logging.warning('Updating recursedeps by prepending %s.', rel_prefix)
  675. rel_deps = {}
  676. for depname, options in self.recursedeps.items():
  677. rel_deps[
  678. os.path.normpath(os.path.join(rel_prefix, depname))] = options
  679. self.recursedeps = rel_deps
  680. # To get gn_args from another DEPS, that DEPS must be recursed into.
  681. if self._gn_args_from:
  682. assert self.recursedeps and self._gn_args_from in self.recursedeps, \
  683. 'The "gclient_gn_args_from" value must be in recursedeps.'
  684. # If present, save 'target_os' in the local_target_os property.
  685. if 'target_os' in local_scope:
  686. self.local_target_os = local_scope['target_os']
  687. deps = local_scope.get('deps', {})
  688. deps_to_add = self._deps_to_objects(
  689. self._postprocess_deps(deps, rel_prefix), use_relative_paths)
  690. # compute which working directory should be used for hooks
  691. use_relative_hooks = local_scope.get('use_relative_hooks', False)
  692. hooks_cwd = self.root.root_dir
  693. if use_relative_hooks:
  694. if not use_relative_paths:
  695. raise gclient_utils.Error(
  696. 'ParseDepsFile(%s): use_relative_hooks must be used with '
  697. 'use_relative_paths' % self.name)
  698. hooks_cwd = os.path.join(hooks_cwd, self.name)
  699. logging.warning('Updating hook base working directory to %s.',
  700. hooks_cwd)
  701. # override named sets of hooks by the custom hooks
  702. hooks_to_run = []
  703. hook_names_to_suppress = [c.get('name', '') for c in self.custom_hooks]
  704. for hook in local_scope.get('hooks', []):
  705. if hook.get('name', '') not in hook_names_to_suppress:
  706. hooks_to_run.append(hook)
  707. # add the replacements and any additions
  708. for hook in self.custom_hooks:
  709. if 'action' in hook:
  710. hooks_to_run.append(hook)
  711. if self.should_recurse:
  712. self._pre_deps_hooks = [
  713. Hook.from_dict(hook, variables=self.get_vars(), verbose=True,
  714. conditions=self.condition, cwd_base=hooks_cwd)
  715. for hook in local_scope.get('pre_deps_hooks', [])
  716. ]
  717. self.add_dependencies_and_close(deps_to_add, hooks_to_run,
  718. hooks_cwd=hooks_cwd)
  719. logging.info('ParseDepsFile(%s) done' % self.name)
  720. def _get_option(self, attr, default):
  721. obj = self
  722. while not hasattr(obj, '_options'):
  723. obj = obj.parent
  724. return getattr(obj._options, attr, default)
  725. def add_dependencies_and_close(self, deps_to_add, hooks, hooks_cwd=None):
  726. """Adds the dependencies, hooks and mark the parsing as done."""
  727. if hooks_cwd == None:
  728. hooks_cwd = self.root.root_dir
  729. for dep in deps_to_add:
  730. if dep.verify_validity():
  731. self.add_dependency(dep)
  732. self._mark_as_parsed([
  733. Hook.from_dict(
  734. h, variables=self.get_vars(), verbose=self.root._options.verbose,
  735. conditions=self.condition, cwd_base=hooks_cwd)
  736. for h in hooks
  737. ])
  738. def findDepsFromNotAllowedHosts(self):
  739. """Returns a list of dependencies from not allowed hosts.
  740. If allowed_hosts is not set, allows all hosts and returns empty list.
  741. """
  742. if not self._allowed_hosts:
  743. return []
  744. bad_deps = []
  745. for dep in self._dependencies:
  746. # Don't enforce this for custom_deps.
  747. if dep.name in self._custom_deps:
  748. continue
  749. if isinstance(dep.url, basestring):
  750. parsed_url = urlparse.urlparse(dep.url)
  751. if parsed_url.netloc and parsed_url.netloc not in self._allowed_hosts:
  752. bad_deps.append(dep)
  753. return bad_deps
  754. def FuzzyMatchUrl(self, candidates):
  755. """Attempts to find this dependency in the list of candidates.
  756. It looks first for the URL of this dependency in the list of
  757. candidates. If it doesn't succeed, and the URL ends in '.git', it will try
  758. looking for the URL minus '.git'. Finally it will try to look for the name
  759. of the dependency.
  760. Args:
  761. candidates: list, dict. The list of candidates in which to look for this
  762. dependency. It can contain URLs as above, or dependency names like
  763. "src/some/dep".
  764. Returns:
  765. If this dependency is not found in the list of candidates, returns None.
  766. Otherwise, it returns under which name did we find this dependency:
  767. - Its parsed url: "https://example.com/src.git'
  768. - Its parsed url minus '.git': "https://example.com/src"
  769. - Its name: "src"
  770. """
  771. if self.url:
  772. origin, _ = gclient_utils.SplitUrlRevision(self.url)
  773. if origin in candidates:
  774. return origin
  775. if origin.endswith('.git') and origin[:-len('.git')] in candidates:
  776. return origin[:-len('.git')]
  777. if origin + '.git' in candidates:
  778. return origin + '.git'
  779. if self.name in candidates:
  780. return self.name
  781. return None
  782. # Arguments number differs from overridden method
  783. # pylint: disable=arguments-differ
  784. def run(self, revision_overrides, command, args, work_queue, options,
  785. patch_refs, target_branches):
  786. """Runs |command| then parse the DEPS file."""
  787. logging.info('Dependency(%s).run()' % self.name)
  788. assert self._file_list == []
  789. if not self.should_process:
  790. return
  791. # When running runhooks, there's no need to consult the SCM.
  792. # All known hooks are expected to run unconditionally regardless of working
  793. # copy state, so skip the SCM status check.
  794. run_scm = command not in (
  795. 'flatten', 'runhooks', 'recurse', 'validate', None)
  796. file_list = [] if not options.nohooks else None
  797. revision_override = revision_overrides.pop(
  798. self.FuzzyMatchUrl(revision_overrides), None)
  799. if not revision_override and not self.managed:
  800. revision_override = 'unmanaged'
  801. if run_scm and self.url:
  802. # Create a shallow copy to mutate revision.
  803. options = copy.copy(options)
  804. options.revision = revision_override
  805. self._used_revision = options.revision
  806. self._used_scm = self.CreateSCM(out_cb=work_queue.out_cb)
  807. self._got_revision = self._used_scm.RunCommand(command, options, args,
  808. file_list)
  809. patch_repo = self.url.split('@')[0]
  810. patch_ref = patch_refs.pop(self.FuzzyMatchUrl(patch_refs), None)
  811. target_branch = target_branches.pop(
  812. self.FuzzyMatchUrl(target_branches), None)
  813. if command == 'update' and patch_ref is not None:
  814. self._used_scm.apply_patch_ref(patch_repo, patch_ref, target_branch,
  815. options, file_list)
  816. if file_list:
  817. file_list = [os.path.join(self.name, f.strip()) for f in file_list]
  818. # TODO(phajdan.jr): We should know exactly when the paths are absolute.
  819. # Convert all absolute paths to relative.
  820. for i in range(len(file_list or [])):
  821. # It depends on the command being executed (like runhooks vs sync).
  822. if not os.path.isabs(file_list[i]):
  823. continue
  824. prefix = os.path.commonprefix(
  825. [self.root.root_dir.lower(), file_list[i].lower()])
  826. file_list[i] = file_list[i][len(prefix):]
  827. # Strip any leading path separators.
  828. while file_list[i].startswith(('\\', '/')):
  829. file_list[i] = file_list[i][1:]
  830. if self.should_recurse:
  831. self.ParseDepsFile()
  832. self._run_is_done(file_list or [])
  833. if self.should_recurse:
  834. if command in ('update', 'revert') and not options.noprehooks:
  835. self.RunPreDepsHooks()
  836. # Parse the dependencies of this dependency.
  837. for s in self.dependencies:
  838. if s.should_process:
  839. work_queue.enqueue(s)
  840. if command == 'recurse':
  841. # Skip file only checkout.
  842. scm = self.GetScmName()
  843. if not options.scm or scm in options.scm:
  844. cwd = os.path.normpath(os.path.join(self.root.root_dir, self.name))
  845. # Pass in the SCM type as an env variable. Make sure we don't put
  846. # unicode strings in the environment.
  847. env = os.environ.copy()
  848. if scm:
  849. env['GCLIENT_SCM'] = str(scm)
  850. if self.url:
  851. env['GCLIENT_URL'] = str(self.url)
  852. env['GCLIENT_DEP_PATH'] = str(self.name)
  853. if options.prepend_dir and scm == 'git':
  854. print_stdout = False
  855. def filter_fn(line):
  856. """Git-specific path marshaling. It is optimized for git-grep."""
  857. def mod_path(git_pathspec):
  858. match = re.match('^(\\S+?:)?([^\0]+)$', git_pathspec)
  859. modified_path = os.path.join(self.name, match.group(2))
  860. branch = match.group(1) or ''
  861. return '%s%s' % (branch, modified_path)
  862. match = re.match('^Binary file ([^\0]+) matches$', line)
  863. if match:
  864. print('Binary file %s matches\n' % mod_path(match.group(1)))
  865. return
  866. items = line.split('\0')
  867. if len(items) == 2 and items[1]:
  868. print('%s : %s' % (mod_path(items[0]), items[1]))
  869. elif len(items) >= 2:
  870. # Multiple null bytes or a single trailing null byte indicate
  871. # git is likely displaying filenames only (such as with -l)
  872. print('\n'.join(mod_path(path) for path in items if path))
  873. else:
  874. print(line)
  875. else:
  876. print_stdout = True
  877. filter_fn = None
  878. if self.url is None:
  879. print('Skipped omitted dependency %s' % cwd, file=sys.stderr)
  880. elif os.path.isdir(cwd):
  881. try:
  882. gclient_utils.CheckCallAndFilter(
  883. args, cwd=cwd, env=env, print_stdout=print_stdout,
  884. filter_fn=filter_fn,
  885. )
  886. except subprocess2.CalledProcessError:
  887. if not options.ignore:
  888. raise
  889. else:
  890. print('Skipped missing %s' % cwd, file=sys.stderr)
  891. def GetScmName(self):
  892. raise NotImplementedError()
  893. def CreateSCM(self, out_cb=None):
  894. raise NotImplementedError()
  895. def HasGNArgsFile(self):
  896. return self._gn_args_file is not None
  897. def WriteGNArgsFile(self):
  898. lines = ['# Generated from %r' % self.deps_file]
  899. variables = self.get_vars()
  900. for arg in self._gn_args:
  901. value = variables[arg]
  902. if isinstance(value, basestring):
  903. value = gclient_eval.EvaluateCondition(value, variables)
  904. lines.append('%s = %s' % (arg, ToGNString(value)))
  905. with open(os.path.join(self.root.root_dir, self._gn_args_file), 'w') as f:
  906. f.write('\n'.join(lines))
  907. @gclient_utils.lockedmethod
  908. def _run_is_done(self, file_list):
  909. # Both these are kept for hooks that are run as a separate tree traversal.
  910. self._file_list = file_list
  911. self._processed = True
  912. def GetHooks(self, options):
  913. """Evaluates all hooks, and return them in a flat list.
  914. RunOnDeps() must have been called before to load the DEPS.
  915. """
  916. result = []
  917. if not self.should_process or not self.should_recurse:
  918. # Don't run the hook when it is above recursion_limit.
  919. return result
  920. # If "--force" was specified, run all hooks regardless of what files have
  921. # changed.
  922. if self.deps_hooks:
  923. # TODO(maruel): If the user is using git, then we don't know
  924. # what files have changed so we always run all hooks. It'd be nice to fix
  925. # that.
  926. result.extend(self.deps_hooks)
  927. for s in self.dependencies:
  928. result.extend(s.GetHooks(options))
  929. return result
  930. def RunHooksRecursively(self, options, progress):
  931. assert self.hooks_ran == False
  932. self._hooks_ran = True
  933. hooks = self.GetHooks(options)
  934. if progress:
  935. progress._total = len(hooks)
  936. for hook in hooks:
  937. if progress:
  938. progress.update(extra=hook.name or '')
  939. hook.run()
  940. if progress:
  941. progress.end()
  942. def RunPreDepsHooks(self):
  943. assert self.processed
  944. assert self.deps_parsed
  945. assert not self.pre_deps_hooks_ran
  946. assert not self.hooks_ran
  947. for s in self.dependencies:
  948. assert not s.processed
  949. self._pre_deps_hooks_ran = True
  950. for hook in self.pre_deps_hooks:
  951. hook.run()
  952. def GetCipdRoot(self):
  953. if self.root is self:
  954. # Let's not infinitely recurse. If this is root and isn't an
  955. # instance of GClient, do nothing.
  956. return None
  957. return self.root.GetCipdRoot()
  958. def subtree(self, include_all):
  959. """Breadth first recursion excluding root node."""
  960. dependencies = self.dependencies
  961. for d in dependencies:
  962. if d.should_process or include_all:
  963. yield d
  964. for d in dependencies:
  965. for i in d.subtree(include_all):
  966. yield i
  967. @gclient_utils.lockedmethod
  968. def add_dependency(self, new_dep):
  969. self._dependencies.append(new_dep)
  970. @gclient_utils.lockedmethod
  971. def _mark_as_parsed(self, new_hooks):
  972. self._deps_hooks.extend(new_hooks)
  973. self._deps_parsed = True
  974. @property
  975. @gclient_utils.lockedmethod
  976. def dependencies(self):
  977. return tuple(self._dependencies)
  978. @property
  979. @gclient_utils.lockedmethod
  980. def deps_hooks(self):
  981. return tuple(self._deps_hooks)
  982. @property
  983. @gclient_utils.lockedmethod
  984. def pre_deps_hooks(self):
  985. return tuple(self._pre_deps_hooks)
  986. @property
  987. @gclient_utils.lockedmethod
  988. def deps_parsed(self):
  989. """This is purely for debugging purposes. It's not used anywhere."""
  990. return self._deps_parsed
  991. @property
  992. @gclient_utils.lockedmethod
  993. def processed(self):
  994. return self._processed
  995. @property
  996. @gclient_utils.lockedmethod
  997. def pre_deps_hooks_ran(self):
  998. return self._pre_deps_hooks_ran
  999. @property
  1000. @gclient_utils.lockedmethod
  1001. def hooks_ran(self):
  1002. return self._hooks_ran
  1003. @property
  1004. @gclient_utils.lockedmethod
  1005. def allowed_hosts(self):
  1006. return self._allowed_hosts
  1007. @property
  1008. @gclient_utils.lockedmethod
  1009. def file_list(self):
  1010. return tuple(self._file_list)
  1011. @property
  1012. def used_scm(self):
  1013. """SCMWrapper instance for this dependency or None if not processed yet."""
  1014. return self._used_scm
  1015. @property
  1016. @gclient_utils.lockedmethod
  1017. def got_revision(self):
  1018. return self._got_revision
  1019. @property
  1020. def file_list_and_children(self):
  1021. result = list(self.file_list)
  1022. for d in self.dependencies:
  1023. result.extend(d.file_list_and_children)
  1024. return tuple(result)
  1025. def __str__(self):
  1026. out = []
  1027. for i in ('name', 'url', 'custom_deps',
  1028. 'custom_vars', 'deps_hooks', 'file_list', 'should_process',
  1029. 'processed', 'hooks_ran', 'deps_parsed', 'requirements',
  1030. 'allowed_hosts'):
  1031. # First try the native property if it exists.
  1032. if hasattr(self, '_' + i):
  1033. value = getattr(self, '_' + i, False)
  1034. else:
  1035. value = getattr(self, i, False)
  1036. if value:
  1037. out.append('%s: %s' % (i, value))
  1038. for d in self.dependencies:
  1039. out.extend([' ' + x for x in str(d).splitlines()])
  1040. out.append('')
  1041. return '\n'.join(out)
  1042. def __repr__(self):
  1043. return '%s: %s' % (self.name, self.url)
  1044. def hierarchy(self, include_url=True):
  1045. """Returns a human-readable hierarchical reference to a Dependency."""
  1046. def format_name(d):
  1047. if include_url:
  1048. return '%s(%s)' % (d.name, d.url)
  1049. return d.name
  1050. out = format_name(self)
  1051. i = self.parent
  1052. while i and i.name:
  1053. out = '%s -> %s' % (format_name(i), out)
  1054. i = i.parent
  1055. return out
  1056. def hierarchy_data(self):
  1057. """Returns a machine-readable hierarchical reference to a Dependency."""
  1058. d = self
  1059. out = []
  1060. while d and d.name:
  1061. out.insert(0, (d.name, d.url))
  1062. d = d.parent
  1063. return tuple(out)
  1064. def get_builtin_vars(self):
  1065. return {
  1066. 'checkout_android': 'android' in self.target_os,
  1067. 'checkout_chromeos': 'chromeos' in self.target_os,
  1068. 'checkout_fuchsia': 'fuchsia' in self.target_os,
  1069. 'checkout_ios': 'ios' in self.target_os,
  1070. 'checkout_linux': 'unix' in self.target_os,
  1071. 'checkout_mac': 'mac' in self.target_os,
  1072. 'checkout_win': 'win' in self.target_os,
  1073. 'host_os': _detect_host_os(),
  1074. 'checkout_arm': 'arm' in self.target_cpu,
  1075. 'checkout_arm64': 'arm64' in self.target_cpu,
  1076. 'checkout_x86': 'x86' in self.target_cpu,
  1077. 'checkout_mips': 'mips' in self.target_cpu,
  1078. 'checkout_mips64': 'mips64' in self.target_cpu,
  1079. 'checkout_ppc': 'ppc' in self.target_cpu,
  1080. 'checkout_s390': 's390' in self.target_cpu,
  1081. 'checkout_x64': 'x64' in self.target_cpu,
  1082. 'host_cpu': detect_host_arch.HostArch(),
  1083. }
  1084. def get_vars(self):
  1085. """Returns a dictionary of effective variable values
  1086. (DEPS file contents with applied custom_vars overrides)."""
  1087. # Variable precedence (last has highest):
  1088. # - DEPS vars
  1089. # - parents, from first to last
  1090. # - built-in
  1091. # - custom_vars overrides
  1092. result = {}
  1093. result.update(self._vars)
  1094. if self.parent:
  1095. parent_vars = self.parent.get_vars()
  1096. result.update(parent_vars)
  1097. # Provide some built-in variables.
  1098. result.update(self.get_builtin_vars())
  1099. result.update(self.custom_vars or {})
  1100. return result
  1101. _PLATFORM_MAPPING = {
  1102. 'cygwin': 'win',
  1103. 'darwin': 'mac',
  1104. 'linux2': 'linux',
  1105. 'linux': 'linux',
  1106. 'win32': 'win',
  1107. 'aix6': 'aix',
  1108. }
  1109. def _detect_host_os():
  1110. return _PLATFORM_MAPPING[sys.platform]
  1111. class GitDependency(Dependency):
  1112. """A Dependency object that represents a single git checkout."""
  1113. #override
  1114. def GetScmName(self):
  1115. """Always 'git'."""
  1116. return 'git'
  1117. #override
  1118. def CreateSCM(self, out_cb=None):
  1119. """Create a Wrapper instance suitable for handling this git dependency."""
  1120. return gclient_scm.GitWrapper(
  1121. self.url, self.root.root_dir, self.name, self.outbuf, out_cb,
  1122. print_outbuf=self.print_outbuf)
  1123. class GClient(GitDependency):
  1124. """Object that represent a gclient checkout. A tree of Dependency(), one per
  1125. solution or DEPS entry."""
  1126. DEPS_OS_CHOICES = {
  1127. "aix6": "unix",
  1128. "win32": "win",
  1129. "win": "win",
  1130. "cygwin": "win",
  1131. "darwin": "mac",
  1132. "mac": "mac",
  1133. "unix": "unix",
  1134. "linux": "unix",
  1135. "linux2": "unix",
  1136. "linux3": "unix",
  1137. "android": "android",
  1138. "ios": "ios",
  1139. "fuchsia": "fuchsia",
  1140. "chromeos": "chromeos",
  1141. }
  1142. DEFAULT_CLIENT_FILE_TEXT = ("""\
  1143. solutions = [
  1144. { "name" : "%(solution_name)s",
  1145. "url" : "%(solution_url)s",
  1146. "deps_file" : "%(deps_file)s",
  1147. "managed" : %(managed)s,
  1148. "custom_deps" : {
  1149. },
  1150. "custom_vars": %(custom_vars)r,
  1151. },
  1152. ]
  1153. """)
  1154. DEFAULT_CLIENT_CACHE_DIR_TEXT = ("""\
  1155. cache_dir = %(cache_dir)r
  1156. """)
  1157. DEFAULT_SNAPSHOT_FILE_TEXT = ("""\
  1158. # Snapshot generated with gclient revinfo --snapshot
  1159. solutions = %(solution_list)s
  1160. """)
  1161. def __init__(self, root_dir, options):
  1162. # Do not change previous behavior. Only solution level and immediate DEPS
  1163. # are processed.
  1164. self._recursion_limit = 2
  1165. super(GClient, self).__init__(
  1166. parent=None,
  1167. name=None,
  1168. url=None,
  1169. managed=True,
  1170. custom_deps=None,
  1171. custom_vars=None,
  1172. custom_hooks=None,
  1173. deps_file='unused',
  1174. should_process=True,
  1175. should_recurse=True,
  1176. relative=None,
  1177. condition=None,
  1178. print_outbuf=True)
  1179. self._options = options
  1180. if options.deps_os:
  1181. enforced_os = options.deps_os.split(',')
  1182. else:
  1183. enforced_os = [self.DEPS_OS_CHOICES.get(sys.platform, 'unix')]
  1184. if 'all' in enforced_os:
  1185. enforced_os = self.DEPS_OS_CHOICES.values()
  1186. self._enforced_os = tuple(set(enforced_os))
  1187. self._enforced_cpu = detect_host_arch.HostArch(),
  1188. self._root_dir = root_dir
  1189. self._cipd_root = None
  1190. self.config_content = None
  1191. def _CheckConfig(self):
  1192. """Verify that the config matches the state of the existing checked-out
  1193. solutions."""
  1194. for dep in self.dependencies:
  1195. if dep.managed and dep.url:
  1196. scm = dep.CreateSCM()
  1197. actual_url = scm.GetActualRemoteURL(self._options)
  1198. if actual_url and not scm.DoesRemoteURLMatch(self._options):
  1199. mirror = scm.GetCacheMirror()
  1200. if mirror:
  1201. mirror_string = '%s (exists=%s)' % (mirror.mirror_path,
  1202. mirror.exists())
  1203. else:
  1204. mirror_string = 'not used'
  1205. raise gclient_utils.Error(
  1206. '''
  1207. Your .gclient file seems to be broken. The requested URL is different from what
  1208. is actually checked out in %(checkout_path)s.
  1209. The .gclient file contains:
  1210. URL: %(expected_url)s (%(expected_scm)s)
  1211. Cache mirror: %(mirror_string)s
  1212. The local checkout in %(checkout_path)s reports:
  1213. %(actual_url)s (%(actual_scm)s)
  1214. You should ensure that the URL listed in .gclient is correct and either change
  1215. it or fix the checkout.
  1216. ''' % {'checkout_path': os.path.join(self.root_dir, dep.name),
  1217. 'expected_url': dep.url,
  1218. 'expected_scm': dep.GetScmName(),
  1219. 'mirror_string': mirror_string,
  1220. 'actual_url': actual_url,
  1221. 'actual_scm': dep.GetScmName()})
  1222. def SetConfig(self, content):
  1223. assert not self.dependencies
  1224. config_dict = {}
  1225. self.config_content = content
  1226. try:
  1227. exec(content, config_dict)
  1228. except SyntaxError as e:
  1229. gclient_utils.SyntaxErrorToError('.gclient', e)
  1230. # Append any target OS that is not already being enforced to the tuple.
  1231. target_os = config_dict.get('target_os', [])
  1232. if config_dict.get('target_os_only', False):
  1233. self._enforced_os = tuple(set(target_os))
  1234. else:
  1235. self._enforced_os = tuple(set(self._enforced_os).union(target_os))
  1236. # Append any target CPU that is not already being enforced to the tuple.
  1237. target_cpu = config_dict.get('target_cpu', [])
  1238. if config_dict.get('target_cpu_only', False):
  1239. self._enforced_cpu = tuple(set(target_cpu))
  1240. else:
  1241. self._enforced_cpu = tuple(set(self._enforced_cpu).union(target_cpu))
  1242. cache_dir = config_dict.get('cache_dir', UNSET_CACHE_DIR)
  1243. if cache_dir is not UNSET_CACHE_DIR:
  1244. if cache_dir:
  1245. cache_dir = os.path.join(self.root_dir, cache_dir)
  1246. cache_dir = os.path.abspath(cache_dir)
  1247. git_cache.Mirror.SetCachePath(cache_dir)
  1248. if not target_os and config_dict.get('target_os_only', False):
  1249. raise gclient_utils.Error('Can\'t use target_os_only if target_os is '
  1250. 'not specified')
  1251. if not target_cpu and config_dict.get('target_cpu_only', False):
  1252. raise gclient_utils.Error('Can\'t use target_cpu_only if target_cpu is '
  1253. 'not specified')
  1254. deps_to_add = []
  1255. for s in config_dict.get('solutions', []):
  1256. try:
  1257. deps_to_add.append(GitDependency(
  1258. parent=self,
  1259. name=s['name'],
  1260. url=s['url'],
  1261. managed=s.get('managed', True),
  1262. custom_deps=s.get('custom_deps', {}),
  1263. custom_vars=s.get('custom_vars', {}),
  1264. custom_hooks=s.get('custom_hooks', []),
  1265. deps_file=s.get('deps_file', 'DEPS'),
  1266. should_process=True,
  1267. should_recurse=True,
  1268. relative=None,
  1269. condition=None,
  1270. print_outbuf=True))
  1271. except KeyError:
  1272. raise gclient_utils.Error('Invalid .gclient file. Solution is '
  1273. 'incomplete: %s' % s)
  1274. metrics.collector.add(
  1275. 'project_urls',
  1276. [
  1277. dep.FuzzyMatchUrl(metrics_utils.KNOWN_PROJECT_URLS)
  1278. for dep in deps_to_add
  1279. if dep.FuzzyMatchUrl(metrics_utils.KNOWN_PROJECT_URLS)
  1280. ]
  1281. )
  1282. self.add_dependencies_and_close(deps_to_add, config_dict.get('hooks', []))
  1283. logging.info('SetConfig() done')
  1284. def SaveConfig(self):
  1285. gclient_utils.FileWrite(os.path.join(self.root_dir,
  1286. self._options.config_filename),
  1287. self.config_content)
  1288. @staticmethod
  1289. def LoadCurrentConfig(options):
  1290. """Searches for and loads a .gclient file relative to the current working
  1291. dir. Returns a GClient object."""
  1292. if options.spec:
  1293. client = GClient('.', options)
  1294. client.SetConfig(options.spec)
  1295. else:
  1296. if options.verbose:
  1297. print('Looking for %s starting from %s\n' % (
  1298. options.config_filename, os.getcwd()))
  1299. path = gclient_paths.FindGclientRoot(os.getcwd(), options.config_filename)
  1300. if not path:
  1301. if options.verbose:
  1302. print('Couldn\'t find configuration file.')
  1303. return None
  1304. client = GClient(path, options)
  1305. client.SetConfig(gclient_utils.FileRead(
  1306. os.path.join(path, options.config_filename)))
  1307. if (options.revisions and
  1308. len(client.dependencies) > 1 and
  1309. any('@' not in r for r in options.revisions)):
  1310. print(
  1311. ('You must specify the full solution name like --revision %s@%s\n'
  1312. 'when you have multiple solutions setup in your .gclient file.\n'
  1313. 'Other solutions present are: %s.') % (
  1314. client.dependencies[0].name,
  1315. options.revisions[0],
  1316. ', '.join(s.name for s in client.dependencies[1:])),
  1317. file=sys.stderr)
  1318. return client
  1319. def SetDefaultConfig(self, solution_name, deps_file, solution_url,
  1320. managed=True, cache_dir=UNSET_CACHE_DIR,
  1321. custom_vars=None):
  1322. text = self.DEFAULT_CLIENT_FILE_TEXT
  1323. format_dict = {
  1324. 'solution_name': solution_name,
  1325. 'solution_url': solution_url,
  1326. 'deps_file': deps_file,
  1327. 'managed': managed,
  1328. 'custom_vars': custom_vars or {},
  1329. }
  1330. if cache_dir is not UNSET_CACHE_DIR:
  1331. text += self.DEFAULT_CLIENT_CACHE_DIR_TEXT
  1332. format_dict['cache_dir'] = cache_dir
  1333. self.SetConfig(text % format_dict)
  1334. def _SaveEntries(self):
  1335. """Creates a .gclient_entries file to record the list of unique checkouts.
  1336. The .gclient_entries file lives in the same directory as .gclient.
  1337. """
  1338. # Sometimes pprint.pformat will use {', sometimes it'll use { ' ... It
  1339. # makes testing a bit too fun.
  1340. result = 'entries = {\n'
  1341. for entry in self.root.subtree(False):
  1342. result += ' %s: %s,\n' % (pprint.pformat(entry.name),
  1343. pprint.pformat(entry.url))
  1344. result += '}\n'
  1345. file_path = os.path.join(self.root_dir, self._options.entries_filename)
  1346. logging.debug(result)
  1347. gclient_utils.FileWrite(file_path, result)
  1348. def _ReadEntries(self):
  1349. """Read the .gclient_entries file for the given client.
  1350. Returns:
  1351. A sequence of solution names, which will be empty if there is the
  1352. entries file hasn't been created yet.
  1353. """
  1354. scope = {}
  1355. filename = os.path.join(self.root_dir, self._options.entries_filename)
  1356. if not os.path.exists(filename):
  1357. return {}
  1358. try:
  1359. exec(gclient_utils.FileRead(filename), scope)
  1360. except SyntaxError as e:
  1361. gclient_utils.SyntaxErrorToError(filename, e)
  1362. return scope.get('entries', {})
  1363. def _EnforceRevisions(self):
  1364. """Checks for revision overrides."""
  1365. revision_overrides = {}
  1366. if self._options.head:
  1367. return revision_overrides
  1368. if not self._options.revisions:
  1369. return revision_overrides
  1370. solutions_names = [s.name for s in self.dependencies]
  1371. index = 0
  1372. for revision in self._options.revisions:
  1373. if not '@' in revision:
  1374. # Support for --revision 123
  1375. revision = '%s@%s' % (solutions_names[index], revision)
  1376. name, rev = revision.split('@', 1)
  1377. revision_overrides[name] = rev
  1378. index += 1
  1379. return revision_overrides
  1380. def _EnforcePatchRefsAndBranches(self):
  1381. """Checks for patch refs."""
  1382. patch_refs = {}
  1383. target_branches = {}
  1384. if not self._options.patch_refs:
  1385. return patch_refs, target_branches
  1386. for given_patch_ref in self._options.patch_refs:
  1387. patch_repo, _, patch_ref = given_patch_ref.partition('@')
  1388. if not patch_repo or not patch_ref or ':' not in patch_ref:
  1389. raise gclient_utils.Error(
  1390. 'Wrong revision format: %s should be of the form '
  1391. 'patch_repo@target_branch:patch_ref.' % given_patch_ref)
  1392. target_branch, _, patch_ref = patch_ref.partition(':')
  1393. target_branches[patch_repo] = target_branch
  1394. patch_refs[patch_repo] = patch_ref
  1395. return patch_refs, target_branches
  1396. def _RemoveUnversionedGitDirs(self):
  1397. """Remove directories that are no longer part of the checkout.
  1398. Notify the user if there is an orphaned entry in their working copy.
  1399. Only delete the directory if there are no changes in it, and
  1400. delete_unversioned_trees is set to true.
  1401. """
  1402. entries = [i.name for i in self.root.subtree(False) if i.url]
  1403. full_entries = [os.path.join(self.root_dir, e.replace('/', os.path.sep))
  1404. for e in entries]
  1405. for entry, prev_url in self._ReadEntries().items():
  1406. if not prev_url:
  1407. # entry must have been overridden via .gclient custom_deps
  1408. continue
  1409. # Fix path separator on Windows.
  1410. entry_fixed = entry.replace('/', os.path.sep)
  1411. e_dir = os.path.join(self.root_dir, entry_fixed)
  1412. # Use entry and not entry_fixed there.
  1413. if (entry not in entries and
  1414. (not any(path.startswith(entry + '/') for path in entries)) and
  1415. os.path.exists(e_dir)):
  1416. # The entry has been removed from DEPS.
  1417. scm = gclient_scm.GitWrapper(
  1418. prev_url, self.root_dir, entry_fixed, self.outbuf)
  1419. # Check to see if this directory is now part of a higher-up checkout.
  1420. scm_root = None
  1421. try:
  1422. scm_root = gclient_scm.scm.GIT.GetCheckoutRoot(scm.checkout_path)
  1423. except subprocess2.CalledProcessError:
  1424. pass
  1425. if not scm_root:
  1426. logging.warning('Could not find checkout root for %s. Unable to '
  1427. 'determine whether it is part of a higher-level '
  1428. 'checkout, so not removing.' % entry)
  1429. continue
  1430. # This is to handle the case of third_party/WebKit migrating from
  1431. # being a DEPS entry to being part of the main project.
  1432. # If the subproject is a Git project, we need to remove its .git
  1433. # folder. Otherwise git operations on that folder will have different
  1434. # effects depending on the current working directory.
  1435. if os.path.abspath(scm_root) == os.path.abspath(e_dir):
  1436. e_par_dir = os.path.join(e_dir, os.pardir)
  1437. if gclient_scm.scm.GIT.IsInsideWorkTree(e_par_dir):
  1438. par_scm_root = gclient_scm.scm.GIT.GetCheckoutRoot(e_par_dir)
  1439. # rel_e_dir : relative path of entry w.r.t. its parent repo.
  1440. rel_e_dir = os.path.relpath(e_dir, par_scm_root)
  1441. if gclient_scm.scm.GIT.IsDirectoryVersioned(
  1442. par_scm_root, rel_e_dir):
  1443. save_dir = scm.GetGitBackupDirPath()
  1444. # Remove any eventual stale backup dir for the same project.
  1445. if os.path.exists(save_dir):
  1446. gclient_utils.rmtree(save_dir)
  1447. os.rename(os.path.join(e_dir, '.git'), save_dir)
  1448. # When switching between the two states (entry/ is a subproject
  1449. # -> entry/ is part of the outer project), it is very likely
  1450. # that some files are changed in the checkout, unless we are
  1451. # jumping *exactly* across the commit which changed just DEPS.
  1452. # In such case we want to cleanup any eventual stale files
  1453. # (coming from the old subproject) in order to end up with a
  1454. # clean checkout.
  1455. gclient_scm.scm.GIT.CleanupDir(par_scm_root, rel_e_dir)
  1456. assert not os.path.exists(os.path.join(e_dir, '.git'))
  1457. print('\nWARNING: \'%s\' has been moved from DEPS to a higher '
  1458. 'level checkout. The git folder containing all the local'
  1459. ' branches has been saved to %s.\n'
  1460. 'If you don\'t care about its state you can safely '
  1461. 'remove that folder to free up space.' % (entry, save_dir))
  1462. continue
  1463. if scm_root in full_entries:
  1464. logging.info('%s is part of a higher level checkout, not removing',
  1465. scm.GetCheckoutRoot())
  1466. continue
  1467. file_list = []
  1468. scm.status(self._options, [], file_list)
  1469. modified_files = file_list != []
  1470. if (not self._options.delete_unversioned_trees or
  1471. (modified_files and not self._options.force)):
  1472. # There are modified files in this entry. Keep warning until
  1473. # removed.
  1474. self.add_dependency(
  1475. GitDependency(
  1476. parent=self,
  1477. name=entry,
  1478. url=prev_url,
  1479. managed=False,
  1480. custom_deps={},
  1481. custom_vars={},
  1482. custom_hooks=[],
  1483. deps_file=None,
  1484. should_process=True,
  1485. should_recurse=False,
  1486. relative=None,
  1487. condition=None))
  1488. if modified_files and self._options.delete_unversioned_trees:
  1489. print('\nWARNING: \'%s\' is no longer part of this client.\n'
  1490. 'Despite running \'gclient sync -D\' no action was taken '
  1491. 'as there are modifications.\nIt is recommended you revert '
  1492. 'all changes or run \'gclient sync -D --force\' next '
  1493. 'time.' % entry_fixed)
  1494. else:
  1495. print('\nWARNING: \'%s\' is no longer part of this client.\n'
  1496. 'It is recommended that you manually remove it or use '
  1497. '\'gclient sync -D\' next time.' % entry_fixed)
  1498. else:
  1499. # Delete the entry
  1500. print('\n________ deleting \'%s\' in \'%s\'' % (
  1501. entry_fixed, self.root_dir))
  1502. gclient_utils.rmtree(e_dir)
  1503. # record the current list of entries for next time
  1504. self._SaveEntries()
  1505. def RunOnDeps(self, command, args, ignore_requirements=False, progress=True):
  1506. """Runs a command on each dependency in a client and its dependencies.
  1507. Args:
  1508. command: The command to use (e.g., 'status' or 'diff')
  1509. args: list of str - extra arguments to add to the command line.
  1510. """
  1511. if not self.dependencies:
  1512. raise gclient_utils.Error('No solution specified')
  1513. revision_overrides = {}
  1514. patch_refs = {}
  1515. target_branches = {}
  1516. # It's unnecessary to check for revision overrides for 'recurse'.
  1517. # Save a few seconds by not calling _EnforceRevisions() in that case.
  1518. if command not in ('diff', 'recurse', 'runhooks', 'status', 'revert',
  1519. 'validate'):
  1520. self._CheckConfig()
  1521. revision_overrides = self._EnforceRevisions()
  1522. if command == 'update':
  1523. patch_refs, target_branches = self._EnforcePatchRefsAndBranches()
  1524. # Disable progress for non-tty stdout.
  1525. should_show_progress = (
  1526. setup_color.IS_TTY and not self._options.verbose and progress)
  1527. pm = None
  1528. if should_show_progress:
  1529. if command in ('update', 'revert'):
  1530. pm = Progress('Syncing projects', 1)
  1531. elif command in ('recurse', 'validate'):
  1532. pm = Progress(' '.join(args), 1)
  1533. work_queue = gclient_utils.ExecutionQueue(
  1534. self._options.jobs, pm, ignore_requirements=ignore_requirements,
  1535. verbose=self._options.verbose)
  1536. for s in self.dependencies:
  1537. if s.should_process:
  1538. work_queue.enqueue(s)
  1539. work_queue.flush(revision_overrides, command, args, options=self._options,
  1540. patch_refs=patch_refs, target_branches=target_branches)
  1541. if revision_overrides:
  1542. print('Please fix your script, having invalid --revision flags will soon '
  1543. 'be considered an error.', file=sys.stderr)
  1544. if patch_refs:
  1545. raise gclient_utils.Error(
  1546. 'The following --patch-ref flags were not used. Please fix it:\n%s' %
  1547. ('\n'.join(
  1548. patch_repo + '@' + patch_ref
  1549. for patch_repo, patch_ref in patch_refs.items())))
  1550. # Once all the dependencies have been processed, it's now safe to write
  1551. # out the gn_args_file and run the hooks.
  1552. if command == 'update':
  1553. gn_args_dep = self.dependencies[0]
  1554. if gn_args_dep._gn_args_from:
  1555. deps_map = dict([(dep.name, dep) for dep in gn_args_dep.dependencies])
  1556. gn_args_dep = deps_map.get(gn_args_dep._gn_args_from)
  1557. if gn_args_dep and gn_args_dep.HasGNArgsFile():
  1558. gn_args_dep.WriteGNArgsFile()
  1559. self._RemoveUnversionedGitDirs()
  1560. # Sync CIPD dependencies once removed deps are deleted. In case a git
  1561. # dependency was moved to CIPD, we want to remove the old git directory
  1562. # first and then sync the CIPD dep.
  1563. if self._cipd_root:
  1564. self._cipd_root.run(command)
  1565. if not self._options.nohooks:
  1566. if should_show_progress:
  1567. pm = Progress('Running hooks', 1)
  1568. self.RunHooksRecursively(self._options, pm)
  1569. return 0
  1570. def PrintRevInfo(self):
  1571. if not self.dependencies:
  1572. raise gclient_utils.Error('No solution specified')
  1573. # Load all the settings.
  1574. work_queue = gclient_utils.ExecutionQueue(
  1575. self._options.jobs, None, False, verbose=self._options.verbose)
  1576. for s in self.dependencies:
  1577. if s.should_process:
  1578. work_queue.enqueue(s)
  1579. work_queue.flush({}, None, [], options=self._options, patch_refs=None,
  1580. target_branches=None)
  1581. def ShouldPrintRevision(dep):
  1582. return (not self._options.filter
  1583. or dep.FuzzyMatchUrl(self._options.filter))
  1584. if self._options.snapshot:
  1585. json_output = []
  1586. # First level at .gclient
  1587. for d in self.dependencies:
  1588. entries = {}
  1589. def GrabDeps(dep):
  1590. """Recursively grab dependencies."""
  1591. for d in dep.dependencies:
  1592. d.PinToActualRevision()
  1593. if ShouldPrintRevision(d):
  1594. entries[d.name] = d.url
  1595. GrabDeps(d)
  1596. GrabDeps(d)
  1597. json_output.append({
  1598. 'name': d.name,
  1599. 'solution_url': d.url,
  1600. 'deps_file': d.deps_file,
  1601. 'managed': d.managed,
  1602. 'custom_deps': entries,
  1603. })
  1604. if self._options.output_json == '-':
  1605. print(json.dumps(json_output, indent=2, separators=(',', ': ')))
  1606. elif self._options.output_json:
  1607. with open(self._options.output_json, 'w') as f:
  1608. json.dump(json_output, f)
  1609. else:
  1610. # Print the snapshot configuration file
  1611. print(self.DEFAULT_SNAPSHOT_FILE_TEXT % {
  1612. 'solution_list': pprint.pformat(json_output, indent=2),
  1613. })
  1614. else:
  1615. entries = {}
  1616. for d in self.root.subtree(False):
  1617. if self._options.actual:
  1618. d.PinToActualRevision()
  1619. if ShouldPrintRevision(d):
  1620. entries[d.name] = d.url
  1621. if self._options.output_json:
  1622. json_output = {
  1623. name: {
  1624. 'url': rev.split('@')[0] if rev else None,
  1625. 'rev': rev.split('@')[1] if rev and '@' in rev else None,
  1626. }
  1627. for name, rev in entries.items()
  1628. }
  1629. if self._options.output_json == '-':
  1630. print(json.dumps(json_output, indent=2, separators=(',', ': ')))
  1631. else:
  1632. with open(self._options.output_json, 'w') as f:
  1633. json.dump(json_output, f)
  1634. else:
  1635. keys = sorted(entries.keys())
  1636. for x in keys:
  1637. print('%s: %s' % (x, entries[x]))
  1638. logging.info(str(self))
  1639. def ParseDepsFile(self):
  1640. """No DEPS to parse for a .gclient file."""
  1641. raise gclient_utils.Error('Internal error')
  1642. def PrintLocationAndContents(self):
  1643. # Print out the .gclient file. This is longer than if we just printed the
  1644. # client dict, but more legible, and it might contain helpful comments.
  1645. print('Loaded .gclient config in %s:\n%s' % (
  1646. self.root_dir, self.config_content))
  1647. def GetCipdRoot(self):
  1648. if not self._cipd_root:
  1649. self._cipd_root = gclient_scm.CipdRoot(
  1650. self.root_dir,
  1651. # TODO(jbudorick): Support other service URLs as necessary.
  1652. # Service URLs should be constant over the scope of a cipd
  1653. # root, so a var per DEPS file specifying the service URL
  1654. # should suffice.
  1655. 'https://chrome-infra-packages.appspot.com')
  1656. return self._cipd_root
  1657. @property
  1658. def root_dir(self):
  1659. """Root directory of gclient checkout."""
  1660. return self._root_dir
  1661. @property
  1662. def enforced_os(self):
  1663. """What deps_os entries that are to be parsed."""
  1664. return self._enforced_os
  1665. @property
  1666. def target_os(self):
  1667. return self._enforced_os
  1668. @property
  1669. def target_cpu(self):
  1670. return self._enforced_cpu
  1671. class CipdDependency(Dependency):
  1672. """A Dependency object that represents a single CIPD package."""
  1673. def __init__(
  1674. self, parent, name, dep_value, cipd_root,
  1675. custom_vars, should_process, relative, condition):
  1676. package = dep_value['package']
  1677. version = dep_value['version']
  1678. url = urlparse.urljoin(
  1679. cipd_root.service_url, '%s@%s' % (package, version))
  1680. super(CipdDependency, self).__init__(
  1681. parent=parent,
  1682. name=name + ':' + package,
  1683. url=url,
  1684. managed=None,
  1685. custom_deps=None,
  1686. custom_vars=custom_vars,
  1687. custom_hooks=None,
  1688. deps_file=None,
  1689. should_process=should_process,
  1690. should_recurse=False,
  1691. relative=relative,
  1692. condition=condition)
  1693. self._cipd_package = None
  1694. self._cipd_root = cipd_root
  1695. # CIPD wants /-separated paths, even on Windows.
  1696. native_subdir_path = os.path.relpath(
  1697. os.path.join(self.root.root_dir, name), cipd_root.root_dir)
  1698. self._cipd_subdir = posixpath.join(*native_subdir_path.split(os.sep))
  1699. self._package_name = package
  1700. self._package_version = version
  1701. #override
  1702. def run(self, revision_overrides, command, args, work_queue, options,
  1703. patch_refs, target_branches):
  1704. """Runs |command| then parse the DEPS file."""
  1705. logging.info('CipdDependency(%s).run()' % self.name)
  1706. if not self.should_process:
  1707. return
  1708. self._CreatePackageIfNecessary()
  1709. super(CipdDependency, self).run(revision_overrides, command, args,
  1710. work_queue, options, patch_refs,
  1711. target_branches)
  1712. def _CreatePackageIfNecessary(self):
  1713. # We lazily create the CIPD package to make sure that only packages
  1714. # that we want (as opposed to all packages defined in all DEPS files
  1715. # we parse) get added to the root and subsequently ensured.
  1716. if not self._cipd_package:
  1717. self._cipd_package = self._cipd_root.add_package(
  1718. self._cipd_subdir, self._package_name, self._package_version)
  1719. def ParseDepsFile(self):
  1720. """CIPD dependencies are not currently allowed to have nested deps."""
  1721. self.add_dependencies_and_close([], [])
  1722. #override
  1723. def verify_validity(self):
  1724. """CIPD dependencies allow duplicate name for packages in same directory."""
  1725. logging.info('Dependency(%s).verify_validity()' % self.name)
  1726. return True
  1727. #override
  1728. def GetScmName(self):
  1729. """Always 'cipd'."""
  1730. return 'cipd'
  1731. #override
  1732. def CreateSCM(self, out_cb=None):
  1733. """Create a Wrapper instance suitable for handling this CIPD dependency."""
  1734. self._CreatePackageIfNecessary()
  1735. return gclient_scm.CipdWrapper(
  1736. self.url, self.root.root_dir, self.name, self.outbuf, out_cb,
  1737. root=self._cipd_root, package=self._cipd_package)
  1738. def hierarchy(self, include_url=False):
  1739. return self.parent.hierarchy(include_url) + ' -> ' + self._cipd_subdir
  1740. def ToLines(self):
  1741. """Return a list of lines representing this in a DEPS file."""
  1742. def escape_cipd_var(package):
  1743. return package.replace('{', '{{').replace('}', '}}')
  1744. s = []
  1745. self._CreatePackageIfNecessary()
  1746. if self._cipd_package.authority_for_subdir:
  1747. condition_part = ([' "condition": %r,' % self.condition]
  1748. if self.condition else [])
  1749. s.extend([
  1750. ' # %s' % self.hierarchy(include_url=False),
  1751. ' "%s": {' % (self.name.split(':')[0],),
  1752. ' "packages": [',
  1753. ])
  1754. for p in sorted(
  1755. self._cipd_root.packages(self._cipd_subdir),
  1756. key=lambda x: x.name):
  1757. s.extend([
  1758. ' {',
  1759. ' "package": "%s",' % escape_cipd_var(p.name),
  1760. ' "version": "%s",' % p.version,
  1761. ' },',
  1762. ])
  1763. s.extend([
  1764. ' ],',
  1765. ' "dep_type": "cipd",',
  1766. ] + condition_part + [
  1767. ' },',
  1768. '',
  1769. ])
  1770. return s
  1771. #### gclient commands.
  1772. @subcommand.usage('[command] [args ...]')
  1773. @metrics.collector.collect_metrics('gclient recurse')
  1774. def CMDrecurse(parser, args):
  1775. """Operates [command args ...] on all the dependencies.
  1776. Runs a shell command on all entries.
  1777. Sets GCLIENT_DEP_PATH environment variable as the dep's relative location to
  1778. root directory of the checkout.
  1779. """
  1780. # Stop parsing at the first non-arg so that these go through to the command
  1781. parser.disable_interspersed_args()
  1782. parser.add_option('-s', '--scm', action='append', default=[],
  1783. help='Choose scm types to operate upon.')
  1784. parser.add_option('-i', '--ignore', action='store_true',
  1785. help='Ignore non-zero return codes from subcommands.')
  1786. parser.add_option('--prepend-dir', action='store_true',
  1787. help='Prepend relative dir for use with git <cmd> --null.')
  1788. parser.add_option('--no-progress', action='store_true',
  1789. help='Disable progress bar that shows sub-command updates')
  1790. options, args = parser.parse_args(args)
  1791. if not args:
  1792. print('Need to supply a command!', file=sys.stderr)
  1793. return 1
  1794. root_and_entries = gclient_utils.GetGClientRootAndEntries()
  1795. if not root_and_entries:
  1796. print(
  1797. 'You need to run gclient sync at least once to use \'recurse\'.\n'
  1798. 'This is because .gclient_entries needs to exist and be up to date.',
  1799. file=sys.stderr)
  1800. return 1
  1801. # Normalize options.scm to a set()
  1802. scm_set = set()
  1803. for scm in options.scm:
  1804. scm_set.update(scm.split(','))
  1805. options.scm = scm_set
  1806. options.nohooks = True
  1807. client = GClient.LoadCurrentConfig(options)
  1808. if not client:
  1809. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1810. return client.RunOnDeps('recurse', args, ignore_requirements=True,
  1811. progress=not options.no_progress)
  1812. @subcommand.usage('[args ...]')
  1813. @metrics.collector.collect_metrics('gclient fetch')
  1814. def CMDfetch(parser, args):
  1815. """Fetches upstream commits for all modules.
  1816. Completely git-specific. Simply runs 'git fetch [args ...]' for each module.
  1817. """
  1818. (options, args) = parser.parse_args(args)
  1819. return CMDrecurse(OptionParser(), [
  1820. '--jobs=%d' % options.jobs, '--scm=git', 'git', 'fetch'] + args)
  1821. class Flattener(object):
  1822. """Flattens a gclient solution."""
  1823. def __init__(self, client, pin_all_deps=False):
  1824. """Constructor.
  1825. Arguments:
  1826. client (GClient): client to flatten
  1827. pin_all_deps (bool): whether to pin all deps, even if they're not pinned
  1828. in DEPS
  1829. """
  1830. self._client = client
  1831. self._deps_string = None
  1832. self._deps_files = set()
  1833. self._allowed_hosts = set()
  1834. self._deps = {}
  1835. self._hooks = []
  1836. self._pre_deps_hooks = []
  1837. self._vars = {}
  1838. self._flatten(pin_all_deps=pin_all_deps)
  1839. @property
  1840. def deps_string(self):
  1841. assert self._deps_string is not None
  1842. return self._deps_string
  1843. @property
  1844. def deps_files(self):
  1845. return self._deps_files
  1846. def _pin_dep(self, dep):
  1847. """Pins a dependency to specific full revision sha.
  1848. Arguments:
  1849. dep (Dependency): dependency to process
  1850. """
  1851. if dep.url is None:
  1852. return
  1853. # Make sure the revision is always fully specified (a hash),
  1854. # as opposed to refs or tags which might change. Similarly,
  1855. # shortened shas might become ambiguous; make sure to always
  1856. # use full one for pinning.
  1857. revision = gclient_utils.SplitUrlRevision(dep.url)[1]
  1858. if not revision or not gclient_utils.IsFullGitSha(revision):
  1859. dep.PinToActualRevision()
  1860. def _flatten(self, pin_all_deps=False):
  1861. """Runs the flattener. Saves resulting DEPS string.
  1862. Arguments:
  1863. pin_all_deps (bool): whether to pin all deps, even if they're not pinned
  1864. in DEPS
  1865. """
  1866. for solution in self._client.dependencies:
  1867. self._add_dep(solution)
  1868. self._flatten_dep(solution)
  1869. if pin_all_deps:
  1870. for dep in self._deps.values():
  1871. self._pin_dep(dep)
  1872. def add_deps_file(dep):
  1873. # Only include DEPS files referenced by recursedeps.
  1874. if not dep.should_recurse:
  1875. return
  1876. deps_file = dep.deps_file
  1877. deps_path = os.path.join(self._client.root_dir, dep.name, deps_file)
  1878. if not os.path.exists(deps_path):
  1879. # gclient has a fallback that if deps_file doesn't exist, it'll try
  1880. # DEPS. Do the same here.
  1881. deps_file = 'DEPS'
  1882. deps_path = os.path.join(self._client.root_dir, dep.name, deps_file)
  1883. if not os.path.exists(deps_path):
  1884. return
  1885. assert dep.url
  1886. self._deps_files.add((dep.url, deps_file, dep.hierarchy_data()))
  1887. for dep in self._deps.values():
  1888. add_deps_file(dep)
  1889. gn_args_dep = self._deps.get(self._client.dependencies[0]._gn_args_from,
  1890. self._client.dependencies[0])
  1891. self._deps_string = '\n'.join(
  1892. _GNSettingsToLines(gn_args_dep._gn_args_file, gn_args_dep._gn_args) +
  1893. _AllowedHostsToLines(self._allowed_hosts) +
  1894. _DepsToLines(self._deps) +
  1895. _HooksToLines('hooks', self._hooks) +
  1896. _HooksToLines('pre_deps_hooks', self._pre_deps_hooks) +
  1897. _VarsToLines(self._vars) +
  1898. ['# %s, %s' % (url, deps_file)
  1899. for url, deps_file, _ in sorted(self._deps_files)] +
  1900. ['']) # Ensure newline at end of file.
  1901. def _add_dep(self, dep):
  1902. """Helper to add a dependency to flattened DEPS.
  1903. Arguments:
  1904. dep (Dependency): dependency to add
  1905. """
  1906. assert dep.name not in self._deps or self._deps.get(dep.name) == dep, (
  1907. dep.name, self._deps.get(dep.name))
  1908. if dep.url:
  1909. self._deps[dep.name] = dep
  1910. def _flatten_dep(self, dep):
  1911. """Visits a dependency in order to flatten it (see CMDflatten).
  1912. Arguments:
  1913. dep (Dependency): dependency to process
  1914. """
  1915. logging.debug('_flatten_dep(%s)', dep.name)
  1916. assert dep.deps_parsed, (
  1917. "Attempted to flatten %s but it has not been processed." % dep.name)
  1918. self._allowed_hosts.update(dep.allowed_hosts)
  1919. # Only include vars explicitly listed in the DEPS files or gclient solution,
  1920. # not automatic, local overrides (i.e. not all of dep.get_vars()).
  1921. hierarchy = dep.hierarchy(include_url=False)
  1922. for key, value in dep._vars.items():
  1923. # Make sure there are no conflicting variables. It is fine however
  1924. # to use same variable name, as long as the value is consistent.
  1925. assert key not in self._vars or self._vars[key][1] == value, (
  1926. "dep:%s key:%s value:%s != %s" % (
  1927. dep.name, key, value, self._vars[key][1]))
  1928. self._vars[key] = (hierarchy, value)
  1929. # Override explicit custom variables.
  1930. for key, value in dep.custom_vars.items():
  1931. # Do custom_vars that don't correspond to DEPS vars ever make sense? DEPS
  1932. # conditionals shouldn't be using vars that aren't also defined in the
  1933. # DEPS (presubmit actually disallows this), so any new custom_var must be
  1934. # unused in the DEPS, so no need to add it to the flattened output either.
  1935. if key not in self._vars:
  1936. continue
  1937. # Don't "override" existing vars if it's actually the same value.
  1938. elif self._vars[key][1] == value:
  1939. continue
  1940. # Anything else is overriding a default value from the DEPS.
  1941. self._vars[key] = (hierarchy + ' [custom_var override]', value)
  1942. self._pre_deps_hooks.extend([(dep, hook) for hook in dep.pre_deps_hooks])
  1943. self._hooks.extend([(dep, hook) for hook in dep.deps_hooks])
  1944. for sub_dep in dep.dependencies:
  1945. self._add_dep(sub_dep)
  1946. for d in dep.dependencies:
  1947. if d.should_recurse:
  1948. self._flatten_dep(d)
  1949. @metrics.collector.collect_metrics('gclient flatten')
  1950. def CMDflatten(parser, args):
  1951. """Flattens the solutions into a single DEPS file."""
  1952. parser.add_option('--output-deps', help='Path to the output DEPS file')
  1953. parser.add_option(
  1954. '--output-deps-files',
  1955. help=('Path to the output metadata about DEPS files referenced by '
  1956. 'recursedeps.'))
  1957. parser.add_option(
  1958. '--pin-all-deps', action='store_true',
  1959. help=('Pin all deps, even if not pinned in DEPS. CAVEAT: only does so '
  1960. 'for checked out deps, NOT deps_os.'))
  1961. options, args = parser.parse_args(args)
  1962. options.nohooks = True
  1963. options.process_all_deps = True
  1964. client = GClient.LoadCurrentConfig(options)
  1965. # Only print progress if we're writing to a file. Otherwise, progress updates
  1966. # could obscure intended output.
  1967. code = client.RunOnDeps('flatten', args, progress=options.output_deps)
  1968. if code != 0:
  1969. return code
  1970. flattener = Flattener(client, pin_all_deps=options.pin_all_deps)
  1971. if options.output_deps:
  1972. with open(options.output_deps, 'w') as f:
  1973. f.write(flattener.deps_string)
  1974. else:
  1975. print(flattener.deps_string)
  1976. deps_files = [{'url': d[0], 'deps_file': d[1], 'hierarchy': d[2]}
  1977. for d in sorted(flattener.deps_files)]
  1978. if options.output_deps_files:
  1979. with open(options.output_deps_files, 'w') as f:
  1980. json.dump(deps_files, f)
  1981. return 0
  1982. def _GNSettingsToLines(gn_args_file, gn_args):
  1983. s = []
  1984. if gn_args_file:
  1985. s.extend([
  1986. 'gclient_gn_args_file = "%s"' % gn_args_file,
  1987. 'gclient_gn_args = %r' % gn_args,
  1988. ])
  1989. return s
  1990. def _AllowedHostsToLines(allowed_hosts):
  1991. """Converts |allowed_hosts| set to list of lines for output."""
  1992. if not allowed_hosts:
  1993. return []
  1994. s = ['allowed_hosts = [']
  1995. for h in sorted(allowed_hosts):
  1996. s.append(' "%s",' % h)
  1997. s.extend([']', ''])
  1998. return s
  1999. def _DepsToLines(deps):
  2000. """Converts |deps| dict to list of lines for output."""
  2001. if not deps:
  2002. return []
  2003. s = ['deps = {']
  2004. for _, dep in sorted(deps.items()):
  2005. s.extend(dep.ToLines())
  2006. s.extend(['}', ''])
  2007. return s
  2008. def _DepsOsToLines(deps_os):
  2009. """Converts |deps_os| dict to list of lines for output."""
  2010. if not deps_os:
  2011. return []
  2012. s = ['deps_os = {']
  2013. for dep_os, os_deps in sorted(deps_os.items()):
  2014. s.append(' "%s": {' % dep_os)
  2015. for name, dep in sorted(os_deps.items()):
  2016. condition_part = ([' "condition": %r,' % dep.condition]
  2017. if dep.condition else [])
  2018. s.extend([
  2019. ' # %s' % dep.hierarchy(include_url=False),
  2020. ' "%s": {' % (name,),
  2021. ' "url": "%s",' % (dep.url,),
  2022. ] + condition_part + [
  2023. ' },',
  2024. '',
  2025. ])
  2026. s.extend([' },', ''])
  2027. s.extend(['}', ''])
  2028. return s
  2029. def _HooksToLines(name, hooks):
  2030. """Converts |hooks| list to list of lines for output."""
  2031. if not hooks:
  2032. return []
  2033. s = ['%s = [' % name]
  2034. for dep, hook in hooks:
  2035. s.extend([
  2036. ' # %s' % dep.hierarchy(include_url=False),
  2037. ' {',
  2038. ])
  2039. if hook.name is not None:
  2040. s.append(' "name": "%s",' % hook.name)
  2041. if hook.pattern is not None:
  2042. s.append(' "pattern": "%s",' % hook.pattern)
  2043. if hook.condition is not None:
  2044. s.append(' "condition": %r,' % hook.condition)
  2045. # Flattened hooks need to be written relative to the root gclient dir
  2046. cwd = os.path.relpath(os.path.normpath(hook.effective_cwd))
  2047. s.extend(
  2048. [' "cwd": "%s",' % cwd] +
  2049. [' "action": ['] +
  2050. [' "%s",' % arg for arg in hook.action] +
  2051. [' ]', ' },', '']
  2052. )
  2053. s.extend([']', ''])
  2054. return s
  2055. def _HooksOsToLines(hooks_os):
  2056. """Converts |hooks| list to list of lines for output."""
  2057. if not hooks_os:
  2058. return []
  2059. s = ['hooks_os = {']
  2060. for hook_os, os_hooks in hooks_os.items():
  2061. s.append(' "%s": [' % hook_os)
  2062. for dep, hook in os_hooks:
  2063. s.extend([
  2064. ' # %s' % dep.hierarchy(include_url=False),
  2065. ' {',
  2066. ])
  2067. if hook.name is not None:
  2068. s.append(' "name": "%s",' % hook.name)
  2069. if hook.pattern is not None:
  2070. s.append(' "pattern": "%s",' % hook.pattern)
  2071. if hook.condition is not None:
  2072. s.append(' "condition": %r,' % hook.condition)
  2073. # Flattened hooks need to be written relative to the root gclient dir
  2074. cwd = os.path.relpath(os.path.normpath(hook.effective_cwd))
  2075. s.extend(
  2076. [' "cwd": "%s",' % cwd] +
  2077. [' "action": ['] +
  2078. [' "%s",' % arg for arg in hook.action] +
  2079. [' ]', ' },', '']
  2080. )
  2081. s.extend([' ],', ''])
  2082. s.extend(['}', ''])
  2083. return s
  2084. def _VarsToLines(variables):
  2085. """Converts |variables| dict to list of lines for output."""
  2086. if not variables:
  2087. return []
  2088. s = ['vars = {']
  2089. for key, tup in sorted(variables.items()):
  2090. hierarchy, value = tup
  2091. s.extend([
  2092. ' # %s' % hierarchy,
  2093. ' "%s": %r,' % (key, value),
  2094. '',
  2095. ])
  2096. s.extend(['}', ''])
  2097. return s
  2098. @metrics.collector.collect_metrics('gclient grep')
  2099. def CMDgrep(parser, args):
  2100. """Greps through git repos managed by gclient.
  2101. Runs 'git grep [args...]' for each module.
  2102. """
  2103. # We can't use optparse because it will try to parse arguments sent
  2104. # to git grep and throw an error. :-(
  2105. if not args or re.match('(-h|--help)$', args[0]):
  2106. print(
  2107. 'Usage: gclient grep [-j <N>] git-grep-args...\n\n'
  2108. 'Example: "gclient grep -j10 -A2 RefCountedBase" runs\n"git grep '
  2109. '-A2 RefCountedBase" on each of gclient\'s git\nrepos with up to '
  2110. '10 jobs.\n\nBonus: page output by appending "|& less -FRSX" to the'
  2111. ' end of your query.',
  2112. file=sys.stderr)
  2113. return 1
  2114. jobs_arg = ['--jobs=1']
  2115. if re.match(r'(-j|--jobs=)\d+$', args[0]):
  2116. jobs_arg, args = args[:1], args[1:]
  2117. elif re.match(r'(-j|--jobs)$', args[0]):
  2118. jobs_arg, args = args[:2], args[2:]
  2119. return CMDrecurse(
  2120. parser,
  2121. jobs_arg + ['--ignore', '--prepend-dir', '--no-progress', '--scm=git',
  2122. 'git', 'grep', '--null', '--color=Always'] + args)
  2123. @metrics.collector.collect_metrics('gclient root')
  2124. def CMDroot(parser, args):
  2125. """Outputs the solution root (or current dir if there isn't one)."""
  2126. (options, args) = parser.parse_args(args)
  2127. client = GClient.LoadCurrentConfig(options)
  2128. if client:
  2129. print(os.path.abspath(client.root_dir))
  2130. else:
  2131. print(os.path.abspath('.'))
  2132. @subcommand.usage('[url]')
  2133. @metrics.collector.collect_metrics('gclient config')
  2134. def CMDconfig(parser, args):
  2135. """Creates a .gclient file in the current directory.
  2136. This specifies the configuration for further commands. After update/sync,
  2137. top-level DEPS files in each module are read to determine dependent
  2138. modules to operate on as well. If optional [url] parameter is
  2139. provided, then configuration is read from a specified Subversion server
  2140. URL.
  2141. """
  2142. # We do a little dance with the --gclientfile option. 'gclient config' is the
  2143. # only command where it's acceptable to have both '--gclientfile' and '--spec'
  2144. # arguments. So, we temporarily stash any --gclientfile parameter into
  2145. # options.output_config_file until after the (gclientfile xor spec) error
  2146. # check.
  2147. parser.remove_option('--gclientfile')
  2148. parser.add_option('--gclientfile', dest='output_config_file',
  2149. help='Specify an alternate .gclient file')
  2150. parser.add_option('--name',
  2151. help='overrides the default name for the solution')
  2152. parser.add_option('--deps-file', default='DEPS',
  2153. help='overrides the default name for the DEPS file for the '
  2154. 'main solutions and all sub-dependencies')
  2155. parser.add_option('--unmanaged', action='store_true', default=False,
  2156. help='overrides the default behavior to make it possible '
  2157. 'to have the main solution untouched by gclient '
  2158. '(gclient will check out unmanaged dependencies but '
  2159. 'will never sync them)')
  2160. parser.add_option('--cache-dir', default=UNSET_CACHE_DIR,
  2161. help='Cache all git repos into this dir and do shared '
  2162. 'clones from the cache, instead of cloning directly '
  2163. 'from the remote. Pass "None" to disable cache, even '
  2164. 'if globally enabled due to $GIT_CACHE_PATH.')
  2165. parser.add_option('--custom-var', action='append', dest='custom_vars',
  2166. default=[],
  2167. help='overrides variables; key=value syntax')
  2168. parser.set_defaults(config_filename=None)
  2169. (options, args) = parser.parse_args(args)
  2170. if options.output_config_file:
  2171. setattr(options, 'config_filename', getattr(options, 'output_config_file'))
  2172. if ((options.spec and args) or len(args) > 2 or
  2173. (not options.spec and not args)):
  2174. parser.error('Inconsistent arguments. Use either --spec or one or 2 args')
  2175. if (options.cache_dir is not UNSET_CACHE_DIR
  2176. and options.cache_dir.lower() == 'none'):
  2177. options.cache_dir = None
  2178. custom_vars = {}
  2179. for arg in options.custom_vars:
  2180. kv = arg.split('=', 1)
  2181. if len(kv) != 2:
  2182. parser.error('Invalid --custom-var argument: %r' % arg)
  2183. custom_vars[kv[0]] = gclient_eval.EvaluateCondition(kv[1], {})
  2184. client = GClient('.', options)
  2185. if options.spec:
  2186. client.SetConfig(options.spec)
  2187. else:
  2188. base_url = args[0].rstrip('/')
  2189. if not options.name:
  2190. name = base_url.split('/')[-1]
  2191. if name.endswith('.git'):
  2192. name = name[:-4]
  2193. else:
  2194. # specify an alternate relpath for the given URL.
  2195. name = options.name
  2196. if not os.path.abspath(os.path.join(os.getcwd(), name)).startswith(
  2197. os.getcwd()):
  2198. parser.error('Do not pass a relative path for --name.')
  2199. if any(x in ('..', '.', '/', '\\') for x in name.split(os.sep)):
  2200. parser.error('Do not include relative path components in --name.')
  2201. deps_file = options.deps_file
  2202. client.SetDefaultConfig(name, deps_file, base_url,
  2203. managed=not options.unmanaged,
  2204. cache_dir=options.cache_dir,
  2205. custom_vars=custom_vars)
  2206. client.SaveConfig()
  2207. return 0
  2208. @subcommand.epilog("""Example:
  2209. gclient pack > patch.txt
  2210. generate simple patch for configured client and dependences
  2211. """)
  2212. @metrics.collector.collect_metrics('gclient pack')
  2213. def CMDpack(parser, args):
  2214. """Generates a patch which can be applied at the root of the tree.
  2215. Internally, runs 'git diff' on each checked out module and
  2216. dependencies, and performs minimal postprocessing of the output. The
  2217. resulting patch is printed to stdout and can be applied to a freshly
  2218. checked out tree via 'patch -p0 < patchfile'.
  2219. """
  2220. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  2221. help='override deps for the specified (comma-separated) '
  2222. 'platform(s); \'all\' will process all deps_os '
  2223. 'references')
  2224. parser.remove_option('--jobs')
  2225. (options, args) = parser.parse_args(args)
  2226. # Force jobs to 1 so the stdout is not annotated with the thread ids
  2227. options.jobs = 1
  2228. client = GClient.LoadCurrentConfig(options)
  2229. if not client:
  2230. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2231. if options.verbose:
  2232. client.PrintLocationAndContents()
  2233. return client.RunOnDeps('pack', args)
  2234. @metrics.collector.collect_metrics('gclient status')
  2235. def CMDstatus(parser, args):
  2236. """Shows modification status for every dependencies."""
  2237. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  2238. help='override deps for the specified (comma-separated) '
  2239. 'platform(s); \'all\' will process all deps_os '
  2240. 'references')
  2241. (options, args) = parser.parse_args(args)
  2242. client = GClient.LoadCurrentConfig(options)
  2243. if not client:
  2244. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2245. if options.verbose:
  2246. client.PrintLocationAndContents()
  2247. return client.RunOnDeps('status', args)
  2248. @subcommand.epilog("""Examples:
  2249. gclient sync
  2250. update files from SCM according to current configuration,
  2251. *for modules which have changed since last update or sync*
  2252. gclient sync --force
  2253. update files from SCM according to current configuration, for
  2254. all modules (useful for recovering files deleted from local copy)
  2255. gclient sync --revision src@31000
  2256. update src directory to r31000
  2257. JSON output format:
  2258. If the --output-json option is specified, the following document structure will
  2259. be emitted to the provided file. 'null' entries may occur for subprojects which
  2260. are present in the gclient solution, but were not processed (due to custom_deps,
  2261. os_deps, etc.)
  2262. {
  2263. "solutions" : {
  2264. "<name>": { # <name> is the posix-normalized path to the solution.
  2265. "revision": [<git id hex string>|null],
  2266. "scm": ["git"|null],
  2267. }
  2268. }
  2269. }
  2270. """)
  2271. @metrics.collector.collect_metrics('gclient sync')
  2272. def CMDsync(parser, args):
  2273. """Checkout/update all modules."""
  2274. parser.add_option('-f', '--force', action='store_true',
  2275. help='force update even for unchanged modules')
  2276. parser.add_option('-n', '--nohooks', action='store_true',
  2277. help='don\'t run hooks after the update is complete')
  2278. parser.add_option('-p', '--noprehooks', action='store_true',
  2279. help='don\'t run pre-DEPS hooks', default=False)
  2280. parser.add_option('-r', '--revision', action='append',
  2281. dest='revisions', metavar='REV', default=[],
  2282. help='Enforces revision/hash for the solutions with the '
  2283. 'format src@rev. The src@ part is optional and can be '
  2284. 'skipped. You can also specify URLs instead of paths '
  2285. 'and gclient will find the solution corresponding to '
  2286. 'the given URL. If a path is also specified, the URL '
  2287. 'takes precedence. -r can be used multiple times when '
  2288. '.gclient has multiple solutions configured, and will '
  2289. 'work even if the src@ part is skipped.')
  2290. parser.add_option('--patch-ref', action='append',
  2291. dest='patch_refs', metavar='GERRIT_REF', default=[],
  2292. help='Patches the given reference with the format '
  2293. 'dep@target-ref:patch-ref. '
  2294. 'For |dep|, you can specify URLs as well as paths, '
  2295. 'with URLs taking preference. '
  2296. '|patch-ref| will be applied to |dep|, rebased on top '
  2297. 'of what |dep| was synced to, and a soft reset will '
  2298. 'be done. Use --no-rebase-patch-ref and '
  2299. '--no-reset-patch-ref to disable this behavior. '
  2300. '|target-ref| is the target branch against which a '
  2301. 'patch was created, it is used to determine which '
  2302. 'commits from the |patch-ref| actually constitute a '
  2303. 'patch.')
  2304. parser.add_option('--with_branch_heads', action='store_true',
  2305. help='Clone git "branch_heads" refspecs in addition to '
  2306. 'the default refspecs. This adds about 1/2GB to a '
  2307. 'full checkout. (git only)')
  2308. parser.add_option('--with_tags', action='store_true',
  2309. help='Clone git tags in addition to the default refspecs.')
  2310. parser.add_option('-H', '--head', action='store_true',
  2311. help='DEPRECATED: only made sense with safesync urls.')
  2312. parser.add_option('-D', '--delete_unversioned_trees', action='store_true',
  2313. help='Deletes from the working copy any dependencies that '
  2314. 'have been removed since the last sync, as long as '
  2315. 'there are no local modifications. When used with '
  2316. '--force, such dependencies are removed even if they '
  2317. 'have local modifications. When used with --reset, '
  2318. 'all untracked directories are removed from the '
  2319. 'working copy, excluding those which are explicitly '
  2320. 'ignored in the repository.')
  2321. parser.add_option('-R', '--reset', action='store_true',
  2322. help='resets any local changes before updating (git only)')
  2323. parser.add_option('-M', '--merge', action='store_true',
  2324. help='merge upstream changes instead of trying to '
  2325. 'fast-forward or rebase')
  2326. parser.add_option('-A', '--auto_rebase', action='store_true',
  2327. help='Automatically rebase repositories against local '
  2328. 'checkout during update (git only).')
  2329. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  2330. help='override deps for the specified (comma-separated) '
  2331. 'platform(s); \'all\' will process all deps_os '
  2332. 'references')
  2333. parser.add_option('--process-all-deps', action='store_true',
  2334. help='Check out all deps, even for different OS-es, '
  2335. 'or with conditions evaluating to false')
  2336. parser.add_option('--upstream', action='store_true',
  2337. help='Make repo state match upstream branch.')
  2338. parser.add_option('--output-json',
  2339. help='Output a json document to this path containing '
  2340. 'summary information about the sync.')
  2341. parser.add_option('--no-history', action='store_true',
  2342. help='GIT ONLY - Reduces the size/time of the checkout at '
  2343. 'the cost of no history. Requires Git 1.9+')
  2344. parser.add_option('--shallow', action='store_true',
  2345. help='GIT ONLY - Do a shallow clone into the cache dir. '
  2346. 'Requires Git 1.9+')
  2347. parser.add_option('--no_bootstrap', '--no-bootstrap',
  2348. action='store_true',
  2349. help='Don\'t bootstrap from Google Storage.')
  2350. parser.add_option('--ignore_locks', action='store_true',
  2351. help='GIT ONLY - Ignore cache locks.')
  2352. parser.add_option('--break_repo_locks', action='store_true',
  2353. help='GIT ONLY - Forcibly remove repo locks (e.g. '
  2354. 'index.lock). This should only be used if you know for '
  2355. 'certain that this invocation of gclient is the only '
  2356. 'thing operating on the git repos (e.g. on a bot).')
  2357. parser.add_option('--lock_timeout', type='int', default=5000,
  2358. help='GIT ONLY - Deadline (in seconds) to wait for git '
  2359. 'cache lock to become available. Default is %default.')
  2360. # TODO(agable): Remove these when the oldest CrOS release milestone is M56.
  2361. parser.add_option('-t', '--transitive', action='store_true',
  2362. help='DEPRECATED: This is a no-op.')
  2363. parser.add_option('-m', '--manually_grab_svn_rev', action='store_true',
  2364. help='DEPRECATED: This is a no-op.')
  2365. # TODO(phajdan.jr): Remove validation options once default (crbug/570091).
  2366. parser.add_option('--validate-syntax', action='store_true', default=True,
  2367. help='Validate the .gclient and DEPS syntax')
  2368. parser.add_option('--disable-syntax-validation', action='store_false',
  2369. dest='validate_syntax',
  2370. help='Disable validation of .gclient and DEPS syntax.')
  2371. parser.add_option('--no-rebase-patch-ref', action='store_false',
  2372. dest='rebase_patch_ref', default=True,
  2373. help='Bypass rebase of the patch ref after checkout.')
  2374. parser.add_option('--no-reset-patch-ref', action='store_false',
  2375. dest='reset_patch_ref', default=True,
  2376. help='Bypass calling reset after patching the ref.')
  2377. (options, args) = parser.parse_args(args)
  2378. client = GClient.LoadCurrentConfig(options)
  2379. if not client:
  2380. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2381. if options.revisions and options.head:
  2382. # TODO(maruel): Make it a parser.error if it doesn't break any builder.
  2383. print('Warning: you cannot use both --head and --revision')
  2384. if options.verbose:
  2385. client.PrintLocationAndContents()
  2386. ret = client.RunOnDeps('update', args)
  2387. if options.output_json:
  2388. slns = {}
  2389. for d in client.subtree(True):
  2390. normed = d.name.replace('\\', '/').rstrip('/') + '/'
  2391. slns[normed] = {
  2392. 'revision': d.got_revision,
  2393. 'scm': d.used_scm.name if d.used_scm else None,
  2394. 'url': str(d.url) if d.url else None,
  2395. 'was_processed': d.should_process,
  2396. }
  2397. with open(options.output_json, 'w') as f:
  2398. json.dump({'solutions': slns}, f)
  2399. return ret
  2400. CMDupdate = CMDsync
  2401. @metrics.collector.collect_metrics('gclient validate')
  2402. def CMDvalidate(parser, args):
  2403. """Validates the .gclient and DEPS syntax."""
  2404. options, args = parser.parse_args(args)
  2405. options.validate_syntax = True
  2406. client = GClient.LoadCurrentConfig(options)
  2407. rv = client.RunOnDeps('validate', args)
  2408. if rv == 0:
  2409. print('validate: SUCCESS')
  2410. else:
  2411. print('validate: FAILURE')
  2412. return rv
  2413. @metrics.collector.collect_metrics('gclient diff')
  2414. def CMDdiff(parser, args):
  2415. """Displays local diff for every dependencies."""
  2416. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  2417. help='override deps for the specified (comma-separated) '
  2418. 'platform(s); \'all\' will process all deps_os '
  2419. 'references')
  2420. (options, args) = parser.parse_args(args)
  2421. client = GClient.LoadCurrentConfig(options)
  2422. if not client:
  2423. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2424. if options.verbose:
  2425. client.PrintLocationAndContents()
  2426. return client.RunOnDeps('diff', args)
  2427. @metrics.collector.collect_metrics('gclient revert')
  2428. def CMDrevert(parser, args):
  2429. """Reverts all modifications in every dependencies.
  2430. That's the nuclear option to get back to a 'clean' state. It removes anything
  2431. that shows up in git status."""
  2432. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  2433. help='override deps for the specified (comma-separated) '
  2434. 'platform(s); \'all\' will process all deps_os '
  2435. 'references')
  2436. parser.add_option('-n', '--nohooks', action='store_true',
  2437. help='don\'t run hooks after the revert is complete')
  2438. parser.add_option('-p', '--noprehooks', action='store_true',
  2439. help='don\'t run pre-DEPS hooks', default=False)
  2440. parser.add_option('--upstream', action='store_true',
  2441. help='Make repo state match upstream branch.')
  2442. parser.add_option('--break_repo_locks', action='store_true',
  2443. help='GIT ONLY - Forcibly remove repo locks (e.g. '
  2444. 'index.lock). This should only be used if you know for '
  2445. 'certain that this invocation of gclient is the only '
  2446. 'thing operating on the git repos (e.g. on a bot).')
  2447. (options, args) = parser.parse_args(args)
  2448. # --force is implied.
  2449. options.force = True
  2450. options.reset = False
  2451. options.delete_unversioned_trees = False
  2452. options.merge = False
  2453. client = GClient.LoadCurrentConfig(options)
  2454. if not client:
  2455. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2456. return client.RunOnDeps('revert', args)
  2457. @metrics.collector.collect_metrics('gclient runhooks')
  2458. def CMDrunhooks(parser, args):
  2459. """Runs hooks for files that have been modified in the local working copy."""
  2460. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  2461. help='override deps for the specified (comma-separated) '
  2462. 'platform(s); \'all\' will process all deps_os '
  2463. 'references')
  2464. parser.add_option('-f', '--force', action='store_true', default=True,
  2465. help='Deprecated. No effect.')
  2466. (options, args) = parser.parse_args(args)
  2467. client = GClient.LoadCurrentConfig(options)
  2468. if not client:
  2469. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2470. if options.verbose:
  2471. client.PrintLocationAndContents()
  2472. options.force = True
  2473. options.nohooks = False
  2474. return client.RunOnDeps('runhooks', args)
  2475. @metrics.collector.collect_metrics('gclient revinfo')
  2476. def CMDrevinfo(parser, args):
  2477. """Outputs revision info mapping for the client and its dependencies.
  2478. This allows the capture of an overall 'revision' for the source tree that
  2479. can be used to reproduce the same tree in the future. It is only useful for
  2480. 'unpinned dependencies', i.e. DEPS/deps references without a git hash.
  2481. A git branch name isn't 'pinned' since the actual commit can change.
  2482. """
  2483. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  2484. help='override deps for the specified (comma-separated) '
  2485. 'platform(s); \'all\' will process all deps_os '
  2486. 'references')
  2487. parser.add_option('-a', '--actual', action='store_true',
  2488. help='gets the actual checked out revisions instead of the '
  2489. 'ones specified in the DEPS and .gclient files')
  2490. parser.add_option('-s', '--snapshot', action='store_true',
  2491. help='creates a snapshot .gclient file of the current '
  2492. 'version of all repositories to reproduce the tree, '
  2493. 'implies -a')
  2494. parser.add_option('--filter', action='append', dest='filter',
  2495. help='Display revision information only for the specified '
  2496. 'dependencies (filtered by URL or path).')
  2497. parser.add_option('--output-json',
  2498. help='Output a json document to this path containing '
  2499. 'information about the revisions.')
  2500. parser.add_option('--ignore-dep-type', choices=['git', 'cipd'],
  2501. help='Specify to skip processing of a certain type of dep.')
  2502. (options, args) = parser.parse_args(args)
  2503. client = GClient.LoadCurrentConfig(options)
  2504. if not client:
  2505. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2506. client.PrintRevInfo()
  2507. return 0
  2508. @metrics.collector.collect_metrics('gclient getdep')
  2509. def CMDgetdep(parser, args):
  2510. """Gets revision information and variable values from a DEPS file."""
  2511. parser.add_option('--var', action='append',
  2512. dest='vars', metavar='VAR', default=[],
  2513. help='Gets the value of a given variable.')
  2514. parser.add_option('-r', '--revision', action='append',
  2515. dest='getdep_revisions', metavar='DEP', default=[],
  2516. help='Gets the revision/version for the given dependency. '
  2517. 'If it is a git dependency, dep must be a path. If it '
  2518. 'is a CIPD dependency, dep must be of the form '
  2519. 'path:package.')
  2520. parser.add_option('--deps-file', default='DEPS',
  2521. # TODO(ehmaldonado): Try to find the DEPS file pointed by
  2522. # .gclient first.
  2523. help='The DEPS file to be edited. Defaults to the DEPS '
  2524. 'file in the current directory.')
  2525. (options, args) = parser.parse_args(args)
  2526. if not os.path.isfile(options.deps_file):
  2527. raise gclient_utils.Error(
  2528. 'DEPS file %s does not exist.' % options.deps_file)
  2529. with open(options.deps_file) as f:
  2530. contents = f.read()
  2531. client = GClient.LoadCurrentConfig(options)
  2532. if client is not None:
  2533. builtin_vars = client.get_builtin_vars()
  2534. else:
  2535. logging.warning(
  2536. 'Couldn\'t find a valid gclient config. Will attempt to parse the DEPS '
  2537. 'file without support for built-in variables.')
  2538. builtin_vars = None
  2539. local_scope = gclient_eval.Exec(contents, options.deps_file,
  2540. builtin_vars=builtin_vars)
  2541. for var in options.vars:
  2542. print(gclient_eval.GetVar(local_scope, var))
  2543. for name in options.getdep_revisions:
  2544. if ':' in name:
  2545. name, _, package = name.partition(':')
  2546. if not name or not package:
  2547. parser.error(
  2548. 'Wrong CIPD format: %s:%s should be of the form path:pkg.'
  2549. % (name, package))
  2550. print(gclient_eval.GetCIPD(local_scope, name, package))
  2551. else:
  2552. print(gclient_eval.GetRevision(local_scope, name))
  2553. @metrics.collector.collect_metrics('gclient setdep')
  2554. def CMDsetdep(parser, args):
  2555. """Modifies dependency revisions and variable values in a DEPS file"""
  2556. parser.add_option('--var', action='append',
  2557. dest='vars', metavar='VAR=VAL', default=[],
  2558. help='Sets a variable to the given value with the format '
  2559. 'name=value.')
  2560. parser.add_option('-r', '--revision', action='append',
  2561. dest='setdep_revisions', metavar='DEP@REV', default=[],
  2562. help='Sets the revision/version for the dependency with '
  2563. 'the format dep@rev. If it is a git dependency, dep '
  2564. 'must be a path and rev must be a git hash or '
  2565. 'reference (e.g. src/dep@deadbeef). If it is a CIPD '
  2566. 'dependency, dep must be of the form path:package and '
  2567. 'rev must be the package version '
  2568. '(e.g. src/pkg:chromium/pkg@2.1-cr0).')
  2569. parser.add_option('--deps-file', default='DEPS',
  2570. # TODO(ehmaldonado): Try to find the DEPS file pointed by
  2571. # .gclient first.
  2572. help='The DEPS file to be edited. Defaults to the DEPS '
  2573. 'file in the current directory.')
  2574. (options, args) = parser.parse_args(args)
  2575. if args:
  2576. parser.error('Unused arguments: "%s"' % '" "'.join(args))
  2577. if not options.setdep_revisions and not options.vars:
  2578. parser.error(
  2579. 'You must specify at least one variable or revision to modify.')
  2580. if not os.path.isfile(options.deps_file):
  2581. raise gclient_utils.Error(
  2582. 'DEPS file %s does not exist.' % options.deps_file)
  2583. with open(options.deps_file) as f:
  2584. contents = f.read()
  2585. client = GClient.LoadCurrentConfig(options)
  2586. if client is not None:
  2587. builtin_vars = client.get_builtin_vars()
  2588. else:
  2589. logging.warning(
  2590. 'Couldn\'t find a valid gclient config. Will attempt to parse the DEPS '
  2591. 'file without support for built-in variables.')
  2592. builtin_vars = None
  2593. local_scope = gclient_eval.Exec(contents, options.deps_file,
  2594. builtin_vars=builtin_vars)
  2595. for var in options.vars:
  2596. name, _, value = var.partition('=')
  2597. if not name or not value:
  2598. parser.error(
  2599. 'Wrong var format: %s should be of the form name=value.' % var)
  2600. if name in local_scope['vars']:
  2601. gclient_eval.SetVar(local_scope, name, value)
  2602. else:
  2603. gclient_eval.AddVar(local_scope, name, value)
  2604. for revision in options.setdep_revisions:
  2605. name, _, value = revision.partition('@')
  2606. if not name or not value:
  2607. parser.error(
  2608. 'Wrong dep format: %s should be of the form dep@rev.' % revision)
  2609. if ':' in name:
  2610. name, _, package = name.partition(':')
  2611. if not name or not package:
  2612. parser.error(
  2613. 'Wrong CIPD format: %s:%s should be of the form path:pkg@version.'
  2614. % (name, package))
  2615. gclient_eval.SetCIPD(local_scope, name, package, value)
  2616. else:
  2617. gclient_eval.SetRevision(local_scope, name, value)
  2618. with open(options.deps_file, 'w') as f:
  2619. f.write(gclient_eval.RenderDEPSFile(local_scope))
  2620. @metrics.collector.collect_metrics('gclient verify')
  2621. def CMDverify(parser, args):
  2622. """Verifies the DEPS file deps are only from allowed_hosts."""
  2623. (options, args) = parser.parse_args(args)
  2624. client = GClient.LoadCurrentConfig(options)
  2625. if not client:
  2626. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  2627. client.RunOnDeps(None, [])
  2628. # Look at each first-level dependency of this gclient only.
  2629. for dep in client.dependencies:
  2630. bad_deps = dep.findDepsFromNotAllowedHosts()
  2631. if not bad_deps:
  2632. continue
  2633. print("There are deps from not allowed hosts in file %s" % dep.deps_file)
  2634. for bad_dep in bad_deps:
  2635. print("\t%s at %s" % (bad_dep.name, bad_dep.url))
  2636. print("allowed_hosts:", ', '.join(dep.allowed_hosts))
  2637. sys.stdout.flush()
  2638. raise gclient_utils.Error(
  2639. 'dependencies from disallowed hosts; check your DEPS file.')
  2640. return 0
  2641. @subcommand.epilog("""For more information on what metrics are we collecting and
  2642. why, please read metrics.README.md or visit https://bit.ly/2ufRS4p""")
  2643. @metrics.collector.collect_metrics('gclient metrics')
  2644. def CMDmetrics(parser, args):
  2645. """Reports, and optionally modifies, the status of metric collection."""
  2646. parser.add_option('--opt-in', action='store_true', dest='enable_metrics',
  2647. help='Opt-in to metrics collection.',
  2648. default=None)
  2649. parser.add_option('--opt-out', action='store_false', dest='enable_metrics',
  2650. help='Opt-out of metrics collection.')
  2651. options, args = parser.parse_args(args)
  2652. if args:
  2653. parser.error('Unused arguments: "%s"' % '" "'.join(args))
  2654. if not metrics.collector.config.is_googler:
  2655. print("You're not a Googler. Metrics collection is disabled for you.")
  2656. return 0
  2657. if options.enable_metrics is not None:
  2658. metrics.collector.config.opted_in = options.enable_metrics
  2659. if metrics.collector.config.opted_in is None:
  2660. print("You haven't opted in or out of metrics collection.")
  2661. elif metrics.collector.config.opted_in:
  2662. print("You have opted in. Thanks!")
  2663. else:
  2664. print("You have opted out. Please consider opting in.")
  2665. return 0
  2666. class OptionParser(optparse.OptionParser):
  2667. gclientfile_default = os.environ.get('GCLIENT_FILE', '.gclient')
  2668. def __init__(self, **kwargs):
  2669. optparse.OptionParser.__init__(
  2670. self, version='%prog ' + __version__, **kwargs)
  2671. # Some arm boards have issues with parallel sync.
  2672. if platform.machine().startswith('arm'):
  2673. jobs = 1
  2674. else:
  2675. jobs = max(8, gclient_utils.NumLocalCpus())
  2676. self.add_option(
  2677. '-j', '--jobs', default=jobs, type='int',
  2678. help='Specify how many SCM commands can run in parallel; defaults to '
  2679. '%default on this machine')
  2680. self.add_option(
  2681. '-v', '--verbose', action='count', default=0,
  2682. help='Produces additional output for diagnostics. Can be used up to '
  2683. 'three times for more logging info.')
  2684. self.add_option(
  2685. '--gclientfile', dest='config_filename',
  2686. help='Specify an alternate %s file' % self.gclientfile_default)
  2687. self.add_option(
  2688. '--spec',
  2689. help='create a gclient file containing the provided string. Due to '
  2690. 'Cygwin/Python brokenness, it can\'t contain any newlines.')
  2691. self.add_option(
  2692. '--no-nag-max', default=False, action='store_true',
  2693. help='Ignored for backwards compatibility.')
  2694. def parse_args(self, args=None, _values=None):
  2695. """Integrates standard options processing."""
  2696. # Create an optparse.Values object that will store only the actual passed
  2697. # options, without the defaults.
  2698. actual_options = optparse.Values()
  2699. _, args = optparse.OptionParser.parse_args(self, args, actual_options)
  2700. # Create an optparse.Values object with the default options.
  2701. options = optparse.Values(self.get_default_values().__dict__)
  2702. # Update it with the options passed by the user.
  2703. options._update_careful(actual_options.__dict__)
  2704. # Store the options passed by the user in an _actual_options attribute.
  2705. # We store only the keys, and not the values, since the values can contain
  2706. # arbitrary information, which might be PII.
  2707. metrics.collector.add('arguments', list(actual_options.__dict__))
  2708. levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
  2709. logging.basicConfig(
  2710. level=levels[min(options.verbose, len(levels) - 1)],
  2711. format='%(module)s(%(lineno)d) %(funcName)s:%(message)s')
  2712. if options.config_filename and options.spec:
  2713. self.error('Cannot specifiy both --gclientfile and --spec')
  2714. if (options.config_filename and
  2715. options.config_filename != os.path.basename(options.config_filename)):
  2716. self.error('--gclientfile target must be a filename, not a path')
  2717. if not options.config_filename:
  2718. options.config_filename = self.gclientfile_default
  2719. options.entries_filename = options.config_filename + '_entries'
  2720. if options.jobs < 1:
  2721. self.error('--jobs must be 1 or higher')
  2722. # These hacks need to die.
  2723. if not hasattr(options, 'revisions'):
  2724. # GClient.RunOnDeps expects it even if not applicable.
  2725. options.revisions = []
  2726. if not hasattr(options, 'head'):
  2727. options.head = None
  2728. if not hasattr(options, 'nohooks'):
  2729. options.nohooks = True
  2730. if not hasattr(options, 'noprehooks'):
  2731. options.noprehooks = True
  2732. if not hasattr(options, 'deps_os'):
  2733. options.deps_os = None
  2734. if not hasattr(options, 'force'):
  2735. options.force = None
  2736. return (options, args)
  2737. def disable_buffering():
  2738. # Make stdout auto-flush so buildbot doesn't kill us during lengthy
  2739. # operations. Python as a strong tendency to buffer sys.stdout.
  2740. sys.stdout = gclient_utils.MakeFileAutoFlush(sys.stdout)
  2741. # Make stdout annotated with the thread ids.
  2742. sys.stdout = gclient_utils.MakeFileAnnotated(sys.stdout)
  2743. def path_contains_tilde():
  2744. for element in os.environ['PATH'].split(os.pathsep):
  2745. if element.startswith('~') and os.path.abspath(
  2746. os.path.realpath(os.path.expanduser(element))) == DEPOT_TOOLS_DIR:
  2747. return True
  2748. return False
  2749. def can_run_gclient_and_helpers():
  2750. if sys.hexversion < 0x02060000:
  2751. print(
  2752. '\nYour python version %s is unsupported, please upgrade.\n' %
  2753. sys.version.split(' ', 1)[0],
  2754. file=sys.stderr)
  2755. return False
  2756. if not sys.executable:
  2757. print(
  2758. '\nPython cannot find the location of it\'s own executable.\n',
  2759. file=sys.stderr)
  2760. return False
  2761. if path_contains_tilde():
  2762. print(
  2763. '\nYour PATH contains a literal "~", which works in some shells ' +
  2764. 'but will break when python tries to run subprocesses. ' +
  2765. 'Replace the "~" with $HOME.\n' +
  2766. 'See https://crbug.com/952865.\n',
  2767. file=sys.stderr)
  2768. return False
  2769. return True
  2770. def main(argv):
  2771. """Doesn't parse the arguments here, just find the right subcommand to
  2772. execute."""
  2773. if not can_run_gclient_and_helpers():
  2774. return 2
  2775. fix_encoding.fix_encoding()
  2776. disable_buffering()
  2777. setup_color.init()
  2778. dispatcher = subcommand.CommandDispatcher(__name__)
  2779. try:
  2780. return dispatcher.execute(OptionParser(), argv)
  2781. except KeyboardInterrupt:
  2782. gclient_utils.GClientChildren.KillAllRemainingChildren()
  2783. raise
  2784. except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
  2785. print('Error: %s' % str(e), file=sys.stderr)
  2786. return 1
  2787. finally:
  2788. gclient_utils.PrintWarnings()
  2789. return 0
  2790. if '__main__' == __name__:
  2791. with metrics.collector.print_notice_and_exit():
  2792. sys.exit(main(sys.argv[1:]))
  2793. # vim: ts=2:sw=2:tw=80:et: