gclient.py 107 KB

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