gclient.py 131 KB

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