gclient.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331
  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 manager supporting both Subversion and 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 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. from __future__ import print_function
  78. __version__ = '0.7'
  79. import ast
  80. import copy
  81. import json
  82. import logging
  83. import optparse
  84. import os
  85. import platform
  86. import posixpath
  87. import pprint
  88. import re
  89. import sys
  90. import time
  91. import urllib
  92. import urlparse
  93. import fix_encoding
  94. import gclient_scm
  95. import gclient_utils
  96. import git_cache
  97. from third_party.repo.progress import Progress
  98. import subcommand
  99. import subprocess2
  100. from third_party import colorama
  101. CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src.git'
  102. def ast_dict_index(dnode, key):
  103. """Search an ast.Dict for the argument key, and return its index."""
  104. idx = [i for i in range(len(dnode.keys)) if (
  105. type(dnode.keys[i]) is ast.Str and dnode.keys[i].s == key)]
  106. if not idx:
  107. return -1
  108. elif len(idx) > 1:
  109. raise gclient_utils.Error('Multiple dict entries with same key in AST')
  110. return idx[-1]
  111. def ast2str(node, indent=0):
  112. """Return a pretty-printed rendition of an ast.Node."""
  113. t = type(node)
  114. if t is ast.Module:
  115. return '\n'.join([ast2str(x, indent) for x in node.body])
  116. elif t is ast.Assign:
  117. return ((' ' * indent) +
  118. ' = '.join([ast2str(x) for x in node.targets] +
  119. [ast2str(node.value, indent)]) + '\n')
  120. elif t is ast.Name:
  121. return node.id
  122. elif t is ast.List:
  123. if not node.elts:
  124. return '[]'
  125. elif len(node.elts) == 1:
  126. return '[' + ast2str(node.elts[0], indent) + ']'
  127. return ('[\n' + (' ' * (indent + 1)) +
  128. (',\n' + (' ' * (indent + 1))).join(
  129. [ast2str(x, indent + 1) for x in node.elts]) +
  130. '\n' + (' ' * indent) + ']')
  131. elif t is ast.Dict:
  132. if not node.keys:
  133. return '{}'
  134. elif len(node.keys) == 1:
  135. return '{%s: %s}' % (ast2str(node.keys[0]),
  136. ast2str(node.values[0], indent + 1))
  137. return ('{\n' + (' ' * (indent + 1)) +
  138. (',\n' + (' ' * (indent + 1))).join(
  139. ['%s: %s' % (ast2str(node.keys[i]),
  140. ast2str(node.values[i], indent + 1))
  141. for i in range(len(node.keys))]) +
  142. '\n' + (' ' * indent) + '}')
  143. elif t is ast.Str:
  144. return "'%s'" % node.s
  145. else:
  146. raise gclient_utils.Error("Unexpected AST node at line %d, column %d: %s"
  147. % (node.lineno, node.col_offset, t))
  148. class GClientKeywords(object):
  149. class FromImpl(object):
  150. """Used to implement the From() syntax."""
  151. def __init__(self, module_name, sub_target_name=None):
  152. """module_name is the dep module we want to include from. It can also be
  153. the name of a subdirectory to include from.
  154. sub_target_name is an optional parameter if the module name in the other
  155. DEPS file is different. E.g., you might want to map src/net to net."""
  156. self.module_name = module_name
  157. self.sub_target_name = sub_target_name
  158. def __str__(self):
  159. return 'From(%s, %s)' % (repr(self.module_name),
  160. repr(self.sub_target_name))
  161. class FileImpl(object):
  162. """Used to implement the File('') syntax which lets you sync a single file
  163. from a SVN repo."""
  164. def __init__(self, file_location):
  165. self.file_location = file_location
  166. def __str__(self):
  167. return 'File("%s")' % self.file_location
  168. def GetPath(self):
  169. return os.path.split(self.file_location)[0]
  170. def GetFilename(self):
  171. rev_tokens = self.file_location.split('@')
  172. return os.path.split(rev_tokens[0])[1]
  173. def GetRevision(self):
  174. rev_tokens = self.file_location.split('@')
  175. if len(rev_tokens) > 1:
  176. return rev_tokens[1]
  177. return None
  178. class VarImpl(object):
  179. def __init__(self, custom_vars, local_scope):
  180. self._custom_vars = custom_vars
  181. self._local_scope = local_scope
  182. def Lookup(self, var_name):
  183. """Implements the Var syntax."""
  184. if var_name in self._custom_vars:
  185. return self._custom_vars[var_name]
  186. elif var_name in self._local_scope.get("vars", {}):
  187. return self._local_scope["vars"][var_name]
  188. raise gclient_utils.Error("Var is not defined: %s" % var_name)
  189. class DependencySettings(GClientKeywords):
  190. """Immutable configuration settings."""
  191. def __init__(
  192. self, parent, url, safesync_url, managed, custom_deps, custom_vars,
  193. custom_hooks, deps_file, should_process):
  194. GClientKeywords.__init__(self)
  195. # These are not mutable:
  196. self._parent = parent
  197. self._safesync_url = safesync_url
  198. self._deps_file = deps_file
  199. self._url = url
  200. # 'managed' determines whether or not this dependency is synced/updated by
  201. # gclient after gclient checks it out initially. The difference between
  202. # 'managed' and 'should_process' is that the user specifies 'managed' via
  203. # the --unmanaged command-line flag or a .gclient config, where
  204. # 'should_process' is dynamically set by gclient if it goes over its
  205. # recursion limit and controls gclient's behavior so it does not misbehave.
  206. self._managed = managed
  207. self._should_process = should_process
  208. # This is a mutable value which has the list of 'target_os' OSes listed in
  209. # the current deps file.
  210. self.local_target_os = None
  211. # These are only set in .gclient and not in DEPS files.
  212. self._custom_vars = custom_vars or {}
  213. self._custom_deps = custom_deps or {}
  214. self._custom_hooks = custom_hooks or []
  215. # TODO(iannucci): Remove this when all masters are correctly substituting
  216. # the new blink url.
  217. if (self._custom_vars.get('webkit_trunk', '') ==
  218. 'svn://svn-mirror.golo.chromium.org/webkit-readonly/trunk'):
  219. new_url = 'svn://svn-mirror.golo.chromium.org/blink/trunk'
  220. print('Overwriting Var("webkit_trunk") with %s' % new_url)
  221. self._custom_vars['webkit_trunk'] = new_url
  222. # Post process the url to remove trailing slashes.
  223. if isinstance(self._url, basestring):
  224. # urls are sometime incorrectly written as proto://host/path/@rev. Replace
  225. # it to proto://host/path@rev.
  226. self._url = self._url.replace('/@', '@')
  227. elif not isinstance(self._url,
  228. (self.FromImpl, self.FileImpl, None.__class__)):
  229. raise gclient_utils.Error(
  230. ('dependency url must be either a string, None, '
  231. 'File() or From() instead of %s') % self._url.__class__.__name__)
  232. # Make any deps_file path platform-appropriate.
  233. for sep in ['/', '\\']:
  234. self._deps_file = self._deps_file.replace(sep, os.sep)
  235. @property
  236. def deps_file(self):
  237. return self._deps_file
  238. @property
  239. def managed(self):
  240. return self._managed
  241. @property
  242. def parent(self):
  243. return self._parent
  244. @property
  245. def root(self):
  246. """Returns the root node, a GClient object."""
  247. if not self.parent:
  248. # This line is to signal pylint that it could be a GClient instance.
  249. return self or GClient(None, None)
  250. return self.parent.root
  251. @property
  252. def safesync_url(self):
  253. return self._safesync_url
  254. @property
  255. def should_process(self):
  256. """True if this dependency should be processed, i.e. checked out."""
  257. return self._should_process
  258. @property
  259. def custom_vars(self):
  260. return self._custom_vars.copy()
  261. @property
  262. def custom_deps(self):
  263. return self._custom_deps.copy()
  264. @property
  265. def custom_hooks(self):
  266. return self._custom_hooks[:]
  267. @property
  268. def url(self):
  269. return self._url
  270. @property
  271. def target_os(self):
  272. if self.local_target_os is not None:
  273. return tuple(set(self.local_target_os).union(self.parent.target_os))
  274. else:
  275. return self.parent.target_os
  276. def get_custom_deps(self, name, url):
  277. """Returns a custom deps if applicable."""
  278. if self.parent:
  279. url = self.parent.get_custom_deps(name, url)
  280. # None is a valid return value to disable a dependency.
  281. return self.custom_deps.get(name, url)
  282. class Dependency(gclient_utils.WorkItem, DependencySettings):
  283. """Object that represents a dependency checkout."""
  284. def __init__(self, parent, name, url, safesync_url, managed, custom_deps,
  285. custom_vars, custom_hooks, deps_file, should_process):
  286. gclient_utils.WorkItem.__init__(self, name)
  287. DependencySettings.__init__(
  288. self, parent, url, safesync_url, managed, custom_deps, custom_vars,
  289. custom_hooks, deps_file, should_process)
  290. # This is in both .gclient and DEPS files:
  291. self._deps_hooks = []
  292. self._pre_deps_hooks = []
  293. # Calculates properties:
  294. self._parsed_url = None
  295. self._dependencies = []
  296. # A cache of the files affected by the current operation, necessary for
  297. # hooks.
  298. self._file_list = []
  299. # List of host names from which dependencies are allowed.
  300. # Default is an empty set, meaning unspecified in DEPS file, and hence all
  301. # hosts will be allowed. Non-empty set means whitelist of hosts.
  302. # allowed_hosts var is scoped to its DEPS file, and so it isn't recursive.
  303. self._allowed_hosts = frozenset()
  304. # If it is not set to True, the dependency wasn't processed for its child
  305. # dependency, i.e. its DEPS wasn't read.
  306. self._deps_parsed = False
  307. # This dependency has been processed, i.e. checked out
  308. self._processed = False
  309. # This dependency had its pre-DEPS hooks run
  310. self._pre_deps_hooks_ran = False
  311. # This dependency had its hook run
  312. self._hooks_ran = False
  313. # This is the scm used to checkout self.url. It may be used by dependencies
  314. # to get the datetime of the revision we checked out.
  315. self._used_scm = None
  316. self._used_revision = None
  317. # The actual revision we ended up getting, or None if that information is
  318. # unavailable
  319. self._got_revision = None
  320. # This is a mutable value that overrides the normal recursion limit for this
  321. # dependency. It is read from the actual DEPS file so cannot be set on
  322. # class instantiation.
  323. self.recursion_override = None
  324. # recursedeps is a mutable value that selectively overrides the default
  325. # 'no recursion' setting on a dep-by-dep basis. It will replace
  326. # recursion_override.
  327. self.recursedeps = None
  328. if not self.name and self.parent:
  329. raise gclient_utils.Error('Dependency without name')
  330. @property
  331. def requirements(self):
  332. """Calculate the list of requirements."""
  333. requirements = set()
  334. # self.parent is implicitly a requirement. This will be recursive by
  335. # definition.
  336. if self.parent and self.parent.name:
  337. requirements.add(self.parent.name)
  338. # For a tree with at least 2 levels*, the leaf node needs to depend
  339. # on the level higher up in an orderly way.
  340. # This becomes messy for >2 depth as the DEPS file format is a dictionary,
  341. # thus unsorted, while the .gclient format is a list thus sorted.
  342. #
  343. # * _recursion_limit is hard coded 2 and there is no hope to change this
  344. # value.
  345. #
  346. # Interestingly enough, the following condition only works in the case we
  347. # want: self is a 2nd level node. 3nd level node wouldn't need this since
  348. # they already have their parent as a requirement.
  349. if self.parent and self.parent.parent and not self.parent.parent.parent:
  350. requirements |= set(i.name for i in self.root.dependencies if i.name)
  351. if isinstance(self.url, self.FromImpl):
  352. requirements.add(self.url.module_name)
  353. if self.name:
  354. requirements |= set(
  355. obj.name for obj in self.root.subtree(False)
  356. if (obj is not self
  357. and obj.name and
  358. self.name.startswith(posixpath.join(obj.name, ''))))
  359. requirements = tuple(sorted(requirements))
  360. logging.info('Dependency(%s).requirements = %s' % (self.name, requirements))
  361. return requirements
  362. @property
  363. def try_recursedeps(self):
  364. """Returns False if recursion_override is ever specified."""
  365. if self.recursion_override is not None:
  366. return False
  367. return self.parent.try_recursedeps
  368. @property
  369. def recursion_limit(self):
  370. """Returns > 0 if this dependency is not too recursed to be processed."""
  371. # We continue to support the absence of recursedeps until tools and DEPS
  372. # using recursion_override are updated.
  373. if self.try_recursedeps and self.parent.recursedeps != None:
  374. if self.name in self.parent.recursedeps:
  375. return 1
  376. if self.recursion_override is not None:
  377. return self.recursion_override
  378. return max(self.parent.recursion_limit - 1, 0)
  379. def verify_validity(self):
  380. """Verifies that this Dependency is fine to add as a child of another one.
  381. Returns True if this entry should be added, False if it is a duplicate of
  382. another entry.
  383. """
  384. logging.info('Dependency(%s).verify_validity()' % self.name)
  385. if self.name in [s.name for s in self.parent.dependencies]:
  386. raise gclient_utils.Error(
  387. 'The same name "%s" appears multiple times in the deps section' %
  388. self.name)
  389. if not self.should_process:
  390. # Return early, no need to set requirements.
  391. return True
  392. # This require a full tree traversal with locks.
  393. siblings = [d for d in self.root.subtree(False) if d.name == self.name]
  394. for sibling in siblings:
  395. self_url = self.LateOverride(self.url)
  396. sibling_url = sibling.LateOverride(sibling.url)
  397. # Allow to have only one to be None or ''.
  398. if self_url != sibling_url and bool(self_url) == bool(sibling_url):
  399. raise gclient_utils.Error(
  400. ('Dependency %s specified more than once:\n'
  401. ' %s [%s]\n'
  402. 'vs\n'
  403. ' %s [%s]') % (
  404. self.name,
  405. sibling.hierarchy(),
  406. sibling_url,
  407. self.hierarchy(),
  408. self_url))
  409. # In theory we could keep it as a shadow of the other one. In
  410. # practice, simply ignore it.
  411. logging.warn('Won\'t process duplicate dependency %s' % sibling)
  412. return False
  413. return True
  414. def LateOverride(self, url):
  415. """Resolves the parsed url from url.
  416. Manages From() keyword accordingly. Do not touch self.parsed_url nor
  417. self.url because it may called with other urls due to From()."""
  418. assert self.parsed_url == None or not self.should_process, self.parsed_url
  419. parsed_url = self.get_custom_deps(self.name, url)
  420. if parsed_url != url:
  421. logging.info(
  422. 'Dependency(%s).LateOverride(%s) -> %s' %
  423. (self.name, url, parsed_url))
  424. return parsed_url
  425. if isinstance(url, self.FromImpl):
  426. # Requires tree traversal.
  427. ref = [
  428. dep for dep in self.root.subtree(True) if url.module_name == dep.name
  429. ]
  430. if not ref:
  431. raise gclient_utils.Error('Failed to find one reference to %s. %s' % (
  432. url.module_name, ref))
  433. # It may happen that len(ref) > 1 but it's no big deal.
  434. ref = ref[0]
  435. sub_target = url.sub_target_name or self.name
  436. found_deps = [d for d in ref.dependencies if d.name == sub_target]
  437. if len(found_deps) != 1:
  438. raise gclient_utils.Error(
  439. 'Couldn\'t find %s in %s, referenced by %s (parent: %s)\n%s' % (
  440. sub_target, ref.name, self.name, self.parent.name,
  441. str(self.root)))
  442. # Call LateOverride() again.
  443. found_dep = found_deps[0]
  444. parsed_url = found_dep.LateOverride(found_dep.url)
  445. logging.info(
  446. 'Dependency(%s).LateOverride(%s) -> %s (From)' %
  447. (self.name, url, parsed_url))
  448. return parsed_url
  449. if isinstance(url, basestring):
  450. parsed_url = urlparse.urlparse(url)
  451. if (not parsed_url[0] and
  452. not re.match(r'^\w+\@[\w\.-]+\:[\w\/]+', parsed_url[2])):
  453. # A relative url. Fetch the real base.
  454. path = parsed_url[2]
  455. if not path.startswith('/'):
  456. raise gclient_utils.Error(
  457. 'relative DEPS entry \'%s\' must begin with a slash' % url)
  458. # Create a scm just to query the full url.
  459. parent_url = self.parent.parsed_url
  460. if isinstance(parent_url, self.FileImpl):
  461. parent_url = parent_url.file_location
  462. scm = gclient_scm.CreateSCM(
  463. parent_url, self.root.root_dir, None, self.outbuf)
  464. parsed_url = scm.FullUrlForRelativeUrl(url)
  465. else:
  466. parsed_url = url
  467. logging.info(
  468. 'Dependency(%s).LateOverride(%s) -> %s' %
  469. (self.name, url, parsed_url))
  470. return parsed_url
  471. if isinstance(url, self.FileImpl):
  472. logging.info(
  473. 'Dependency(%s).LateOverride(%s) -> %s (File)' %
  474. (self.name, url, url))
  475. return url
  476. if url is None:
  477. logging.info(
  478. 'Dependency(%s).LateOverride(%s) -> %s' % (self.name, url, url))
  479. return url
  480. raise gclient_utils.Error('Unknown url type')
  481. @staticmethod
  482. def MergeWithOsDeps(deps, deps_os, target_os_list):
  483. """Returns a new "deps" structure that is the deps sent in updated
  484. with information from deps_os (the deps_os section of the DEPS
  485. file) that matches the list of target os."""
  486. os_overrides = {}
  487. for the_target_os in target_os_list:
  488. the_target_os_deps = deps_os.get(the_target_os, {})
  489. for os_dep_key, os_dep_value in the_target_os_deps.iteritems():
  490. overrides = os_overrides.setdefault(os_dep_key, [])
  491. overrides.append((the_target_os, os_dep_value))
  492. # If any os didn't specify a value (we have fewer value entries
  493. # than in the os list), then it wants to use the default value.
  494. for os_dep_key, os_dep_value in os_overrides.iteritems():
  495. if len(os_dep_value) != len(target_os_list):
  496. # Record the default value too so that we don't accidently
  497. # set it to None or miss a conflicting DEPS.
  498. if os_dep_key in deps:
  499. os_dep_value.append(('default', deps[os_dep_key]))
  500. target_os_deps = {}
  501. for os_dep_key, os_dep_value in os_overrides.iteritems():
  502. # os_dep_value is a list of (os, value) pairs.
  503. possible_values = set(x[1] for x in os_dep_value if x[1] is not None)
  504. if not possible_values:
  505. target_os_deps[os_dep_key] = None
  506. else:
  507. if len(possible_values) > 1:
  508. # It would be possible to abort here but it would be
  509. # unfortunate if we end up preventing any kind of checkout.
  510. logging.error('Conflicting dependencies for %s: %s. (target_os=%s)',
  511. os_dep_key, os_dep_value, target_os_list)
  512. # Sorting to get the same result every time in case of conflicts.
  513. target_os_deps[os_dep_key] = sorted(possible_values)[0]
  514. new_deps = deps.copy()
  515. new_deps.update(target_os_deps)
  516. return new_deps
  517. def ParseDepsFile(self):
  518. """Parses the DEPS file for this dependency."""
  519. assert not self.deps_parsed
  520. assert not self.dependencies
  521. deps_content = None
  522. use_strict = False
  523. # First try to locate the configured deps file. If it's missing, fallback
  524. # to DEPS.
  525. deps_files = [self.deps_file]
  526. if 'DEPS' not in deps_files:
  527. deps_files.append('DEPS')
  528. for deps_file in deps_files:
  529. filepath = os.path.join(self.root.root_dir, self.name, deps_file)
  530. if os.path.isfile(filepath):
  531. logging.info(
  532. 'ParseDepsFile(%s): %s file found at %s', self.name, deps_file,
  533. filepath)
  534. break
  535. logging.info(
  536. 'ParseDepsFile(%s): No %s file found at %s', self.name, deps_file,
  537. filepath)
  538. if os.path.isfile(filepath):
  539. deps_content = gclient_utils.FileRead(filepath)
  540. logging.debug('ParseDepsFile(%s) read:\n%s', self.name, deps_content)
  541. use_strict = 'use strict' in deps_content.splitlines()[0]
  542. local_scope = {}
  543. if deps_content:
  544. # One thing is unintuitive, vars = {} must happen before Var() use.
  545. var = self.VarImpl(self.custom_vars, local_scope)
  546. if use_strict:
  547. logging.info(
  548. 'ParseDepsFile(%s): Strict Mode Enabled', self.name)
  549. global_scope = {
  550. '__builtins__': {'None': None},
  551. 'Var': var.Lookup,
  552. 'deps_os': {},
  553. }
  554. else:
  555. global_scope = {
  556. 'File': self.FileImpl,
  557. 'From': self.FromImpl,
  558. 'Var': var.Lookup,
  559. 'deps_os': {},
  560. }
  561. # Eval the content.
  562. try:
  563. exec(deps_content, global_scope, local_scope)
  564. except SyntaxError as e:
  565. gclient_utils.SyntaxErrorToError(filepath, e)
  566. if use_strict:
  567. for key, val in local_scope.iteritems():
  568. if not isinstance(val, (dict, list, tuple, str)):
  569. raise gclient_utils.Error(
  570. 'ParseDepsFile(%s): Strict mode disallows %r -> %r' %
  571. (self.name, key, val))
  572. deps = local_scope.get('deps', {})
  573. if 'recursion' in local_scope:
  574. self.recursion_override = local_scope.get('recursion')
  575. logging.warning(
  576. 'Setting %s recursion to %d.', self.name, self.recursion_limit)
  577. self.recursedeps = local_scope.get('recursedeps', None)
  578. if 'recursedeps' in local_scope:
  579. self.recursedeps = set(self.recursedeps)
  580. logging.warning('Found recursedeps %r.', repr(self.recursedeps))
  581. # If present, save 'target_os' in the local_target_os property.
  582. if 'target_os' in local_scope:
  583. self.local_target_os = local_scope['target_os']
  584. # load os specific dependencies if defined. these dependencies may
  585. # override or extend the values defined by the 'deps' member.
  586. target_os_list = self.target_os
  587. if 'deps_os' in local_scope and target_os_list:
  588. deps = self.MergeWithOsDeps(deps, local_scope['deps_os'], target_os_list)
  589. # If a line is in custom_deps, but not in the solution, we want to append
  590. # this line to the solution.
  591. for d in self.custom_deps:
  592. if d not in deps:
  593. deps[d] = self.custom_deps[d]
  594. # If use_relative_paths is set in the DEPS file, regenerate
  595. # the dictionary using paths relative to the directory containing
  596. # the DEPS file. Also update recursedeps if use_relative_paths is
  597. # enabled.
  598. use_relative_paths = local_scope.get('use_relative_paths', False)
  599. if use_relative_paths:
  600. logging.warning('use_relative_paths enabled.')
  601. rel_deps = {}
  602. for d, url in deps.items():
  603. # normpath is required to allow DEPS to use .. in their
  604. # dependency local path.
  605. rel_deps[os.path.normpath(os.path.join(self.name, d))] = url
  606. logging.warning('Updating deps by prepending %s.', self.name)
  607. deps = rel_deps
  608. # Update recursedeps if it's set.
  609. if self.recursedeps is not None:
  610. logging.warning('Updating recursedeps by prepending %s.', self.name)
  611. rel_deps = set()
  612. for d in self.recursedeps:
  613. rel_deps.add(os.path.normpath(os.path.join(self.name, d)))
  614. self.recursedeps = rel_deps
  615. if 'allowed_hosts' in local_scope:
  616. try:
  617. self._allowed_hosts = frozenset(local_scope.get('allowed_hosts'))
  618. except TypeError: # raised if non-iterable
  619. pass
  620. if not self._allowed_hosts:
  621. logging.warning("allowed_hosts is specified but empty %s",
  622. self._allowed_hosts)
  623. raise gclient_utils.Error(
  624. 'ParseDepsFile(%s): allowed_hosts must be absent '
  625. 'or a non-empty iterable' % self.name)
  626. # Convert the deps into real Dependency.
  627. deps_to_add = []
  628. for name, url in deps.iteritems():
  629. should_process = self.recursion_limit and self.should_process
  630. deps_to_add.append(Dependency(
  631. self, name, url, None, None, None, None, None,
  632. self.deps_file, should_process))
  633. deps_to_add.sort(key=lambda x: x.name)
  634. # override named sets of hooks by the custom hooks
  635. hooks_to_run = []
  636. hook_names_to_suppress = [c.get('name', '') for c in self.custom_hooks]
  637. for hook in local_scope.get('hooks', []):
  638. if hook.get('name', '') not in hook_names_to_suppress:
  639. hooks_to_run.append(hook)
  640. # add the replacements and any additions
  641. for hook in self.custom_hooks:
  642. if 'action' in hook:
  643. hooks_to_run.append(hook)
  644. self._pre_deps_hooks = [self.GetHookAction(hook, []) for hook in
  645. local_scope.get('pre_deps_hooks', [])]
  646. self.add_dependencies_and_close(deps_to_add, hooks_to_run)
  647. logging.info('ParseDepsFile(%s) done' % self.name)
  648. def add_dependencies_and_close(self, deps_to_add, hooks):
  649. """Adds the dependencies, hooks and mark the parsing as done."""
  650. for dep in deps_to_add:
  651. if dep.verify_validity():
  652. self.add_dependency(dep)
  653. self._mark_as_parsed(hooks)
  654. def maybeGetParentRevision(self, command, options, parsed_url, parent):
  655. """Uses revision/timestamp of parent if no explicit revision was specified.
  656. If we are performing an update and --transitive is set, use
  657. - the parent's revision if 'self.url' is in the same repository
  658. - the parent's timestamp otherwise
  659. to update 'self.url'. The used revision/timestamp will be set in
  660. 'options.revision'.
  661. If we have an explicit revision do nothing.
  662. """
  663. if command == 'update' and options.transitive and not options.revision:
  664. _, revision = gclient_utils.SplitUrlRevision(parsed_url)
  665. if not revision:
  666. options.revision = getattr(parent, '_used_revision', None)
  667. if (options.revision and
  668. not gclient_utils.IsDateRevision(options.revision)):
  669. assert self.parent and self.parent.used_scm
  670. # If this dependency is in the same repository as parent it's url will
  671. # start with a slash. If so we take the parent revision instead of
  672. # it's timestamp.
  673. # (The timestamps of commits in google code are broken -- which can
  674. # result in dependencies to be checked out at the wrong revision)
  675. if self.url.startswith('/'):
  676. if options.verbose:
  677. print('Using parent\'s revision %s since we are in the same '
  678. 'repository.' % options.revision)
  679. else:
  680. parent_revision_date = self.parent.used_scm.GetRevisionDate(
  681. options.revision)
  682. options.revision = gclient_utils.MakeDateRevision(
  683. parent_revision_date)
  684. if options.verbose:
  685. print('Using parent\'s revision date %s since we are in a '
  686. 'different repository.' % options.revision)
  687. def findDepsFromNotAllowedHosts(self):
  688. """Returns a list of depenecies from not allowed hosts.
  689. If allowed_hosts is not set, allows all hosts and returns empty list.
  690. """
  691. if not self._allowed_hosts:
  692. return []
  693. bad_deps = []
  694. for dep in self._dependencies:
  695. # Don't enforce this for custom_deps.
  696. if dep.name in self._custom_deps:
  697. continue
  698. if isinstance(dep.url, basestring):
  699. parsed_url = urlparse.urlparse(dep.url)
  700. if parsed_url.netloc and parsed_url.netloc not in self._allowed_hosts:
  701. bad_deps.append(dep)
  702. return bad_deps
  703. # Arguments number differs from overridden method
  704. # pylint: disable=W0221
  705. def run(self, revision_overrides, command, args, work_queue, options):
  706. """Runs |command| then parse the DEPS file."""
  707. logging.info('Dependency(%s).run()' % self.name)
  708. assert self._file_list == []
  709. if not self.should_process:
  710. return
  711. # When running runhooks, there's no need to consult the SCM.
  712. # All known hooks are expected to run unconditionally regardless of working
  713. # copy state, so skip the SCM status check.
  714. run_scm = command not in ('runhooks', 'recurse', None)
  715. parsed_url = self.LateOverride(self.url)
  716. file_list = [] if not options.nohooks else None
  717. revision_override = revision_overrides.pop(self.name, None)
  718. if run_scm and parsed_url:
  719. if isinstance(parsed_url, self.FileImpl):
  720. # Special support for single-file checkout.
  721. if not command in (None, 'cleanup', 'diff', 'pack', 'status'):
  722. # Sadly, pylint doesn't realize that parsed_url is of FileImpl.
  723. # pylint: disable=E1103
  724. options.revision = parsed_url.GetRevision()
  725. self._used_scm = gclient_scm.SVNWrapper(
  726. parsed_url.GetPath(), self.root.root_dir, self.name,
  727. out_cb=work_queue.out_cb)
  728. self._used_scm.RunCommand('updatesingle',
  729. options, args + [parsed_url.GetFilename()], file_list)
  730. else:
  731. # Create a shallow copy to mutate revision.
  732. options = copy.copy(options)
  733. options.revision = revision_override
  734. self.maybeGetParentRevision(
  735. command, options, parsed_url, self.parent)
  736. self._used_revision = options.revision
  737. self._used_scm = gclient_scm.CreateSCM(
  738. parsed_url, self.root.root_dir, self.name, self.outbuf,
  739. out_cb=work_queue.out_cb)
  740. self._got_revision = self._used_scm.RunCommand(command, options, args,
  741. file_list)
  742. if file_list:
  743. file_list = [os.path.join(self.name, f.strip()) for f in file_list]
  744. # TODO(phajdan.jr): We should know exactly when the paths are absolute.
  745. # Convert all absolute paths to relative.
  746. for i in range(len(file_list or [])):
  747. # It depends on the command being executed (like runhooks vs sync).
  748. if not os.path.isabs(file_list[i]):
  749. continue
  750. prefix = os.path.commonprefix(
  751. [self.root.root_dir.lower(), file_list[i].lower()])
  752. file_list[i] = file_list[i][len(prefix):]
  753. # Strip any leading path separators.
  754. while file_list[i].startswith(('\\', '/')):
  755. file_list[i] = file_list[i][1:]
  756. # Always parse the DEPS file.
  757. self.ParseDepsFile()
  758. self._run_is_done(file_list or [], parsed_url)
  759. if command in ('update', 'revert') and not options.noprehooks:
  760. self.RunPreDepsHooks()
  761. if self.recursion_limit:
  762. # Parse the dependencies of this dependency.
  763. for s in self.dependencies:
  764. work_queue.enqueue(s)
  765. if command == 'recurse':
  766. if not isinstance(parsed_url, self.FileImpl):
  767. # Skip file only checkout.
  768. scm = gclient_scm.GetScmName(parsed_url)
  769. if not options.scm or scm in options.scm:
  770. cwd = os.path.normpath(os.path.join(self.root.root_dir, self.name))
  771. # Pass in the SCM type as an env variable. Make sure we don't put
  772. # unicode strings in the environment.
  773. env = os.environ.copy()
  774. if scm:
  775. env['GCLIENT_SCM'] = str(scm)
  776. if parsed_url:
  777. env['GCLIENT_URL'] = str(parsed_url)
  778. env['GCLIENT_DEP_PATH'] = str(self.name)
  779. if options.prepend_dir and scm == 'git':
  780. print_stdout = False
  781. def filter_fn(line):
  782. """Git-specific path marshaling. It is optimized for git-grep."""
  783. def mod_path(git_pathspec):
  784. match = re.match('^(\\S+?:)?([^\0]+)$', git_pathspec)
  785. modified_path = os.path.join(self.name, match.group(2))
  786. branch = match.group(1) or ''
  787. return '%s%s' % (branch, modified_path)
  788. match = re.match('^Binary file ([^\0]+) matches$', line)
  789. if match:
  790. print('Binary file %s matches\n' % mod_path(match.group(1)))
  791. return
  792. items = line.split('\0')
  793. if len(items) == 2 and items[1]:
  794. print('%s : %s' % (mod_path(items[0]), items[1]))
  795. elif len(items) >= 2:
  796. # Multiple null bytes or a single trailing null byte indicate
  797. # git is likely displaying filenames only (such as with -l)
  798. print('\n'.join(mod_path(path) for path in items if path))
  799. else:
  800. print(line)
  801. else:
  802. print_stdout = True
  803. filter_fn = None
  804. if parsed_url is None:
  805. print('Skipped omitted dependency %s' % cwd, file=sys.stderr)
  806. elif os.path.isdir(cwd):
  807. try:
  808. gclient_utils.CheckCallAndFilter(
  809. args, cwd=cwd, env=env, print_stdout=print_stdout,
  810. filter_fn=filter_fn,
  811. )
  812. except subprocess2.CalledProcessError:
  813. if not options.ignore:
  814. raise
  815. else:
  816. print('Skipped missing %s' % cwd, file=sys.stderr)
  817. @gclient_utils.lockedmethod
  818. def _run_is_done(self, file_list, parsed_url):
  819. # Both these are kept for hooks that are run as a separate tree traversal.
  820. self._file_list = file_list
  821. self._parsed_url = parsed_url
  822. self._processed = True
  823. @staticmethod
  824. def GetHookAction(hook_dict, matching_file_list):
  825. """Turns a parsed 'hook' dict into an executable command."""
  826. logging.debug(hook_dict)
  827. logging.debug(matching_file_list)
  828. command = hook_dict['action'][:]
  829. if command[0] == 'python':
  830. # If the hook specified "python" as the first item, the action is a
  831. # Python script. Run it by starting a new copy of the same
  832. # interpreter.
  833. command[0] = sys.executable
  834. if '$matching_files' in command:
  835. splice_index = command.index('$matching_files')
  836. command[splice_index:splice_index + 1] = matching_file_list
  837. return command
  838. def GetHooks(self, options):
  839. """Evaluates all hooks, and return them in a flat list.
  840. RunOnDeps() must have been called before to load the DEPS.
  841. """
  842. result = []
  843. if not self.should_process or not self.recursion_limit:
  844. # Don't run the hook when it is above recursion_limit.
  845. return result
  846. # If "--force" was specified, run all hooks regardless of what files have
  847. # changed.
  848. if self.deps_hooks:
  849. # TODO(maruel): If the user is using git or git-svn, then we don't know
  850. # what files have changed so we always run all hooks. It'd be nice to fix
  851. # that.
  852. if (options.force or
  853. isinstance(self.parsed_url, self.FileImpl) or
  854. gclient_scm.GetScmName(self.parsed_url) in ('git', None) or
  855. os.path.isdir(os.path.join(self.root.root_dir, self.name, '.git'))):
  856. for hook_dict in self.deps_hooks:
  857. result.append(self.GetHookAction(hook_dict, []))
  858. else:
  859. # Run hooks on the basis of whether the files from the gclient operation
  860. # match each hook's pattern.
  861. for hook_dict in self.deps_hooks:
  862. pattern = re.compile(hook_dict['pattern'])
  863. matching_file_list = [
  864. f for f in self.file_list_and_children if pattern.search(f)
  865. ]
  866. if matching_file_list:
  867. result.append(self.GetHookAction(hook_dict, matching_file_list))
  868. for s in self.dependencies:
  869. result.extend(s.GetHooks(options))
  870. return result
  871. def RunHooksRecursively(self, options):
  872. assert self.hooks_ran == False
  873. self._hooks_ran = True
  874. for hook in self.GetHooks(options):
  875. try:
  876. start_time = time.time()
  877. gclient_utils.CheckCallAndFilterAndHeader(
  878. hook, cwd=self.root.root_dir, always=True)
  879. except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
  880. # Use a discrete exit status code of 2 to indicate that a hook action
  881. # failed. Users of this script may wish to treat hook action failures
  882. # differently from VC failures.
  883. print('Error: %s' % str(e), file=sys.stderr)
  884. sys.exit(2)
  885. finally:
  886. elapsed_time = time.time() - start_time
  887. if elapsed_time > 10:
  888. print("Hook '%s' took %.2f secs" % (
  889. gclient_utils.CommandToStr(hook), elapsed_time))
  890. def RunPreDepsHooks(self):
  891. assert self.processed
  892. assert self.deps_parsed
  893. assert not self.pre_deps_hooks_ran
  894. assert not self.hooks_ran
  895. for s in self.dependencies:
  896. assert not s.processed
  897. self._pre_deps_hooks_ran = True
  898. for hook in self.pre_deps_hooks:
  899. try:
  900. start_time = time.time()
  901. gclient_utils.CheckCallAndFilterAndHeader(
  902. hook, cwd=self.root.root_dir, always=True)
  903. except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
  904. # Use a discrete exit status code of 2 to indicate that a hook action
  905. # failed. Users of this script may wish to treat hook action failures
  906. # differently from VC failures.
  907. print('Error: %s' % str(e), file=sys.stderr)
  908. sys.exit(2)
  909. finally:
  910. elapsed_time = time.time() - start_time
  911. if elapsed_time > 10:
  912. print("Hook '%s' took %.2f secs" % (
  913. gclient_utils.CommandToStr(hook), elapsed_time))
  914. def subtree(self, include_all):
  915. """Breadth first recursion excluding root node."""
  916. dependencies = self.dependencies
  917. for d in dependencies:
  918. if d.should_process or include_all:
  919. yield d
  920. for d in dependencies:
  921. for i in d.subtree(include_all):
  922. yield i
  923. def depth_first_tree(self):
  924. """Depth-first recursion including the root node."""
  925. yield self
  926. for i in self.dependencies:
  927. for j in i.depth_first_tree():
  928. if j.should_process:
  929. yield j
  930. @gclient_utils.lockedmethod
  931. def add_dependency(self, new_dep):
  932. self._dependencies.append(new_dep)
  933. @gclient_utils.lockedmethod
  934. def _mark_as_parsed(self, new_hooks):
  935. self._deps_hooks.extend(new_hooks)
  936. self._deps_parsed = True
  937. @property
  938. @gclient_utils.lockedmethod
  939. def dependencies(self):
  940. return tuple(self._dependencies)
  941. @property
  942. @gclient_utils.lockedmethod
  943. def deps_hooks(self):
  944. return tuple(self._deps_hooks)
  945. @property
  946. @gclient_utils.lockedmethod
  947. def pre_deps_hooks(self):
  948. return tuple(self._pre_deps_hooks)
  949. @property
  950. @gclient_utils.lockedmethod
  951. def parsed_url(self):
  952. return self._parsed_url
  953. @property
  954. @gclient_utils.lockedmethod
  955. def deps_parsed(self):
  956. """This is purely for debugging purposes. It's not used anywhere."""
  957. return self._deps_parsed
  958. @property
  959. @gclient_utils.lockedmethod
  960. def processed(self):
  961. return self._processed
  962. @property
  963. @gclient_utils.lockedmethod
  964. def pre_deps_hooks_ran(self):
  965. return self._pre_deps_hooks_ran
  966. @property
  967. @gclient_utils.lockedmethod
  968. def hooks_ran(self):
  969. return self._hooks_ran
  970. @property
  971. @gclient_utils.lockedmethod
  972. def allowed_hosts(self):
  973. return self._allowed_hosts
  974. @property
  975. @gclient_utils.lockedmethod
  976. def file_list(self):
  977. return tuple(self._file_list)
  978. @property
  979. def used_scm(self):
  980. """SCMWrapper instance for this dependency or None if not processed yet."""
  981. return self._used_scm
  982. @property
  983. @gclient_utils.lockedmethod
  984. def got_revision(self):
  985. return self._got_revision
  986. @property
  987. def file_list_and_children(self):
  988. result = list(self.file_list)
  989. for d in self.dependencies:
  990. result.extend(d.file_list_and_children)
  991. return tuple(result)
  992. def __str__(self):
  993. out = []
  994. for i in ('name', 'url', 'parsed_url', 'safesync_url', 'custom_deps',
  995. 'custom_vars', 'deps_hooks', 'file_list', 'should_process',
  996. 'processed', 'hooks_ran', 'deps_parsed', 'requirements',
  997. 'allowed_hosts'):
  998. # First try the native property if it exists.
  999. if hasattr(self, '_' + i):
  1000. value = getattr(self, '_' + i, False)
  1001. else:
  1002. value = getattr(self, i, False)
  1003. if value:
  1004. out.append('%s: %s' % (i, value))
  1005. for d in self.dependencies:
  1006. out.extend([' ' + x for x in str(d).splitlines()])
  1007. out.append('')
  1008. return '\n'.join(out)
  1009. def __repr__(self):
  1010. return '%s: %s' % (self.name, self.url)
  1011. def hierarchy(self):
  1012. """Returns a human-readable hierarchical reference to a Dependency."""
  1013. out = '%s(%s)' % (self.name, self.url)
  1014. i = self.parent
  1015. while i and i.name:
  1016. out = '%s(%s) -> %s' % (i.name, i.url, out)
  1017. i = i.parent
  1018. return out
  1019. class GClient(Dependency):
  1020. """Object that represent a gclient checkout. A tree of Dependency(), one per
  1021. solution or DEPS entry."""
  1022. DEPS_OS_CHOICES = {
  1023. "win32": "win",
  1024. "win": "win",
  1025. "cygwin": "win",
  1026. "darwin": "mac",
  1027. "mac": "mac",
  1028. "unix": "unix",
  1029. "linux": "unix",
  1030. "linux2": "unix",
  1031. "linux3": "unix",
  1032. "android": "android",
  1033. }
  1034. DEFAULT_CLIENT_FILE_TEXT = ("""\
  1035. solutions = [
  1036. { "name" : "%(solution_name)s",
  1037. "url" : "%(solution_url)s",
  1038. "deps_file" : "%(deps_file)s",
  1039. "managed" : %(managed)s,
  1040. "custom_deps" : {
  1041. },
  1042. "safesync_url": "%(safesync_url)s",
  1043. },
  1044. ]
  1045. cache_dir = %(cache_dir)r
  1046. """)
  1047. DEFAULT_SNAPSHOT_SOLUTION_TEXT = ("""\
  1048. { "name" : "%(solution_name)s",
  1049. "url" : "%(solution_url)s",
  1050. "deps_file" : "%(deps_file)s",
  1051. "managed" : %(managed)s,
  1052. "custom_deps" : {
  1053. %(solution_deps)s },
  1054. "safesync_url": "%(safesync_url)s",
  1055. },
  1056. """)
  1057. DEFAULT_SNAPSHOT_FILE_TEXT = ("""\
  1058. # Snapshot generated with gclient revinfo --snapshot
  1059. solutions = [
  1060. %(solution_list)s]
  1061. """)
  1062. def __init__(self, root_dir, options):
  1063. # Do not change previous behavior. Only solution level and immediate DEPS
  1064. # are processed.
  1065. self._recursion_limit = 2
  1066. Dependency.__init__(self, None, None, None, None, True, None, None, None,
  1067. 'unused', True)
  1068. self._options = options
  1069. if options.deps_os:
  1070. enforced_os = options.deps_os.split(',')
  1071. else:
  1072. enforced_os = [self.DEPS_OS_CHOICES.get(sys.platform, 'unix')]
  1073. if 'all' in enforced_os:
  1074. enforced_os = self.DEPS_OS_CHOICES.itervalues()
  1075. self._enforced_os = tuple(set(enforced_os))
  1076. self._root_dir = root_dir
  1077. self.config_content = None
  1078. def _CheckConfig(self):
  1079. """Verify that the config matches the state of the existing checked-out
  1080. solutions."""
  1081. for dep in self.dependencies:
  1082. if dep.managed and dep.url:
  1083. scm = gclient_scm.CreateSCM(
  1084. dep.url, self.root_dir, dep.name, self.outbuf)
  1085. actual_url = scm.GetActualRemoteURL(self._options)
  1086. if actual_url and not scm.DoesRemoteURLMatch(self._options):
  1087. raise gclient_utils.Error('''
  1088. Your .gclient file seems to be broken. The requested URL is different from what
  1089. is actually checked out in %(checkout_path)s.
  1090. The .gclient file contains:
  1091. %(expected_url)s (%(expected_scm)s)
  1092. The local checkout in %(checkout_path)s reports:
  1093. %(actual_url)s (%(actual_scm)s)
  1094. You should ensure that the URL listed in .gclient is correct and either change
  1095. it or fix the checkout. If you're managing your own git checkout in
  1096. %(checkout_path)s but the URL in .gclient is for an svn repository, you probably
  1097. want to set 'managed': False in .gclient.
  1098. ''' % {'checkout_path': os.path.join(self.root_dir, dep.name),
  1099. 'expected_url': dep.url,
  1100. 'expected_scm': gclient_scm.GetScmName(dep.url),
  1101. 'actual_url': actual_url,
  1102. 'actual_scm': gclient_scm.GetScmName(actual_url)})
  1103. def SetConfig(self, content):
  1104. assert not self.dependencies
  1105. config_dict = {}
  1106. self.config_content = content
  1107. try:
  1108. exec(content, config_dict)
  1109. except SyntaxError as e:
  1110. gclient_utils.SyntaxErrorToError('.gclient', e)
  1111. # Append any target OS that is not already being enforced to the tuple.
  1112. target_os = config_dict.get('target_os', [])
  1113. if config_dict.get('target_os_only', False):
  1114. self._enforced_os = tuple(set(target_os))
  1115. else:
  1116. self._enforced_os = tuple(set(self._enforced_os).union(target_os))
  1117. cache_dir = config_dict.get('cache_dir')
  1118. if cache_dir:
  1119. cache_dir = os.path.join(self.root_dir, cache_dir)
  1120. cache_dir = os.path.abspath(cache_dir)
  1121. # If running on a bot, force break any stale git cache locks.
  1122. if os.path.exists(cache_dir) and os.environ.get('CHROME_HEADLESS'):
  1123. subprocess2.check_call(['git', 'cache', 'unlock', '--cache-dir',
  1124. cache_dir, '--force', '--all'])
  1125. gclient_scm.GitWrapper.cache_dir = cache_dir
  1126. git_cache.Mirror.SetCachePath(cache_dir)
  1127. if not target_os and config_dict.get('target_os_only', False):
  1128. raise gclient_utils.Error('Can\'t use target_os_only if target_os is '
  1129. 'not specified')
  1130. deps_to_add = []
  1131. for s in config_dict.get('solutions', []):
  1132. try:
  1133. deps_to_add.append(Dependency(
  1134. self, s['name'], s['url'],
  1135. s.get('safesync_url', None),
  1136. s.get('managed', True),
  1137. s.get('custom_deps', {}),
  1138. s.get('custom_vars', {}),
  1139. s.get('custom_hooks', []),
  1140. s.get('deps_file', 'DEPS'),
  1141. True))
  1142. except KeyError:
  1143. raise gclient_utils.Error('Invalid .gclient file. Solution is '
  1144. 'incomplete: %s' % s)
  1145. self.add_dependencies_and_close(deps_to_add, config_dict.get('hooks', []))
  1146. logging.info('SetConfig() done')
  1147. def SaveConfig(self):
  1148. gclient_utils.FileWrite(os.path.join(self.root_dir,
  1149. self._options.config_filename),
  1150. self.config_content)
  1151. def MigrateConfigToGit(self, path, options):
  1152. svn_url_re = re.compile('^(https?://src\.chromium\.org/svn|'
  1153. 'svn://svn\.chromium\.org/chrome)/'
  1154. '(trunk|branches/[^/]+)/src')
  1155. old_git_re = re.compile('^(https?://git\.chromium\.org|'
  1156. 'ssh://([a-zA-Z_][a-zA-Z0-9_-]*@)?'
  1157. 'gerrit\.chromium\.org(:2941[89])?)/'
  1158. 'chromium/src\.git')
  1159. # Scan existing .gclient file for obsolete settings. It would be simpler
  1160. # to traverse self.dependencies, but working with the AST allows the code to
  1161. # dump an updated .gclient file that preserves the ordering of the original.
  1162. a = ast.parse(self.config_content, options.config_filename, 'exec')
  1163. modified = False
  1164. solutions = [elem for elem in a.body if 'solutions' in
  1165. [target.id for target in elem.targets]]
  1166. if not solutions:
  1167. return self
  1168. solutions = solutions[-1]
  1169. for solution in solutions.value.elts:
  1170. # Check for obsolete URL's
  1171. url_idx = ast_dict_index(solution, 'url')
  1172. if url_idx == -1:
  1173. continue
  1174. url_val = solution.values[url_idx]
  1175. if type(url_val) is not ast.Str:
  1176. continue
  1177. if (svn_url_re.match(url_val.s.strip())):
  1178. raise gclient_utils.Error(
  1179. """
  1180. The chromium code repository has migrated completely to git.
  1181. Your SVN-based checkout is now obsolete; you need to create a brand-new
  1182. git checkout by following these instructions:
  1183. http://www.chromium.org/developers/how-tos/get-the-code
  1184. """)
  1185. if (old_git_re.match(url_val.s.strip())):
  1186. url_val.s = CHROMIUM_SRC_URL
  1187. modified = True
  1188. # Ensure deps_file is set to .DEPS.git. We enforce this here to smooth
  1189. # over switching between pre-git-migration and post-git-migration
  1190. # revisions.
  1191. # - For pre-migration revisions, .DEPS.git must be explicitly set.
  1192. # - For post-migration revisions, .DEPS.git is not present, so gclient
  1193. # will correctly fall back to DEPS.
  1194. if url_val.s == CHROMIUM_SRC_URL:
  1195. deps_file_idx = ast_dict_index(solution, 'deps_file')
  1196. if deps_file_idx != -1:
  1197. continue
  1198. solution.keys.append(ast.Str('deps_file'))
  1199. solution.values.append(ast.Str('.DEPS.git'))
  1200. modified = True
  1201. if not modified:
  1202. return self
  1203. print(
  1204. """
  1205. WARNING: gclient detected an obsolete setting in your %s file. The file has
  1206. been automagically updated. The previous version is available at %s.old.
  1207. """ % (options.config_filename, options.config_filename))
  1208. # Replace existing .gclient with the updated version.
  1209. # Return a new GClient instance based on the new content.
  1210. new_content = ast2str(a)
  1211. dot_gclient_fn = os.path.join(path, options.config_filename)
  1212. try:
  1213. os.rename(dot_gclient_fn, dot_gclient_fn + '.old')
  1214. except OSError:
  1215. pass
  1216. with open(dot_gclient_fn, 'w') as fh:
  1217. fh.write(new_content)
  1218. client = GClient(path, options)
  1219. client.SetConfig(new_content)
  1220. return client
  1221. @staticmethod
  1222. def LoadCurrentConfig(options):
  1223. """Searches for and loads a .gclient file relative to the current working
  1224. dir. Returns a GClient object."""
  1225. if options.spec:
  1226. client = GClient('.', options)
  1227. client.SetConfig(options.spec)
  1228. else:
  1229. path = gclient_utils.FindGclientRoot(os.getcwd(), options.config_filename)
  1230. if not path:
  1231. return None
  1232. client = GClient(path, options)
  1233. client.SetConfig(gclient_utils.FileRead(
  1234. os.path.join(path, options.config_filename)))
  1235. client = client.MigrateConfigToGit(path, options)
  1236. if (options.revisions and
  1237. len(client.dependencies) > 1 and
  1238. any('@' not in r for r in options.revisions)):
  1239. print(
  1240. ('You must specify the full solution name like --revision %s@%s\n'
  1241. 'when you have multiple solutions setup in your .gclient file.\n'
  1242. 'Other solutions present are: %s.') % (
  1243. client.dependencies[0].name,
  1244. options.revisions[0],
  1245. ', '.join(s.name for s in client.dependencies[1:])),
  1246. file=sys.stderr)
  1247. return client
  1248. def SetDefaultConfig(self, solution_name, deps_file, solution_url,
  1249. safesync_url, managed=True, cache_dir=None):
  1250. self.SetConfig(self.DEFAULT_CLIENT_FILE_TEXT % {
  1251. 'solution_name': solution_name,
  1252. 'solution_url': solution_url,
  1253. 'deps_file': deps_file,
  1254. 'safesync_url' : safesync_url,
  1255. 'managed': managed,
  1256. 'cache_dir': cache_dir,
  1257. })
  1258. def _SaveEntries(self):
  1259. """Creates a .gclient_entries file to record the list of unique checkouts.
  1260. The .gclient_entries file lives in the same directory as .gclient.
  1261. """
  1262. # Sometimes pprint.pformat will use {', sometimes it'll use { ' ... It
  1263. # makes testing a bit too fun.
  1264. result = 'entries = {\n'
  1265. for entry in self.root.subtree(False):
  1266. # Skip over File() dependencies as we can't version them.
  1267. if not isinstance(entry.parsed_url, self.FileImpl):
  1268. result += ' %s: %s,\n' % (pprint.pformat(entry.name),
  1269. pprint.pformat(entry.parsed_url))
  1270. result += '}\n'
  1271. file_path = os.path.join(self.root_dir, self._options.entries_filename)
  1272. logging.debug(result)
  1273. gclient_utils.FileWrite(file_path, result)
  1274. def _ReadEntries(self):
  1275. """Read the .gclient_entries file for the given client.
  1276. Returns:
  1277. A sequence of solution names, which will be empty if there is the
  1278. entries file hasn't been created yet.
  1279. """
  1280. scope = {}
  1281. filename = os.path.join(self.root_dir, self._options.entries_filename)
  1282. if not os.path.exists(filename):
  1283. return {}
  1284. try:
  1285. exec(gclient_utils.FileRead(filename), scope)
  1286. except SyntaxError as e:
  1287. gclient_utils.SyntaxErrorToError(filename, e)
  1288. return scope['entries']
  1289. def _EnforceRevisions(self):
  1290. """Checks for revision overrides."""
  1291. revision_overrides = {}
  1292. if self._options.head:
  1293. return revision_overrides
  1294. # Do not check safesync_url if one or more --revision flag is specified.
  1295. if not self._options.revisions:
  1296. for s in self.dependencies:
  1297. if not s.managed:
  1298. self._options.revisions.append('%s@unmanaged' % s.name)
  1299. elif s.safesync_url:
  1300. self._ApplySafeSyncRev(dep=s)
  1301. if not self._options.revisions:
  1302. return revision_overrides
  1303. solutions_names = [s.name for s in self.dependencies]
  1304. index = 0
  1305. for revision in self._options.revisions:
  1306. if not '@' in revision:
  1307. # Support for --revision 123
  1308. revision = '%s@%s' % (solutions_names[index], revision)
  1309. name, rev = revision.split('@', 1)
  1310. revision_overrides[name] = rev
  1311. index += 1
  1312. return revision_overrides
  1313. def _ApplySafeSyncRev(self, dep):
  1314. """Finds a valid revision from the content of the safesync_url and apply it
  1315. by appending revisions to the revision list. Throws if revision appears to
  1316. be invalid for the given |dep|."""
  1317. assert len(dep.safesync_url) > 0
  1318. handle = urllib.urlopen(dep.safesync_url)
  1319. rev = handle.read().strip()
  1320. handle.close()
  1321. if not rev:
  1322. raise gclient_utils.Error(
  1323. 'It appears your safesync_url (%s) is not working properly\n'
  1324. '(as it returned an empty response). Check your config.' %
  1325. dep.safesync_url)
  1326. scm = gclient_scm.CreateSCM(
  1327. dep.url, dep.root.root_dir, dep.name, self.outbuf)
  1328. safe_rev = scm.GetUsableRev(rev, self._options)
  1329. if self._options.verbose:
  1330. print('Using safesync_url revision: %s.\n' % safe_rev)
  1331. self._options.revisions.append('%s@%s' % (dep.name, safe_rev))
  1332. def RunOnDeps(self, command, args, ignore_requirements=False, progress=True):
  1333. """Runs a command on each dependency in a client and its dependencies.
  1334. Args:
  1335. command: The command to use (e.g., 'status' or 'diff')
  1336. args: list of str - extra arguments to add to the command line.
  1337. """
  1338. if not self.dependencies:
  1339. raise gclient_utils.Error('No solution specified')
  1340. revision_overrides = {}
  1341. # It's unnecessary to check for revision overrides for 'recurse'.
  1342. # Save a few seconds by not calling _EnforceRevisions() in that case.
  1343. if command not in ('diff', 'recurse', 'runhooks', 'status', 'revert'):
  1344. self._CheckConfig()
  1345. revision_overrides = self._EnforceRevisions()
  1346. pm = None
  1347. # Disable progress for non-tty stdout.
  1348. if (sys.stdout.isatty() and not self._options.verbose and progress):
  1349. if command in ('update', 'revert'):
  1350. pm = Progress('Syncing projects', 1)
  1351. elif command == 'recurse':
  1352. pm = Progress(' '.join(args), 1)
  1353. work_queue = gclient_utils.ExecutionQueue(
  1354. self._options.jobs, pm, ignore_requirements=ignore_requirements,
  1355. verbose=self._options.verbose)
  1356. for s in self.dependencies:
  1357. work_queue.enqueue(s)
  1358. work_queue.flush(revision_overrides, command, args, options=self._options)
  1359. if revision_overrides:
  1360. print('Please fix your script, having invalid --revision flags will soon '
  1361. 'considered an error.', file=sys.stderr)
  1362. # Once all the dependencies have been processed, it's now safe to run the
  1363. # hooks.
  1364. if not self._options.nohooks:
  1365. self.RunHooksRecursively(self._options)
  1366. if command == 'update':
  1367. # Notify the user if there is an orphaned entry in their working copy.
  1368. # Only delete the directory if there are no changes in it, and
  1369. # delete_unversioned_trees is set to true.
  1370. entries = [i.name for i in self.root.subtree(False) if i.url]
  1371. full_entries = [os.path.join(self.root_dir, e.replace('/', os.path.sep))
  1372. for e in entries]
  1373. for entry, prev_url in self._ReadEntries().iteritems():
  1374. if not prev_url:
  1375. # entry must have been overridden via .gclient custom_deps
  1376. continue
  1377. # Fix path separator on Windows.
  1378. entry_fixed = entry.replace('/', os.path.sep)
  1379. e_dir = os.path.join(self.root_dir, entry_fixed)
  1380. # Use entry and not entry_fixed there.
  1381. if (entry not in entries and
  1382. (not any(path.startswith(entry + '/') for path in entries)) and
  1383. os.path.exists(e_dir)):
  1384. # The entry has been removed from DEPS.
  1385. scm = gclient_scm.CreateSCM(
  1386. prev_url, self.root_dir, entry_fixed, self.outbuf)
  1387. # Check to see if this directory is now part of a higher-up checkout.
  1388. # The directory might be part of a git OR svn checkout.
  1389. scm_root = None
  1390. scm_class = None
  1391. for scm_class in (gclient_scm.scm.GIT, gclient_scm.scm.SVN):
  1392. try:
  1393. scm_root = scm_class.GetCheckoutRoot(scm.checkout_path)
  1394. except subprocess2.CalledProcessError:
  1395. pass
  1396. if scm_root:
  1397. break
  1398. else:
  1399. logging.warning('Could not find checkout root for %s. Unable to '
  1400. 'determine whether it is part of a higher-level '
  1401. 'checkout, so not removing.' % entry)
  1402. continue
  1403. # This is to handle the case of third_party/WebKit migrating from
  1404. # being a DEPS entry to being part of the main project.
  1405. # If the subproject is a Git project, we need to remove its .git
  1406. # folder. Otherwise git operations on that folder will have different
  1407. # effects depending on the current working directory.
  1408. if scm_class == gclient_scm.scm.GIT and (
  1409. os.path.abspath(scm_root) == os.path.abspath(e_dir)):
  1410. e_par_dir = os.path.join(e_dir, os.pardir)
  1411. if scm_class.IsInsideWorkTree(e_par_dir):
  1412. par_scm_root = scm_class.GetCheckoutRoot(e_par_dir)
  1413. # rel_e_dir : relative path of entry w.r.t. its parent repo.
  1414. rel_e_dir = os.path.relpath(e_dir, par_scm_root)
  1415. if scm_class.IsDirectoryVersioned(par_scm_root, rel_e_dir):
  1416. save_dir = scm.GetGitBackupDirPath()
  1417. # Remove any eventual stale backup dir for the same project.
  1418. if os.path.exists(save_dir):
  1419. gclient_utils.rmtree(save_dir)
  1420. os.rename(os.path.join(e_dir, '.git'), save_dir)
  1421. # When switching between the two states (entry/ is a subproject
  1422. # -> entry/ is part of the outer project), it is very likely
  1423. # that some files are changed in the checkout, unless we are
  1424. # jumping *exactly* across the commit which changed just DEPS.
  1425. # In such case we want to cleanup any eventual stale files
  1426. # (coming from the old subproject) in order to end up with a
  1427. # clean checkout.
  1428. scm_class.CleanupDir(par_scm_root, rel_e_dir)
  1429. assert not os.path.exists(os.path.join(e_dir, '.git'))
  1430. print(('\nWARNING: \'%s\' has been moved from DEPS to a higher '
  1431. 'level checkout. The git folder containing all the local'
  1432. ' branches has been saved to %s.\n'
  1433. 'If you don\'t care about its state you can safely '
  1434. 'remove that folder to free up space.') %
  1435. (entry, save_dir))
  1436. continue
  1437. if scm_root in full_entries:
  1438. logging.info('%s is part of a higher level checkout, not removing',
  1439. scm.GetCheckoutRoot())
  1440. continue
  1441. file_list = []
  1442. scm.status(self._options, [], file_list)
  1443. modified_files = file_list != []
  1444. if (not self._options.delete_unversioned_trees or
  1445. (modified_files and not self._options.force)):
  1446. # There are modified files in this entry. Keep warning until
  1447. # removed.
  1448. print(('\nWARNING: \'%s\' is no longer part of this client. '
  1449. 'It is recommended that you manually remove it.\n') %
  1450. entry_fixed)
  1451. else:
  1452. # Delete the entry
  1453. print('\n________ deleting \'%s\' in \'%s\'' % (
  1454. entry_fixed, self.root_dir))
  1455. gclient_utils.rmtree(e_dir)
  1456. # record the current list of entries for next time
  1457. self._SaveEntries()
  1458. return 0
  1459. def PrintRevInfo(self):
  1460. if not self.dependencies:
  1461. raise gclient_utils.Error('No solution specified')
  1462. # Load all the settings.
  1463. work_queue = gclient_utils.ExecutionQueue(
  1464. self._options.jobs, None, False, verbose=self._options.verbose)
  1465. for s in self.dependencies:
  1466. work_queue.enqueue(s)
  1467. work_queue.flush({}, None, [], options=self._options)
  1468. def GetURLAndRev(dep):
  1469. """Returns the revision-qualified SCM url for a Dependency."""
  1470. if dep.parsed_url is None:
  1471. return None
  1472. if isinstance(dep.parsed_url, self.FileImpl):
  1473. original_url = dep.parsed_url.file_location
  1474. else:
  1475. original_url = dep.parsed_url
  1476. url, _ = gclient_utils.SplitUrlRevision(original_url)
  1477. scm = gclient_scm.CreateSCM(
  1478. original_url, self.root_dir, dep.name, self.outbuf)
  1479. if not os.path.isdir(scm.checkout_path):
  1480. return None
  1481. return '%s@%s' % (url, scm.revinfo(self._options, [], None))
  1482. if self._options.snapshot:
  1483. new_gclient = ''
  1484. # First level at .gclient
  1485. for d in self.dependencies:
  1486. entries = {}
  1487. def GrabDeps(dep):
  1488. """Recursively grab dependencies."""
  1489. for d in dep.dependencies:
  1490. entries[d.name] = GetURLAndRev(d)
  1491. GrabDeps(d)
  1492. GrabDeps(d)
  1493. custom_deps = []
  1494. for k in sorted(entries.keys()):
  1495. if entries[k]:
  1496. # Quotes aren't escaped...
  1497. custom_deps.append(' \"%s\": \'%s\',\n' % (k, entries[k]))
  1498. else:
  1499. custom_deps.append(' \"%s\": None,\n' % k)
  1500. new_gclient += self.DEFAULT_SNAPSHOT_SOLUTION_TEXT % {
  1501. 'solution_name': d.name,
  1502. 'solution_url': d.url,
  1503. 'deps_file': d.deps_file,
  1504. 'safesync_url' : d.safesync_url or '',
  1505. 'managed': d.managed,
  1506. 'solution_deps': ''.join(custom_deps),
  1507. }
  1508. # Print the snapshot configuration file
  1509. print(self.DEFAULT_SNAPSHOT_FILE_TEXT % {'solution_list': new_gclient})
  1510. else:
  1511. entries = {}
  1512. for d in self.root.subtree(False):
  1513. if self._options.actual:
  1514. entries[d.name] = GetURLAndRev(d)
  1515. else:
  1516. entries[d.name] = d.parsed_url
  1517. keys = sorted(entries.keys())
  1518. for x in keys:
  1519. print('%s: %s' % (x, entries[x]))
  1520. logging.info(str(self))
  1521. def ParseDepsFile(self):
  1522. """No DEPS to parse for a .gclient file."""
  1523. raise gclient_utils.Error('Internal error')
  1524. @property
  1525. def root_dir(self):
  1526. """Root directory of gclient checkout."""
  1527. return self._root_dir
  1528. @property
  1529. def enforced_os(self):
  1530. """What deps_os entries that are to be parsed."""
  1531. return self._enforced_os
  1532. @property
  1533. def recursion_limit(self):
  1534. """How recursive can each dependencies in DEPS file can load DEPS file."""
  1535. return self._recursion_limit
  1536. @property
  1537. def try_recursedeps(self):
  1538. """Whether to attempt using recursedeps-style recursion processing."""
  1539. return True
  1540. @property
  1541. def target_os(self):
  1542. return self._enforced_os
  1543. #### gclient commands.
  1544. def CMDcleanup(parser, args):
  1545. """Cleans up all working copies.
  1546. Mostly svn-specific. Simply runs 'svn cleanup' for each module.
  1547. """
  1548. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1549. help='override deps for the specified (comma-separated) '
  1550. 'platform(s); \'all\' will process all deps_os '
  1551. 'references')
  1552. (options, args) = parser.parse_args(args)
  1553. client = GClient.LoadCurrentConfig(options)
  1554. if not client:
  1555. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1556. if options.verbose:
  1557. # Print out the .gclient file. This is longer than if we just printed the
  1558. # client dict, but more legible, and it might contain helpful comments.
  1559. print(client.config_content)
  1560. return client.RunOnDeps('cleanup', args)
  1561. @subcommand.usage('[command] [args ...]')
  1562. def CMDrecurse(parser, args):
  1563. """Operates [command args ...] on all the dependencies.
  1564. Runs a shell command on all entries.
  1565. Sets GCLIENT_DEP_PATH enviroment variable as the dep's relative location to
  1566. root directory of the checkout.
  1567. """
  1568. # Stop parsing at the first non-arg so that these go through to the command
  1569. parser.disable_interspersed_args()
  1570. parser.add_option('-s', '--scm', action='append', default=[],
  1571. help='Choose scm types to operate upon.')
  1572. parser.add_option('-i', '--ignore', action='store_true',
  1573. help='Ignore non-zero return codes from subcommands.')
  1574. parser.add_option('--prepend-dir', action='store_true',
  1575. help='Prepend relative dir for use with git <cmd> --null.')
  1576. parser.add_option('--no-progress', action='store_true',
  1577. help='Disable progress bar that shows sub-command updates')
  1578. options, args = parser.parse_args(args)
  1579. if not args:
  1580. print('Need to supply a command!', file=sys.stderr)
  1581. return 1
  1582. root_and_entries = gclient_utils.GetGClientRootAndEntries()
  1583. if not root_and_entries:
  1584. print(
  1585. 'You need to run gclient sync at least once to use \'recurse\'.\n'
  1586. 'This is because .gclient_entries needs to exist and be up to date.',
  1587. file=sys.stderr)
  1588. return 1
  1589. # Normalize options.scm to a set()
  1590. scm_set = set()
  1591. for scm in options.scm:
  1592. scm_set.update(scm.split(','))
  1593. options.scm = scm_set
  1594. options.nohooks = True
  1595. client = GClient.LoadCurrentConfig(options)
  1596. return client.RunOnDeps('recurse', args, ignore_requirements=True,
  1597. progress=not options.no_progress)
  1598. @subcommand.usage('[args ...]')
  1599. def CMDfetch(parser, args):
  1600. """Fetches upstream commits for all modules.
  1601. Completely git-specific. Simply runs 'git fetch [args ...]' for each module.
  1602. """
  1603. (options, args) = parser.parse_args(args)
  1604. return CMDrecurse(OptionParser(), [
  1605. '--jobs=%d' % options.jobs, '--scm=git', 'git', 'fetch'] + args)
  1606. def CMDgrep(parser, args):
  1607. """Greps through git repos managed by gclient.
  1608. Runs 'git grep [args...]' for each module.
  1609. """
  1610. # We can't use optparse because it will try to parse arguments sent
  1611. # to git grep and throw an error. :-(
  1612. if not args or re.match('(-h|--help)$', args[0]):
  1613. print(
  1614. 'Usage: gclient grep [-j <N>] git-grep-args...\n\n'
  1615. 'Example: "gclient grep -j10 -A2 RefCountedBase" runs\n"git grep '
  1616. '-A2 RefCountedBase" on each of gclient\'s git\nrepos with up to '
  1617. '10 jobs.\n\nBonus: page output by appending "|& less -FRSX" to the'
  1618. ' end of your query.',
  1619. file=sys.stderr)
  1620. return 1
  1621. jobs_arg = ['--jobs=1']
  1622. if re.match(r'(-j|--jobs=)\d+$', args[0]):
  1623. jobs_arg, args = args[:1], args[1:]
  1624. elif re.match(r'(-j|--jobs)$', args[0]):
  1625. jobs_arg, args = args[:2], args[2:]
  1626. return CMDrecurse(
  1627. parser,
  1628. jobs_arg + ['--ignore', '--prepend-dir', '--no-progress', '--scm=git',
  1629. 'git', 'grep', '--null', '--color=Always'] + args)
  1630. def CMDroot(parser, args):
  1631. """Outputs the solution root (or current dir if there isn't one)."""
  1632. (options, args) = parser.parse_args(args)
  1633. client = GClient.LoadCurrentConfig(options)
  1634. if client:
  1635. print(os.path.abspath(client.root_dir))
  1636. else:
  1637. print(os.path.abspath('.'))
  1638. @subcommand.usage('[url] [safesync url]')
  1639. def CMDconfig(parser, args):
  1640. """Creates a .gclient file in the current directory.
  1641. This specifies the configuration for further commands. After update/sync,
  1642. top-level DEPS files in each module are read to determine dependent
  1643. modules to operate on as well. If optional [url] parameter is
  1644. provided, then configuration is read from a specified Subversion server
  1645. URL.
  1646. """
  1647. # We do a little dance with the --gclientfile option. 'gclient config' is the
  1648. # only command where it's acceptable to have both '--gclientfile' and '--spec'
  1649. # arguments. So, we temporarily stash any --gclientfile parameter into
  1650. # options.output_config_file until after the (gclientfile xor spec) error
  1651. # check.
  1652. parser.remove_option('--gclientfile')
  1653. parser.add_option('--gclientfile', dest='output_config_file',
  1654. help='Specify an alternate .gclient file')
  1655. parser.add_option('--name',
  1656. help='overrides the default name for the solution')
  1657. parser.add_option('--deps-file', default='DEPS',
  1658. help='overrides the default name for the DEPS file for the'
  1659. 'main solutions and all sub-dependencies')
  1660. parser.add_option('--unmanaged', action='store_true', default=False,
  1661. help='overrides the default behavior to make it possible '
  1662. 'to have the main solution untouched by gclient '
  1663. '(gclient will check out unmanaged dependencies but '
  1664. 'will never sync them)')
  1665. parser.add_option('--cache-dir',
  1666. help='(git only) Cache all git repos into this dir and do '
  1667. 'shared clones from the cache, instead of cloning '
  1668. 'directly from the remote. (experimental)')
  1669. parser.set_defaults(config_filename=None)
  1670. (options, args) = parser.parse_args(args)
  1671. if options.output_config_file:
  1672. setattr(options, 'config_filename', getattr(options, 'output_config_file'))
  1673. if ((options.spec and args) or len(args) > 2 or
  1674. (not options.spec and not args)):
  1675. parser.error('Inconsistent arguments. Use either --spec or one or 2 args')
  1676. client = GClient('.', options)
  1677. if options.spec:
  1678. client.SetConfig(options.spec)
  1679. else:
  1680. base_url = args[0].rstrip('/')
  1681. if not options.name:
  1682. name = base_url.split('/')[-1]
  1683. if name.endswith('.git'):
  1684. name = name[:-4]
  1685. else:
  1686. # specify an alternate relpath for the given URL.
  1687. name = options.name
  1688. if not os.path.abspath(os.path.join(os.getcwd(), name)).startswith(
  1689. os.getcwd()):
  1690. parser.error('Do not pass a relative path for --name.')
  1691. if any(x in ('..', '.', '/', '\\') for x in name.split(os.sep)):
  1692. parser.error('Do not include relative path components in --name.')
  1693. deps_file = options.deps_file
  1694. safesync_url = ''
  1695. if len(args) > 1:
  1696. safesync_url = args[1]
  1697. client.SetDefaultConfig(name, deps_file, base_url, safesync_url,
  1698. managed=not options.unmanaged,
  1699. cache_dir=options.cache_dir)
  1700. client.SaveConfig()
  1701. return 0
  1702. @subcommand.epilog("""Example:
  1703. gclient pack > patch.txt
  1704. generate simple patch for configured client and dependences
  1705. """)
  1706. def CMDpack(parser, args):
  1707. """Generates a patch which can be applied at the root of the tree.
  1708. Internally, runs 'svn diff'/'git diff' on each checked out module and
  1709. dependencies, and performs minimal postprocessing of the output. The
  1710. resulting patch is printed to stdout and can be applied to a freshly
  1711. checked out tree via 'patch -p0 < patchfile'.
  1712. """
  1713. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1714. help='override deps for the specified (comma-separated) '
  1715. 'platform(s); \'all\' will process all deps_os '
  1716. 'references')
  1717. parser.remove_option('--jobs')
  1718. (options, args) = parser.parse_args(args)
  1719. # Force jobs to 1 so the stdout is not annotated with the thread ids
  1720. options.jobs = 1
  1721. client = GClient.LoadCurrentConfig(options)
  1722. if not client:
  1723. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1724. if options.verbose:
  1725. # Print out the .gclient file. This is longer than if we just printed the
  1726. # client dict, but more legible, and it might contain helpful comments.
  1727. print(client.config_content)
  1728. return client.RunOnDeps('pack', args)
  1729. def CMDstatus(parser, args):
  1730. """Shows modification status for every dependencies."""
  1731. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1732. help='override deps for the specified (comma-separated) '
  1733. 'platform(s); \'all\' will process all deps_os '
  1734. 'references')
  1735. (options, args) = parser.parse_args(args)
  1736. client = GClient.LoadCurrentConfig(options)
  1737. if not client:
  1738. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1739. if options.verbose:
  1740. # Print out the .gclient file. This is longer than if we just printed the
  1741. # client dict, but more legible, and it might contain helpful comments.
  1742. print(client.config_content)
  1743. return client.RunOnDeps('status', args)
  1744. @subcommand.epilog("""Examples:
  1745. gclient sync
  1746. update files from SCM according to current configuration,
  1747. *for modules which have changed since last update or sync*
  1748. gclient sync --force
  1749. update files from SCM according to current configuration, for
  1750. all modules (useful for recovering files deleted from local copy)
  1751. gclient sync --revision src@31000
  1752. update src directory to r31000
  1753. JSON output format:
  1754. If the --output-json option is specified, the following document structure will
  1755. be emitted to the provided file. 'null' entries may occur for subprojects which
  1756. are present in the gclient solution, but were not processed (due to custom_deps,
  1757. os_deps, etc.)
  1758. {
  1759. "solutions" : {
  1760. "<name>": { # <name> is the posix-normalized path to the solution.
  1761. "revision": [<svn rev int>|<git id hex string>|null],
  1762. "scm": ["svn"|"git"|null],
  1763. }
  1764. }
  1765. }
  1766. """)
  1767. def CMDsync(parser, args):
  1768. """Checkout/update all modules."""
  1769. parser.add_option('-f', '--force', action='store_true',
  1770. help='force update even for unchanged modules')
  1771. parser.add_option('-n', '--nohooks', action='store_true',
  1772. help='don\'t run hooks after the update is complete')
  1773. parser.add_option('-p', '--noprehooks', action='store_true',
  1774. help='don\'t run pre-DEPS hooks', default=False)
  1775. parser.add_option('-r', '--revision', action='append',
  1776. dest='revisions', metavar='REV', default=[],
  1777. help='Enforces revision/hash for the solutions with the '
  1778. 'format src@rev. The src@ part is optional and can be '
  1779. 'skipped. -r can be used multiple times when .gclient '
  1780. 'has multiple solutions configured and will work even '
  1781. 'if the src@ part is skipped. Note that specifying '
  1782. '--revision means your safesync_url gets ignored.')
  1783. parser.add_option('--with_branch_heads', action='store_true',
  1784. help='Clone git "branch_heads" refspecs in addition to '
  1785. 'the default refspecs. This adds about 1/2GB to a '
  1786. 'full checkout. (git only)')
  1787. parser.add_option('--with_tags', action='store_true',
  1788. help='Clone git tags in addition to the default refspecs.')
  1789. parser.add_option('-t', '--transitive', action='store_true',
  1790. help='When a revision is specified (in the DEPS file or '
  1791. 'with the command-line flag), transitively update '
  1792. 'the dependencies to the date of the given revision. '
  1793. 'Only supported for SVN repositories.')
  1794. parser.add_option('-H', '--head', action='store_true',
  1795. help='skips any safesync_urls specified in '
  1796. 'configured solutions and sync to head instead')
  1797. parser.add_option('-D', '--delete_unversioned_trees', action='store_true',
  1798. help='Deletes from the working copy any dependencies that '
  1799. 'have been removed since the last sync, as long as '
  1800. 'there are no local modifications. When used with '
  1801. '--force, such dependencies are removed even if they '
  1802. 'have local modifications. When used with --reset, '
  1803. 'all untracked directories are removed from the '
  1804. 'working copy, excluding those which are explicitly '
  1805. 'ignored in the repository.')
  1806. parser.add_option('-R', '--reset', action='store_true',
  1807. help='resets any local changes before updating (git only)')
  1808. parser.add_option('-M', '--merge', action='store_true',
  1809. help='merge upstream changes instead of trying to '
  1810. 'fast-forward or rebase')
  1811. parser.add_option('-A', '--auto_rebase', action='store_true',
  1812. help='Automatically rebase repositories against local '
  1813. 'checkout during update (git only).')
  1814. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1815. help='override deps for the specified (comma-separated) '
  1816. 'platform(s); \'all\' will process all deps_os '
  1817. 'references')
  1818. parser.add_option('-m', '--manually_grab_svn_rev', action='store_true',
  1819. help='Skip svn up whenever possible by requesting '
  1820. 'actual HEAD revision from the repository')
  1821. parser.add_option('--upstream', action='store_true',
  1822. help='Make repo state match upstream branch.')
  1823. parser.add_option('--output-json',
  1824. help='Output a json document to this path containing '
  1825. 'summary information about the sync.')
  1826. parser.add_option('--no-history', action='store_true',
  1827. help='GIT ONLY - Reduces the size/time of the checkout at '
  1828. 'the cost of no history. Requires Git 1.9+')
  1829. parser.add_option('--shallow', action='store_true',
  1830. help='GIT ONLY - Do a shallow clone into the cache dir. '
  1831. 'Requires Git 1.9+')
  1832. parser.add_option('--no_bootstrap', '--no-bootstrap',
  1833. action='store_true',
  1834. help='Don\'t bootstrap from Google Storage.')
  1835. parser.add_option('--ignore_locks', action='store_true',
  1836. help='GIT ONLY - Ignore cache locks.')
  1837. parser.add_option('--lock_timeout', type='int', default=0,
  1838. help='GIT ONLY - Deadline (in seconds) to wait for git '
  1839. 'cache lock to become available.')
  1840. (options, args) = parser.parse_args(args)
  1841. client = GClient.LoadCurrentConfig(options)
  1842. if not client:
  1843. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1844. if options.revisions and options.head:
  1845. # TODO(maruel): Make it a parser.error if it doesn't break any builder.
  1846. print('Warning: you cannot use both --head and --revision')
  1847. if options.verbose:
  1848. # Print out the .gclient file. This is longer than if we just printed the
  1849. # client dict, but more legible, and it might contain helpful comments.
  1850. print(client.config_content)
  1851. ret = client.RunOnDeps('update', args)
  1852. if options.output_json:
  1853. slns = {}
  1854. for d in client.subtree(True):
  1855. normed = d.name.replace('\\', '/').rstrip('/') + '/'
  1856. slns[normed] = {
  1857. 'revision': d.got_revision,
  1858. 'scm': d.used_scm.name if d.used_scm else None,
  1859. 'url': str(d.url) if d.url else None,
  1860. }
  1861. with open(options.output_json, 'wb') as f:
  1862. json.dump({'solutions': slns}, f)
  1863. return ret
  1864. CMDupdate = CMDsync
  1865. def CMDdiff(parser, args):
  1866. """Displays local diff for every dependencies."""
  1867. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1868. help='override deps for the specified (comma-separated) '
  1869. 'platform(s); \'all\' will process all deps_os '
  1870. 'references')
  1871. (options, args) = parser.parse_args(args)
  1872. client = GClient.LoadCurrentConfig(options)
  1873. if not client:
  1874. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1875. if options.verbose:
  1876. # Print out the .gclient file. This is longer than if we just printed the
  1877. # client dict, but more legible, and it might contain helpful comments.
  1878. print(client.config_content)
  1879. return client.RunOnDeps('diff', args)
  1880. def CMDrevert(parser, args):
  1881. """Reverts all modifications in every dependencies.
  1882. That's the nuclear option to get back to a 'clean' state. It removes anything
  1883. that shows up in svn status."""
  1884. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1885. help='override deps for the specified (comma-separated) '
  1886. 'platform(s); \'all\' will process all deps_os '
  1887. 'references')
  1888. parser.add_option('-n', '--nohooks', action='store_true',
  1889. help='don\'t run hooks after the revert is complete')
  1890. parser.add_option('-p', '--noprehooks', action='store_true',
  1891. help='don\'t run pre-DEPS hooks', default=False)
  1892. parser.add_option('--upstream', action='store_true',
  1893. help='Make repo state match upstream branch.')
  1894. (options, args) = parser.parse_args(args)
  1895. # --force is implied.
  1896. options.force = True
  1897. options.reset = False
  1898. options.delete_unversioned_trees = False
  1899. client = GClient.LoadCurrentConfig(options)
  1900. if not client:
  1901. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1902. return client.RunOnDeps('revert', args)
  1903. def CMDrunhooks(parser, args):
  1904. """Runs hooks for files that have been modified in the local working copy."""
  1905. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1906. help='override deps for the specified (comma-separated) '
  1907. 'platform(s); \'all\' will process all deps_os '
  1908. 'references')
  1909. parser.add_option('-f', '--force', action='store_true', default=True,
  1910. help='Deprecated. No effect.')
  1911. (options, args) = parser.parse_args(args)
  1912. client = GClient.LoadCurrentConfig(options)
  1913. if not client:
  1914. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1915. if options.verbose:
  1916. # Print out the .gclient file. This is longer than if we just printed the
  1917. # client dict, but more legible, and it might contain helpful comments.
  1918. print(client.config_content)
  1919. options.force = True
  1920. options.nohooks = False
  1921. return client.RunOnDeps('runhooks', args)
  1922. def CMDrevinfo(parser, args):
  1923. """Outputs revision info mapping for the client and its dependencies.
  1924. This allows the capture of an overall 'revision' for the source tree that
  1925. can be used to reproduce the same tree in the future. It is only useful for
  1926. 'unpinned dependencies', i.e. DEPS/deps references without a svn revision
  1927. number or a git hash. A git branch name isn't 'pinned' since the actual
  1928. commit can change.
  1929. """
  1930. parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
  1931. help='override deps for the specified (comma-separated) '
  1932. 'platform(s); \'all\' will process all deps_os '
  1933. 'references')
  1934. parser.add_option('-a', '--actual', action='store_true',
  1935. help='gets the actual checked out revisions instead of the '
  1936. 'ones specified in the DEPS and .gclient files')
  1937. parser.add_option('-s', '--snapshot', action='store_true',
  1938. help='creates a snapshot .gclient file of the current '
  1939. 'version of all repositories to reproduce the tree, '
  1940. 'implies -a')
  1941. (options, args) = parser.parse_args(args)
  1942. client = GClient.LoadCurrentConfig(options)
  1943. if not client:
  1944. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1945. client.PrintRevInfo()
  1946. return 0
  1947. def CMDhookinfo(parser, args):
  1948. """Outputs the hooks that would be run by `gclient runhooks`."""
  1949. (options, args) = parser.parse_args(args)
  1950. options.force = True
  1951. client = GClient.LoadCurrentConfig(options)
  1952. if not client:
  1953. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1954. client.RunOnDeps(None, [])
  1955. print('; '.join(' '.join(hook) for hook in client.GetHooks(options)))
  1956. return 0
  1957. def CMDverify(parser, args):
  1958. """Verifies the DEPS file deps are only from allowed_hosts."""
  1959. (options, args) = parser.parse_args(args)
  1960. client = GClient.LoadCurrentConfig(options)
  1961. if not client:
  1962. raise gclient_utils.Error('client not configured; see \'gclient config\'')
  1963. client.RunOnDeps(None, [])
  1964. # Look at each first-level dependency of this gclient only.
  1965. for dep in client.dependencies:
  1966. bad_deps = dep.findDepsFromNotAllowedHosts()
  1967. if not bad_deps:
  1968. continue
  1969. print("There are deps from not allowed hosts in file %s" % dep.deps_file)
  1970. for bad_dep in bad_deps:
  1971. print("\t%s at %s" % (bad_dep.name, bad_dep.url))
  1972. print("allowed_hosts:", ', '.join(dep.allowed_hosts))
  1973. sys.stdout.flush()
  1974. raise gclient_utils.Error(
  1975. 'dependencies from disallowed hosts; check your DEPS file.')
  1976. return 0
  1977. class OptionParser(optparse.OptionParser):
  1978. gclientfile_default = os.environ.get('GCLIENT_FILE', '.gclient')
  1979. def __init__(self, **kwargs):
  1980. optparse.OptionParser.__init__(
  1981. self, version='%prog ' + __version__, **kwargs)
  1982. # Some arm boards have issues with parallel sync.
  1983. if platform.machine().startswith('arm'):
  1984. jobs = 1
  1985. else:
  1986. jobs = max(8, gclient_utils.NumLocalCpus())
  1987. # cmp: 2013/06/19
  1988. # Temporary workaround to lower bot-load on SVN server.
  1989. # Bypassed if a bot_update flag is detected.
  1990. if (os.environ.get('CHROME_HEADLESS') == '1' and
  1991. not os.path.exists('update.flag')):
  1992. jobs = 1
  1993. self.add_option(
  1994. '-j', '--jobs', default=jobs, type='int',
  1995. help='Specify how many SCM commands can run in parallel; defaults to '
  1996. '%default on this machine')
  1997. self.add_option(
  1998. '-v', '--verbose', action='count', default=0,
  1999. help='Produces additional output for diagnostics. Can be used up to '
  2000. 'three times for more logging info.')
  2001. self.add_option(
  2002. '--gclientfile', dest='config_filename',
  2003. help='Specify an alternate %s file' % self.gclientfile_default)
  2004. self.add_option(
  2005. '--spec',
  2006. help='create a gclient file containing the provided string. Due to '
  2007. 'Cygwin/Python brokenness, it can\'t contain any newlines.')
  2008. self.add_option(
  2009. '--no-nag-max', default=False, action='store_true',
  2010. help='Ignored for backwards compatibility.')
  2011. def parse_args(self, args=None, values=None):
  2012. """Integrates standard options processing."""
  2013. options, args = optparse.OptionParser.parse_args(self, args, values)
  2014. levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
  2015. logging.basicConfig(
  2016. level=levels[min(options.verbose, len(levels) - 1)],
  2017. format='%(module)s(%(lineno)d) %(funcName)s:%(message)s')
  2018. if options.config_filename and options.spec:
  2019. self.error('Cannot specifiy both --gclientfile and --spec')
  2020. if (options.config_filename and
  2021. options.config_filename != os.path.basename(options.config_filename)):
  2022. self.error('--gclientfile target must be a filename, not a path')
  2023. if not options.config_filename:
  2024. options.config_filename = self.gclientfile_default
  2025. options.entries_filename = options.config_filename + '_entries'
  2026. if options.jobs < 1:
  2027. self.error('--jobs must be 1 or higher')
  2028. # These hacks need to die.
  2029. if not hasattr(options, 'revisions'):
  2030. # GClient.RunOnDeps expects it even if not applicable.
  2031. options.revisions = []
  2032. if not hasattr(options, 'head'):
  2033. options.head = None
  2034. if not hasattr(options, 'nohooks'):
  2035. options.nohooks = True
  2036. if not hasattr(options, 'noprehooks'):
  2037. options.noprehooks = True
  2038. if not hasattr(options, 'deps_os'):
  2039. options.deps_os = None
  2040. if not hasattr(options, 'manually_grab_svn_rev'):
  2041. options.manually_grab_svn_rev = None
  2042. if not hasattr(options, 'force'):
  2043. options.force = None
  2044. return (options, args)
  2045. def disable_buffering():
  2046. # Make stdout auto-flush so buildbot doesn't kill us during lengthy
  2047. # operations. Python as a strong tendency to buffer sys.stdout.
  2048. sys.stdout = gclient_utils.MakeFileAutoFlush(sys.stdout)
  2049. # Make stdout annotated with the thread ids.
  2050. sys.stdout = gclient_utils.MakeFileAnnotated(sys.stdout)
  2051. def main(argv):
  2052. """Doesn't parse the arguments here, just find the right subcommand to
  2053. execute."""
  2054. if sys.hexversion < 0x02060000:
  2055. print(
  2056. '\nYour python version %s is unsupported, please upgrade.\n' %
  2057. sys.version.split(' ', 1)[0],
  2058. file=sys.stderr)
  2059. return 2
  2060. if not sys.executable:
  2061. print(
  2062. '\nPython cannot find the location of it\'s own executable.\n',
  2063. file=sys.stderr)
  2064. return 2
  2065. fix_encoding.fix_encoding()
  2066. disable_buffering()
  2067. colorama.init()
  2068. dispatcher = subcommand.CommandDispatcher(__name__)
  2069. try:
  2070. return dispatcher.execute(OptionParser(), argv)
  2071. except KeyboardInterrupt:
  2072. gclient_utils.GClientChildren.KillAllRemainingChildren()
  2073. raise
  2074. except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
  2075. print('Error: %s' % str(e), file=sys.stderr)
  2076. return 1
  2077. finally:
  2078. gclient_utils.PrintWarnings()
  2079. return 0
  2080. if '__main__' == __name__:
  2081. try:
  2082. sys.exit(main(sys.argv[1:]))
  2083. except KeyboardInterrupt:
  2084. sys.stderr.write('interrupted\n')
  2085. sys.exit(1)
  2086. # vim: ts=2:sw=2:tw=80:et: