gclient.py 117 KB

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