gclient.py 160 KB

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