gclient.py 112 KB

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