gclient.py 131 KB

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