gclient.py 129 KB

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