gclient.py 112 KB

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