project.py 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import errno
  18. import filecmp
  19. import glob
  20. import json
  21. import os
  22. import random
  23. import re
  24. import shutil
  25. import stat
  26. import subprocess
  27. import sys
  28. import tarfile
  29. import tempfile
  30. import time
  31. import traceback
  32. from color import Coloring
  33. from git_command import GitCommand, git_require
  34. from git_config import GitConfig, IsId, GetSchemeFromUrl, GetUrlCookieFile, \
  35. ID_RE
  36. from error import GitError, HookError, UploadError, DownloadError
  37. from error import ManifestInvalidRevisionError
  38. from error import NoManifestException
  39. import platform_utils
  40. from repo_trace import IsTrace, Trace
  41. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  42. from pyversion import is_python3
  43. if is_python3():
  44. import urllib.parse
  45. else:
  46. import imp
  47. import urlparse
  48. urllib = imp.new_module('urllib')
  49. urllib.parse = urlparse
  50. input = raw_input
  51. def _lwrite(path, content):
  52. lock = '%s.lock' % path
  53. fd = open(lock, 'w')
  54. try:
  55. fd.write(content)
  56. finally:
  57. fd.close()
  58. try:
  59. platform_utils.rename(lock, path)
  60. except OSError:
  61. platform_utils.remove(lock)
  62. raise
  63. def _error(fmt, *args):
  64. msg = fmt % args
  65. print('error: %s' % msg, file=sys.stderr)
  66. def _warn(fmt, *args):
  67. msg = fmt % args
  68. print('warn: %s' % msg, file=sys.stderr)
  69. def not_rev(r):
  70. return '^' + r
  71. def sq(r):
  72. return "'" + r.replace("'", "'\''") + "'"
  73. _project_hook_list = None
  74. def _ProjectHooks():
  75. """List the hooks present in the 'hooks' directory.
  76. These hooks are project hooks and are copied to the '.git/hooks' directory
  77. of all subprojects.
  78. This function caches the list of hooks (based on the contents of the
  79. 'repo/hooks' directory) on the first call.
  80. Returns:
  81. A list of absolute paths to all of the files in the hooks directory.
  82. """
  83. global _project_hook_list
  84. if _project_hook_list is None:
  85. d = platform_utils.realpath(os.path.abspath(os.path.dirname(__file__)))
  86. d = os.path.join(d, 'hooks')
  87. _project_hook_list = [os.path.join(d, x) for x in platform_utils.listdir(d)]
  88. return _project_hook_list
  89. class DownloadedChange(object):
  90. _commit_cache = None
  91. def __init__(self, project, base, change_id, ps_id, commit):
  92. self.project = project
  93. self.base = base
  94. self.change_id = change_id
  95. self.ps_id = ps_id
  96. self.commit = commit
  97. @property
  98. def commits(self):
  99. if self._commit_cache is None:
  100. self._commit_cache = self.project.bare_git.rev_list('--abbrev=8',
  101. '--abbrev-commit',
  102. '--pretty=oneline',
  103. '--reverse',
  104. '--date-order',
  105. not_rev(self.base),
  106. self.commit,
  107. '--')
  108. return self._commit_cache
  109. class ReviewableBranch(object):
  110. _commit_cache = None
  111. def __init__(self, project, branch, base):
  112. self.project = project
  113. self.branch = branch
  114. self.base = base
  115. @property
  116. def name(self):
  117. return self.branch.name
  118. @property
  119. def commits(self):
  120. if self._commit_cache is None:
  121. self._commit_cache = self.project.bare_git.rev_list('--abbrev=8',
  122. '--abbrev-commit',
  123. '--pretty=oneline',
  124. '--reverse',
  125. '--date-order',
  126. not_rev(self.base),
  127. R_HEADS + self.name,
  128. '--')
  129. return self._commit_cache
  130. @property
  131. def unabbrev_commits(self):
  132. r = dict()
  133. for commit in self.project.bare_git.rev_list(not_rev(self.base),
  134. R_HEADS + self.name,
  135. '--'):
  136. r[commit[0:8]] = commit
  137. return r
  138. @property
  139. def date(self):
  140. return self.project.bare_git.log('--pretty=format:%cd',
  141. '-n', '1',
  142. R_HEADS + self.name,
  143. '--')
  144. def UploadForReview(self, people,
  145. auto_topic=False,
  146. draft=False,
  147. private=False,
  148. notify=None,
  149. wip=False,
  150. dest_branch=None,
  151. validate_certs=True,
  152. push_options=None):
  153. self.project.UploadForReview(self.name,
  154. people,
  155. auto_topic=auto_topic,
  156. draft=draft,
  157. private=private,
  158. notify=notify,
  159. wip=wip,
  160. dest_branch=dest_branch,
  161. validate_certs=validate_certs,
  162. push_options=push_options)
  163. def GetPublishedRefs(self):
  164. refs = {}
  165. output = self.project.bare_git.ls_remote(
  166. self.branch.remote.SshReviewUrl(self.project.UserEmail),
  167. 'refs/changes/*')
  168. for line in output.split('\n'):
  169. try:
  170. (sha, ref) = line.split()
  171. refs[sha] = ref
  172. except ValueError:
  173. pass
  174. return refs
  175. class StatusColoring(Coloring):
  176. def __init__(self, config):
  177. Coloring.__init__(self, config, 'status')
  178. self.project = self.printer('header', attr='bold')
  179. self.branch = self.printer('header', attr='bold')
  180. self.nobranch = self.printer('nobranch', fg='red')
  181. self.important = self.printer('important', fg='red')
  182. self.added = self.printer('added', fg='green')
  183. self.changed = self.printer('changed', fg='red')
  184. self.untracked = self.printer('untracked', fg='red')
  185. class DiffColoring(Coloring):
  186. def __init__(self, config):
  187. Coloring.__init__(self, config, 'diff')
  188. self.project = self.printer('header', attr='bold')
  189. class _Annotation(object):
  190. def __init__(self, name, value, keep):
  191. self.name = name
  192. self.value = value
  193. self.keep = keep
  194. class _CopyFile(object):
  195. def __init__(self, src, dest, abssrc, absdest):
  196. self.src = src
  197. self.dest = dest
  198. self.abs_src = abssrc
  199. self.abs_dest = absdest
  200. def _Copy(self):
  201. src = self.abs_src
  202. dest = self.abs_dest
  203. # copy file if it does not exist or is out of date
  204. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  205. try:
  206. # remove existing file first, since it might be read-only
  207. if os.path.exists(dest):
  208. platform_utils.remove(dest)
  209. else:
  210. dest_dir = os.path.dirname(dest)
  211. if not platform_utils.isdir(dest_dir):
  212. os.makedirs(dest_dir)
  213. shutil.copy(src, dest)
  214. # make the file read-only
  215. mode = os.stat(dest)[stat.ST_MODE]
  216. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  217. os.chmod(dest, mode)
  218. except IOError:
  219. _error('Cannot copy file %s to %s', src, dest)
  220. class _LinkFile(object):
  221. def __init__(self, git_worktree, src, dest, relsrc, absdest):
  222. self.git_worktree = git_worktree
  223. self.src = src
  224. self.dest = dest
  225. self.src_rel_to_dest = relsrc
  226. self.abs_dest = absdest
  227. def __linkIt(self, relSrc, absDest):
  228. # link file if it does not exist or is out of date
  229. if not platform_utils.islink(absDest) or (platform_utils.readlink(absDest) != relSrc):
  230. try:
  231. # remove existing file first, since it might be read-only
  232. if os.path.lexists(absDest):
  233. platform_utils.remove(absDest)
  234. else:
  235. dest_dir = os.path.dirname(absDest)
  236. if not platform_utils.isdir(dest_dir):
  237. os.makedirs(dest_dir)
  238. platform_utils.symlink(relSrc, absDest)
  239. except IOError:
  240. _error('Cannot link file %s to %s', relSrc, absDest)
  241. def _Link(self):
  242. """Link the self.rel_src_to_dest and self.abs_dest. Handles wild cards
  243. on the src linking all of the files in the source in to the destination
  244. directory.
  245. """
  246. # We use the absSrc to handle the situation where the current directory
  247. # is not the root of the repo
  248. absSrc = os.path.join(self.git_worktree, self.src)
  249. if os.path.exists(absSrc):
  250. # Entity exists so just a simple one to one link operation
  251. self.__linkIt(self.src_rel_to_dest, self.abs_dest)
  252. else:
  253. # Entity doesn't exist assume there is a wild card
  254. absDestDir = self.abs_dest
  255. if os.path.exists(absDestDir) and not platform_utils.isdir(absDestDir):
  256. _error('Link error: src with wildcard, %s must be a directory',
  257. absDestDir)
  258. else:
  259. absSrcFiles = glob.glob(absSrc)
  260. for absSrcFile in absSrcFiles:
  261. # Create a releative path from source dir to destination dir
  262. absSrcDir = os.path.dirname(absSrcFile)
  263. relSrcDir = os.path.relpath(absSrcDir, absDestDir)
  264. # Get the source file name
  265. srcFile = os.path.basename(absSrcFile)
  266. # Now form the final full paths to srcFile. They will be
  267. # absolute for the desintaiton and relative for the srouce.
  268. absDest = os.path.join(absDestDir, srcFile)
  269. relSrc = os.path.join(relSrcDir, srcFile)
  270. self.__linkIt(relSrc, absDest)
  271. class RemoteSpec(object):
  272. def __init__(self,
  273. name,
  274. url=None,
  275. pushUrl=None,
  276. review=None,
  277. revision=None,
  278. orig_name=None,
  279. fetchUrl=None):
  280. self.name = name
  281. self.url = url
  282. self.pushUrl = pushUrl
  283. self.review = review
  284. self.revision = revision
  285. self.orig_name = orig_name
  286. self.fetchUrl = fetchUrl
  287. class RepoHook(object):
  288. """A RepoHook contains information about a script to run as a hook.
  289. Hooks are used to run a python script before running an upload (for instance,
  290. to run presubmit checks). Eventually, we may have hooks for other actions.
  291. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  292. files are copied into each '.git/hooks' folder for each project. Repo-level
  293. hooks are associated instead with repo actions.
  294. Hooks are always python. When a hook is run, we will load the hook into the
  295. interpreter and execute its main() function.
  296. """
  297. def __init__(self,
  298. hook_type,
  299. hooks_project,
  300. topdir,
  301. manifest_url,
  302. abort_if_user_denies=False):
  303. """RepoHook constructor.
  304. Params:
  305. hook_type: A string representing the type of hook. This is also used
  306. to figure out the name of the file containing the hook. For
  307. example: 'pre-upload'.
  308. hooks_project: The project containing the repo hooks. If you have a
  309. manifest, this is manifest.repo_hooks_project. OK if this is None,
  310. which will make the hook a no-op.
  311. topdir: Repo's top directory (the one containing the .repo directory).
  312. Scripts will run with CWD as this directory. If you have a manifest,
  313. this is manifest.topdir
  314. manifest_url: The URL to the manifest git repo.
  315. abort_if_user_denies: If True, we'll throw a HookError() if the user
  316. doesn't allow us to run the hook.
  317. """
  318. self._hook_type = hook_type
  319. self._hooks_project = hooks_project
  320. self._manifest_url = manifest_url
  321. self._topdir = topdir
  322. self._abort_if_user_denies = abort_if_user_denies
  323. # Store the full path to the script for convenience.
  324. if self._hooks_project:
  325. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  326. self._hook_type + '.py')
  327. else:
  328. self._script_fullpath = None
  329. def _GetHash(self):
  330. """Return a hash of the contents of the hooks directory.
  331. We'll just use git to do this. This hash has the property that if anything
  332. changes in the directory we will return a different has.
  333. SECURITY CONSIDERATION:
  334. This hash only represents the contents of files in the hook directory, not
  335. any other files imported or called by hooks. Changes to imported files
  336. can change the script behavior without affecting the hash.
  337. Returns:
  338. A string representing the hash. This will always be ASCII so that it can
  339. be printed to the user easily.
  340. """
  341. assert self._hooks_project, "Must have hooks to calculate their hash."
  342. # We will use the work_git object rather than just calling GetRevisionId().
  343. # That gives us a hash of the latest checked in version of the files that
  344. # the user will actually be executing. Specifically, GetRevisionId()
  345. # doesn't appear to change even if a user checks out a different version
  346. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  347. #
  348. # NOTE: Local (non-committed) changes will not be factored into this hash.
  349. # I think this is OK, since we're really only worried about warning the user
  350. # about upstream changes.
  351. return self._hooks_project.work_git.rev_parse('HEAD')
  352. def _GetMustVerb(self):
  353. """Return 'must' if the hook is required; 'should' if not."""
  354. if self._abort_if_user_denies:
  355. return 'must'
  356. else:
  357. return 'should'
  358. def _CheckForHookApproval(self):
  359. """Check to see whether this hook has been approved.
  360. We'll accept approval of manifest URLs if they're using secure transports.
  361. This way the user can say they trust the manifest hoster. For insecure
  362. hosts, we fall back to checking the hash of the hooks repo.
  363. Note that we ask permission for each individual hook even though we use
  364. the hash of all hooks when detecting changes. We'd like the user to be
  365. able to approve / deny each hook individually. We only use the hash of all
  366. hooks because there is no other easy way to detect changes to local imports.
  367. Returns:
  368. True if this hook is approved to run; False otherwise.
  369. Raises:
  370. HookError: Raised if the user doesn't approve and abort_if_user_denies
  371. was passed to the consturctor.
  372. """
  373. if self._ManifestUrlHasSecureScheme():
  374. return self._CheckForHookApprovalManifest()
  375. else:
  376. return self._CheckForHookApprovalHash()
  377. def _CheckForHookApprovalHelper(self, subkey, new_val, main_prompt,
  378. changed_prompt):
  379. """Check for approval for a particular attribute and hook.
  380. Args:
  381. subkey: The git config key under [repo.hooks.<hook_type>] to store the
  382. last approved string.
  383. new_val: The new value to compare against the last approved one.
  384. main_prompt: Message to display to the user to ask for approval.
  385. changed_prompt: Message explaining why we're re-asking for approval.
  386. Returns:
  387. True if this hook is approved to run; False otherwise.
  388. Raises:
  389. HookError: Raised if the user doesn't approve and abort_if_user_denies
  390. was passed to the consturctor.
  391. """
  392. hooks_config = self._hooks_project.config
  393. git_approval_key = 'repo.hooks.%s.%s' % (self._hook_type, subkey)
  394. # Get the last value that the user approved for this hook; may be None.
  395. old_val = hooks_config.GetString(git_approval_key)
  396. if old_val is not None:
  397. # User previously approved hook and asked not to be prompted again.
  398. if new_val == old_val:
  399. # Approval matched. We're done.
  400. return True
  401. else:
  402. # Give the user a reason why we're prompting, since they last told
  403. # us to "never ask again".
  404. prompt = 'WARNING: %s\n\n' % (changed_prompt,)
  405. else:
  406. prompt = ''
  407. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  408. if sys.stdout.isatty():
  409. prompt += main_prompt + ' (yes/always/NO)? '
  410. response = input(prompt).lower()
  411. print()
  412. # User is doing a one-time approval.
  413. if response in ('y', 'yes'):
  414. return True
  415. elif response == 'always':
  416. hooks_config.SetString(git_approval_key, new_val)
  417. return True
  418. # For anything else, we'll assume no approval.
  419. if self._abort_if_user_denies:
  420. raise HookError('You must allow the %s hook or use --no-verify.' %
  421. self._hook_type)
  422. return False
  423. def _ManifestUrlHasSecureScheme(self):
  424. """Check if the URI for the manifest is a secure transport."""
  425. secure_schemes = ('file', 'https', 'ssh', 'persistent-https', 'sso', 'rpc')
  426. parse_results = urllib.parse.urlparse(self._manifest_url)
  427. return parse_results.scheme in secure_schemes
  428. def _CheckForHookApprovalManifest(self):
  429. """Check whether the user has approved this manifest host.
  430. Returns:
  431. True if this hook is approved to run; False otherwise.
  432. """
  433. return self._CheckForHookApprovalHelper(
  434. 'approvedmanifest',
  435. self._manifest_url,
  436. 'Run hook scripts from %s' % (self._manifest_url,),
  437. 'Manifest URL has changed since %s was allowed.' % (self._hook_type,))
  438. def _CheckForHookApprovalHash(self):
  439. """Check whether the user has approved the hooks repo.
  440. Returns:
  441. True if this hook is approved to run; False otherwise.
  442. """
  443. prompt = ('Repo %s run the script:\n'
  444. ' %s\n'
  445. '\n'
  446. 'Do you want to allow this script to run')
  447. return self._CheckForHookApprovalHelper(
  448. 'approvedhash',
  449. self._GetHash(),
  450. prompt % (self._GetMustVerb(), self._script_fullpath),
  451. 'Scripts have changed since %s was allowed.' % (self._hook_type,))
  452. @staticmethod
  453. def _ExtractInterpFromShebang(data):
  454. """Extract the interpreter used in the shebang.
  455. Try to locate the interpreter the script is using (ignoring `env`).
  456. Args:
  457. data: The file content of the script.
  458. Returns:
  459. The basename of the main script interpreter, or None if a shebang is not
  460. used or could not be parsed out.
  461. """
  462. firstline = data.splitlines()[:1]
  463. if not firstline:
  464. return None
  465. # The format here can be tricky.
  466. shebang = firstline[0].strip()
  467. m = re.match(r'^#!\s*([^\s]+)(?:\s+([^\s]+))?', shebang)
  468. if not m:
  469. return None
  470. # If the using `env`, find the target program.
  471. interp = m.group(1)
  472. if os.path.basename(interp) == 'env':
  473. interp = m.group(2)
  474. return interp
  475. def _ExecuteHookViaReexec(self, interp, context, **kwargs):
  476. """Execute the hook script through |interp|.
  477. Note: Support for this feature should be dropped ~Jun 2021.
  478. Args:
  479. interp: The Python program to run.
  480. context: Basic Python context to execute the hook inside.
  481. kwargs: Arbitrary arguments to pass to the hook script.
  482. Raises:
  483. HookError: When the hooks failed for any reason.
  484. """
  485. # This logic needs to be kept in sync with _ExecuteHookViaImport below.
  486. script = """
  487. import json, os, sys
  488. path = '''%(path)s'''
  489. kwargs = json.loads('''%(kwargs)s''')
  490. context = json.loads('''%(context)s''')
  491. sys.path.insert(0, os.path.dirname(path))
  492. data = open(path).read()
  493. exec(compile(data, path, 'exec'), context)
  494. context['main'](**kwargs)
  495. """ % {
  496. 'path': self._script_fullpath,
  497. 'kwargs': json.dumps(kwargs),
  498. 'context': json.dumps(context),
  499. }
  500. # We pass the script via stdin to avoid OS argv limits. It also makes
  501. # unhandled exception tracebacks less verbose/confusing for users.
  502. cmd = [interp, '-c', 'import sys; exec(sys.stdin.read())']
  503. proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  504. proc.communicate(input=script.encode('utf-8'))
  505. if proc.returncode:
  506. raise HookError('Failed to run %s hook.' % (self._hook_type,))
  507. def _ExecuteHookViaImport(self, data, context, **kwargs):
  508. """Execute the hook code in |data| directly.
  509. Args:
  510. data: The code of the hook to execute.
  511. context: Basic Python context to execute the hook inside.
  512. kwargs: Arbitrary arguments to pass to the hook script.
  513. Raises:
  514. HookError: When the hooks failed for any reason.
  515. """
  516. # Exec, storing global context in the context dict. We catch exceptions
  517. # and convert to a HookError w/ just the failing traceback.
  518. try:
  519. exec(compile(data, self._script_fullpath, 'exec'), context)
  520. except Exception:
  521. raise HookError('%s\nFailed to import %s hook; see traceback above.' %
  522. (traceback.format_exc(), self._hook_type))
  523. # Running the script should have defined a main() function.
  524. if 'main' not in context:
  525. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  526. # Call the main function in the hook. If the hook should cause the
  527. # build to fail, it will raise an Exception. We'll catch that convert
  528. # to a HookError w/ just the failing traceback.
  529. try:
  530. context['main'](**kwargs)
  531. except Exception:
  532. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  533. 'above.' % (traceback.format_exc(), self._hook_type))
  534. def _ExecuteHook(self, **kwargs):
  535. """Actually execute the given hook.
  536. This will run the hook's 'main' function in our python interpreter.
  537. Args:
  538. kwargs: Keyword arguments to pass to the hook. These are often specific
  539. to the hook type. For instance, pre-upload hooks will contain
  540. a project_list.
  541. """
  542. # Keep sys.path and CWD stashed away so that we can always restore them
  543. # upon function exit.
  544. orig_path = os.getcwd()
  545. orig_syspath = sys.path
  546. try:
  547. # Always run hooks with CWD as topdir.
  548. os.chdir(self._topdir)
  549. # Put the hook dir as the first item of sys.path so hooks can do
  550. # relative imports. We want to replace the repo dir as [0] so
  551. # hooks can't import repo files.
  552. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  553. # Initial global context for the hook to run within.
  554. context = {'__file__': self._script_fullpath}
  555. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  556. # We don't actually want hooks to define their main with this argument--
  557. # it's there to remind them that their hook should always take **kwargs.
  558. # For instance, a pre-upload hook should be defined like:
  559. # def main(project_list, **kwargs):
  560. #
  561. # This allows us to later expand the API without breaking old hooks.
  562. kwargs = kwargs.copy()
  563. kwargs['hook_should_take_kwargs'] = True
  564. # See what version of python the hook has been written against.
  565. data = open(self._script_fullpath).read()
  566. interp = self._ExtractInterpFromShebang(data)
  567. reexec = False
  568. if interp:
  569. prog = os.path.basename(interp)
  570. if prog.startswith('python2') and sys.version_info.major != 2:
  571. reexec = True
  572. elif prog.startswith('python3') and sys.version_info.major == 2:
  573. reexec = True
  574. # Attempt to execute the hooks through the requested version of Python.
  575. if reexec:
  576. try:
  577. self._ExecuteHookViaReexec(interp, context, **kwargs)
  578. except OSError as e:
  579. if e.errno == errno.ENOENT:
  580. # We couldn't find the interpreter, so fallback to importing.
  581. reexec = False
  582. else:
  583. raise
  584. # Run the hook by importing directly.
  585. if not reexec:
  586. self._ExecuteHookViaImport(data, context, **kwargs)
  587. finally:
  588. # Restore sys.path and CWD.
  589. sys.path = orig_syspath
  590. os.chdir(orig_path)
  591. def Run(self, user_allows_all_hooks, **kwargs):
  592. """Run the hook.
  593. If the hook doesn't exist (because there is no hooks project or because
  594. this particular hook is not enabled), this is a no-op.
  595. Args:
  596. user_allows_all_hooks: If True, we will never prompt about running the
  597. hook--we'll just assume it's OK to run it.
  598. kwargs: Keyword arguments to pass to the hook. These are often specific
  599. to the hook type. For instance, pre-upload hooks will contain
  600. a project_list.
  601. Raises:
  602. HookError: If there was a problem finding the hook or the user declined
  603. to run a required hook (from _CheckForHookApproval).
  604. """
  605. # No-op if there is no hooks project or if hook is disabled.
  606. if ((not self._hooks_project) or (self._hook_type not in
  607. self._hooks_project.enabled_repo_hooks)):
  608. return
  609. # Bail with a nice error if we can't find the hook.
  610. if not os.path.isfile(self._script_fullpath):
  611. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  612. # Make sure the user is OK with running the hook.
  613. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  614. return
  615. # Run the hook with the same version of python we're using.
  616. self._ExecuteHook(**kwargs)
  617. class Project(object):
  618. # These objects can be shared between several working trees.
  619. shareable_files = ['description', 'info']
  620. shareable_dirs = ['hooks', 'objects', 'rr-cache', 'svn']
  621. # These objects can only be used by a single working tree.
  622. working_tree_files = ['config', 'packed-refs', 'shallow']
  623. working_tree_dirs = ['logs', 'refs']
  624. def __init__(self,
  625. manifest,
  626. name,
  627. remote,
  628. gitdir,
  629. objdir,
  630. worktree,
  631. relpath,
  632. revisionExpr,
  633. revisionId,
  634. rebase=True,
  635. groups=None,
  636. sync_c=False,
  637. sync_s=False,
  638. sync_tags=True,
  639. clone_depth=None,
  640. upstream=None,
  641. parent=None,
  642. is_derived=False,
  643. dest_branch=None,
  644. optimized_fetch=False,
  645. old_revision=None):
  646. """Init a Project object.
  647. Args:
  648. manifest: The XmlManifest object.
  649. name: The `name` attribute of manifest.xml's project element.
  650. remote: RemoteSpec object specifying its remote's properties.
  651. gitdir: Absolute path of git directory.
  652. objdir: Absolute path of directory to store git objects.
  653. worktree: Absolute path of git working tree.
  654. relpath: Relative path of git working tree to repo's top directory.
  655. revisionExpr: The `revision` attribute of manifest.xml's project element.
  656. revisionId: git commit id for checking out.
  657. rebase: The `rebase` attribute of manifest.xml's project element.
  658. groups: The `groups` attribute of manifest.xml's project element.
  659. sync_c: The `sync-c` attribute of manifest.xml's project element.
  660. sync_s: The `sync-s` attribute of manifest.xml's project element.
  661. sync_tags: The `sync-tags` attribute of manifest.xml's project element.
  662. upstream: The `upstream` attribute of manifest.xml's project element.
  663. parent: The parent Project object.
  664. is_derived: False if the project was explicitly defined in the manifest;
  665. True if the project is a discovered submodule.
  666. dest_branch: The branch to which to push changes for review by default.
  667. optimized_fetch: If True, when a project is set to a sha1 revision, only
  668. fetch from the remote if the sha1 is not present locally.
  669. old_revision: saved git commit id for open GITC projects.
  670. """
  671. self.manifest = manifest
  672. self.name = name
  673. self.remote = remote
  674. self.gitdir = gitdir.replace('\\', '/')
  675. self.objdir = objdir.replace('\\', '/')
  676. if worktree:
  677. self.worktree = os.path.normpath(worktree).replace('\\', '/')
  678. else:
  679. self.worktree = None
  680. self.relpath = relpath
  681. self.revisionExpr = revisionExpr
  682. if revisionId is None \
  683. and revisionExpr \
  684. and IsId(revisionExpr):
  685. self.revisionId = revisionExpr
  686. else:
  687. self.revisionId = revisionId
  688. self.rebase = rebase
  689. self.groups = groups
  690. self.sync_c = sync_c
  691. self.sync_s = sync_s
  692. self.sync_tags = sync_tags
  693. self.clone_depth = clone_depth
  694. self.upstream = upstream
  695. self.parent = parent
  696. self.is_derived = is_derived
  697. self.optimized_fetch = optimized_fetch
  698. self.subprojects = []
  699. self.snapshots = {}
  700. self.copyfiles = []
  701. self.linkfiles = []
  702. self.annotations = []
  703. self.config = GitConfig.ForRepository(gitdir=self.gitdir,
  704. defaults=self.manifest.globalConfig)
  705. if self.worktree:
  706. self.work_git = self._GitGetByExec(self, bare=False, gitdir=gitdir)
  707. else:
  708. self.work_git = None
  709. self.bare_git = self._GitGetByExec(self, bare=True, gitdir=gitdir)
  710. self.bare_ref = GitRefs(gitdir)
  711. self.bare_objdir = self._GitGetByExec(self, bare=True, gitdir=objdir)
  712. self.dest_branch = dest_branch
  713. self.old_revision = old_revision
  714. # This will be filled in if a project is later identified to be the
  715. # project containing repo hooks.
  716. self.enabled_repo_hooks = []
  717. @property
  718. def Derived(self):
  719. return self.is_derived
  720. @property
  721. def Exists(self):
  722. return platform_utils.isdir(self.gitdir) and platform_utils.isdir(self.objdir)
  723. @property
  724. def CurrentBranch(self):
  725. """Obtain the name of the currently checked out branch.
  726. The branch name omits the 'refs/heads/' prefix.
  727. None is returned if the project is on a detached HEAD.
  728. """
  729. b = self.work_git.GetHead()
  730. if b.startswith(R_HEADS):
  731. return b[len(R_HEADS):]
  732. return None
  733. def IsRebaseInProgress(self):
  734. w = self.worktree
  735. g = os.path.join(w, '.git')
  736. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  737. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  738. or os.path.exists(os.path.join(w, '.dotest'))
  739. def IsDirty(self, consider_untracked=True):
  740. """Is the working directory modified in some way?
  741. """
  742. self.work_git.update_index('-q',
  743. '--unmerged',
  744. '--ignore-missing',
  745. '--refresh')
  746. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  747. return True
  748. if self.work_git.DiffZ('diff-files'):
  749. return True
  750. if consider_untracked and self.work_git.LsOthers():
  751. return True
  752. return False
  753. _userident_name = None
  754. _userident_email = None
  755. @property
  756. def UserName(self):
  757. """Obtain the user's personal name.
  758. """
  759. if self._userident_name is None:
  760. self._LoadUserIdentity()
  761. return self._userident_name
  762. @property
  763. def UserEmail(self):
  764. """Obtain the user's email address. This is very likely
  765. to be their Gerrit login.
  766. """
  767. if self._userident_email is None:
  768. self._LoadUserIdentity()
  769. return self._userident_email
  770. def _LoadUserIdentity(self):
  771. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  772. m = re.compile("^(.*) <([^>]*)> ").match(u)
  773. if m:
  774. self._userident_name = m.group(1)
  775. self._userident_email = m.group(2)
  776. else:
  777. self._userident_name = ''
  778. self._userident_email = ''
  779. def GetRemote(self, name):
  780. """Get the configuration for a single remote.
  781. """
  782. return self.config.GetRemote(name)
  783. def GetBranch(self, name):
  784. """Get the configuration for a single branch.
  785. """
  786. return self.config.GetBranch(name)
  787. def GetBranches(self):
  788. """Get all existing local branches.
  789. """
  790. current = self.CurrentBranch
  791. all_refs = self._allrefs
  792. heads = {}
  793. for name, ref_id in all_refs.items():
  794. if name.startswith(R_HEADS):
  795. name = name[len(R_HEADS):]
  796. b = self.GetBranch(name)
  797. b.current = name == current
  798. b.published = None
  799. b.revision = ref_id
  800. heads[name] = b
  801. for name, ref_id in all_refs.items():
  802. if name.startswith(R_PUB):
  803. name = name[len(R_PUB):]
  804. b = heads.get(name)
  805. if b:
  806. b.published = ref_id
  807. return heads
  808. def MatchesGroups(self, manifest_groups):
  809. """Returns true if the manifest groups specified at init should cause
  810. this project to be synced.
  811. Prefixing a manifest group with "-" inverts the meaning of a group.
  812. All projects are implicitly labelled with "all".
  813. labels are resolved in order. In the example case of
  814. project_groups: "all,group1,group2"
  815. manifest_groups: "-group1,group2"
  816. the project will be matched.
  817. The special manifest group "default" will match any project that
  818. does not have the special project group "notdefault"
  819. """
  820. expanded_manifest_groups = manifest_groups or ['default']
  821. expanded_project_groups = ['all'] + (self.groups or [])
  822. if 'notdefault' not in expanded_project_groups:
  823. expanded_project_groups += ['default']
  824. matched = False
  825. for group in expanded_manifest_groups:
  826. if group.startswith('-') and group[1:] in expanded_project_groups:
  827. matched = False
  828. elif group in expanded_project_groups:
  829. matched = True
  830. return matched
  831. # Status Display ##
  832. def UncommitedFiles(self, get_all=True):
  833. """Returns a list of strings, uncommitted files in the git tree.
  834. Args:
  835. get_all: a boolean, if True - get information about all different
  836. uncommitted files. If False - return as soon as any kind of
  837. uncommitted files is detected.
  838. """
  839. details = []
  840. self.work_git.update_index('-q',
  841. '--unmerged',
  842. '--ignore-missing',
  843. '--refresh')
  844. if self.IsRebaseInProgress():
  845. details.append("rebase in progress")
  846. if not get_all:
  847. return details
  848. changes = self.work_git.DiffZ('diff-index', '--cached', HEAD).keys()
  849. if changes:
  850. details.extend(changes)
  851. if not get_all:
  852. return details
  853. changes = self.work_git.DiffZ('diff-files').keys()
  854. if changes:
  855. details.extend(changes)
  856. if not get_all:
  857. return details
  858. changes = self.work_git.LsOthers()
  859. if changes:
  860. details.extend(changes)
  861. return details
  862. def HasChanges(self):
  863. """Returns true if there are uncommitted changes.
  864. """
  865. if self.UncommitedFiles(get_all=False):
  866. return True
  867. else:
  868. return False
  869. def PrintWorkTreeStatus(self, output_redir=None, quiet=False):
  870. """Prints the status of the repository to stdout.
  871. Args:
  872. output: If specified, redirect the output to this object.
  873. quiet: If True then only print the project name. Do not print
  874. the modified files, branch name, etc.
  875. """
  876. if not platform_utils.isdir(self.worktree):
  877. if output_redir is None:
  878. output_redir = sys.stdout
  879. print(file=output_redir)
  880. print('project %s/' % self.relpath, file=output_redir)
  881. print(' missing (run "repo sync")', file=output_redir)
  882. return
  883. self.work_git.update_index('-q',
  884. '--unmerged',
  885. '--ignore-missing',
  886. '--refresh')
  887. rb = self.IsRebaseInProgress()
  888. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  889. df = self.work_git.DiffZ('diff-files')
  890. do = self.work_git.LsOthers()
  891. if not rb and not di and not df and not do and not self.CurrentBranch:
  892. return 'CLEAN'
  893. out = StatusColoring(self.config)
  894. if output_redir is not None:
  895. out.redirect(output_redir)
  896. out.project('project %-40s', self.relpath + '/ ')
  897. if quiet:
  898. out.nl()
  899. return 'DIRTY'
  900. branch = self.CurrentBranch
  901. if branch is None:
  902. out.nobranch('(*** NO BRANCH ***)')
  903. else:
  904. out.branch('branch %s', branch)
  905. out.nl()
  906. if rb:
  907. out.important('prior sync failed; rebase still in progress')
  908. out.nl()
  909. paths = list()
  910. paths.extend(di.keys())
  911. paths.extend(df.keys())
  912. paths.extend(do)
  913. for p in sorted(set(paths)):
  914. try:
  915. i = di[p]
  916. except KeyError:
  917. i = None
  918. try:
  919. f = df[p]
  920. except KeyError:
  921. f = None
  922. if i:
  923. i_status = i.status.upper()
  924. else:
  925. i_status = '-'
  926. if f:
  927. f_status = f.status.lower()
  928. else:
  929. f_status = '-'
  930. if i and i.src_path:
  931. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  932. i.src_path, p, i.level)
  933. else:
  934. line = ' %s%s\t%s' % (i_status, f_status, p)
  935. if i and not f:
  936. out.added('%s', line)
  937. elif (i and f) or (not i and f):
  938. out.changed('%s', line)
  939. elif not i and not f:
  940. out.untracked('%s', line)
  941. else:
  942. out.write('%s', line)
  943. out.nl()
  944. return 'DIRTY'
  945. def PrintWorkTreeDiff(self, absolute_paths=False):
  946. """Prints the status of the repository to stdout.
  947. """
  948. out = DiffColoring(self.config)
  949. cmd = ['diff']
  950. if out.is_on:
  951. cmd.append('--color')
  952. cmd.append(HEAD)
  953. if absolute_paths:
  954. cmd.append('--src-prefix=a/%s/' % self.relpath)
  955. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  956. cmd.append('--')
  957. p = GitCommand(self,
  958. cmd,
  959. capture_stdout=True,
  960. capture_stderr=True)
  961. has_diff = False
  962. for line in p.process.stdout:
  963. if not hasattr(line, 'encode'):
  964. line = line.decode()
  965. if not has_diff:
  966. out.nl()
  967. out.project('project %s/' % self.relpath)
  968. out.nl()
  969. has_diff = True
  970. print(line[:-1])
  971. p.Wait()
  972. # Publish / Upload ##
  973. def WasPublished(self, branch, all_refs=None):
  974. """Was the branch published (uploaded) for code review?
  975. If so, returns the SHA-1 hash of the last published
  976. state for the branch.
  977. """
  978. key = R_PUB + branch
  979. if all_refs is None:
  980. try:
  981. return self.bare_git.rev_parse(key)
  982. except GitError:
  983. return None
  984. else:
  985. try:
  986. return all_refs[key]
  987. except KeyError:
  988. return None
  989. def CleanPublishedCache(self, all_refs=None):
  990. """Prunes any stale published refs.
  991. """
  992. if all_refs is None:
  993. all_refs = self._allrefs
  994. heads = set()
  995. canrm = {}
  996. for name, ref_id in all_refs.items():
  997. if name.startswith(R_HEADS):
  998. heads.add(name)
  999. elif name.startswith(R_PUB):
  1000. canrm[name] = ref_id
  1001. for name, ref_id in canrm.items():
  1002. n = name[len(R_PUB):]
  1003. if R_HEADS + n not in heads:
  1004. self.bare_git.DeleteRef(name, ref_id)
  1005. def GetUploadableBranches(self, selected_branch=None):
  1006. """List any branches which can be uploaded for review.
  1007. """
  1008. heads = {}
  1009. pubed = {}
  1010. for name, ref_id in self._allrefs.items():
  1011. if name.startswith(R_HEADS):
  1012. heads[name[len(R_HEADS):]] = ref_id
  1013. elif name.startswith(R_PUB):
  1014. pubed[name[len(R_PUB):]] = ref_id
  1015. ready = []
  1016. for branch, ref_id in heads.items():
  1017. if branch in pubed and pubed[branch] == ref_id:
  1018. continue
  1019. if selected_branch and branch != selected_branch:
  1020. continue
  1021. rb = self.GetUploadableBranch(branch)
  1022. if rb:
  1023. ready.append(rb)
  1024. return ready
  1025. def GetUploadableBranch(self, branch_name):
  1026. """Get a single uploadable branch, or None.
  1027. """
  1028. branch = self.GetBranch(branch_name)
  1029. base = branch.LocalMerge
  1030. if branch.LocalMerge:
  1031. rb = ReviewableBranch(self, branch, base)
  1032. if rb.commits:
  1033. return rb
  1034. return None
  1035. def UploadForReview(self, branch=None,
  1036. people=([], []),
  1037. auto_topic=False,
  1038. draft=False,
  1039. private=False,
  1040. notify=None,
  1041. wip=False,
  1042. dest_branch=None,
  1043. validate_certs=True,
  1044. push_options=None):
  1045. """Uploads the named branch for code review.
  1046. """
  1047. if branch is None:
  1048. branch = self.CurrentBranch
  1049. if branch is None:
  1050. raise GitError('not currently on a branch')
  1051. branch = self.GetBranch(branch)
  1052. if not branch.LocalMerge:
  1053. raise GitError('branch %s does not track a remote' % branch.name)
  1054. if not branch.remote.review:
  1055. raise GitError('remote %s has no review url' % branch.remote.name)
  1056. if dest_branch is None:
  1057. dest_branch = self.dest_branch
  1058. if dest_branch is None:
  1059. dest_branch = branch.merge
  1060. if not dest_branch.startswith(R_HEADS):
  1061. dest_branch = R_HEADS + dest_branch
  1062. if not branch.remote.projectname:
  1063. branch.remote.projectname = self.name
  1064. branch.remote.Save()
  1065. url = branch.remote.ReviewUrl(self.UserEmail, validate_certs)
  1066. if url is None:
  1067. raise UploadError('review not configured')
  1068. cmd = ['push']
  1069. if url.startswith('ssh://'):
  1070. cmd.append('--receive-pack=gerrit receive-pack')
  1071. for push_option in (push_options or []):
  1072. cmd.append('-o')
  1073. cmd.append(push_option)
  1074. cmd.append(url)
  1075. if dest_branch.startswith(R_HEADS):
  1076. dest_branch = dest_branch[len(R_HEADS):]
  1077. upload_type = 'for'
  1078. if draft:
  1079. upload_type = 'drafts'
  1080. ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
  1081. dest_branch)
  1082. opts = []
  1083. if auto_topic:
  1084. opts += ['topic=' + branch.name]
  1085. opts += ['r=%s' % p for p in people[0]]
  1086. opts += ['cc=%s' % p for p in people[1]]
  1087. if notify:
  1088. opts += ['notify=' + notify]
  1089. if private:
  1090. opts += ['private']
  1091. if wip:
  1092. opts += ['wip']
  1093. if opts:
  1094. ref_spec = ref_spec + '%' + ','.join(opts)
  1095. cmd.append(ref_spec)
  1096. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1097. raise UploadError('Upload failed')
  1098. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  1099. self.bare_git.UpdateRef(R_PUB + branch.name,
  1100. R_HEADS + branch.name,
  1101. message=msg)
  1102. # Sync ##
  1103. def _ExtractArchive(self, tarpath, path=None):
  1104. """Extract the given tar on its current location
  1105. Args:
  1106. - tarpath: The path to the actual tar file
  1107. """
  1108. try:
  1109. with tarfile.open(tarpath, 'r') as tar:
  1110. tar.extractall(path=path)
  1111. return True
  1112. except (IOError, tarfile.TarError) as e:
  1113. _error("Cannot extract archive %s: %s", tarpath, str(e))
  1114. return False
  1115. def Sync_NetworkHalf(self,
  1116. quiet=False,
  1117. is_new=None,
  1118. current_branch_only=False,
  1119. force_sync=False,
  1120. clone_bundle=True,
  1121. no_tags=False,
  1122. archive=False,
  1123. optimized_fetch=False,
  1124. prune=False,
  1125. submodules=False,
  1126. clone_filter=None):
  1127. """Perform only the network IO portion of the sync process.
  1128. Local working directory/branch state is not affected.
  1129. """
  1130. if archive and not isinstance(self, MetaProject):
  1131. if self.remote.url.startswith(('http://', 'https://')):
  1132. _error("%s: Cannot fetch archives from http/https remotes.", self.name)
  1133. return False
  1134. name = self.relpath.replace('\\', '/')
  1135. name = name.replace('/', '_')
  1136. tarpath = '%s.tar' % name
  1137. topdir = self.manifest.topdir
  1138. try:
  1139. self._FetchArchive(tarpath, cwd=topdir)
  1140. except GitError as e:
  1141. _error('%s', e)
  1142. return False
  1143. # From now on, we only need absolute tarpath
  1144. tarpath = os.path.join(topdir, tarpath)
  1145. if not self._ExtractArchive(tarpath, path=topdir):
  1146. return False
  1147. try:
  1148. platform_utils.remove(tarpath)
  1149. except OSError as e:
  1150. _warn("Cannot remove archive %s: %s", tarpath, str(e))
  1151. self._CopyAndLinkFiles()
  1152. return True
  1153. if is_new is None:
  1154. is_new = not self.Exists
  1155. if is_new:
  1156. self._InitGitDir(force_sync=force_sync)
  1157. else:
  1158. self._UpdateHooks()
  1159. self._InitRemote()
  1160. if is_new:
  1161. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  1162. try:
  1163. fd = open(alt)
  1164. try:
  1165. # This works for both absolute and relative alternate directories.
  1166. alt_dir = os.path.join(self.objdir, 'objects', fd.readline().rstrip())
  1167. finally:
  1168. fd.close()
  1169. except IOError:
  1170. alt_dir = None
  1171. else:
  1172. alt_dir = None
  1173. if clone_bundle \
  1174. and alt_dir is None \
  1175. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  1176. is_new = False
  1177. if not current_branch_only:
  1178. if self.sync_c:
  1179. current_branch_only = True
  1180. elif not self.manifest._loaded:
  1181. # Manifest cannot check defaults until it syncs.
  1182. current_branch_only = False
  1183. elif self.manifest.default.sync_c:
  1184. current_branch_only = True
  1185. if not no_tags:
  1186. if not self.sync_tags:
  1187. no_tags = True
  1188. if self.clone_depth:
  1189. depth = self.clone_depth
  1190. else:
  1191. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1192. need_to_fetch = not (optimized_fetch and
  1193. (ID_RE.match(self.revisionExpr) and
  1194. self._CheckForImmutableRevision()))
  1195. if (need_to_fetch and
  1196. not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  1197. current_branch_only=current_branch_only,
  1198. no_tags=no_tags, prune=prune, depth=depth,
  1199. submodules=submodules, force_sync=force_sync,
  1200. clone_filter=clone_filter)):
  1201. return False
  1202. mp = self.manifest.manifestProject
  1203. dissociate = mp.config.GetBoolean('repo.dissociate')
  1204. if dissociate:
  1205. alternates_file = os.path.join(self.gitdir, 'objects/info/alternates')
  1206. if os.path.exists(alternates_file):
  1207. cmd = ['repack', '-a', '-d']
  1208. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1209. return False
  1210. platform_utils.remove(alternates_file)
  1211. if self.worktree:
  1212. self._InitMRef()
  1213. else:
  1214. self._InitMirrorHead()
  1215. try:
  1216. platform_utils.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  1217. except OSError:
  1218. pass
  1219. return True
  1220. def PostRepoUpgrade(self):
  1221. self._InitHooks()
  1222. def _CopyAndLinkFiles(self):
  1223. if self.manifest.isGitcClient:
  1224. return
  1225. for copyfile in self.copyfiles:
  1226. copyfile._Copy()
  1227. for linkfile in self.linkfiles:
  1228. linkfile._Link()
  1229. def GetCommitRevisionId(self):
  1230. """Get revisionId of a commit.
  1231. Use this method instead of GetRevisionId to get the id of the commit rather
  1232. than the id of the current git object (for example, a tag)
  1233. """
  1234. if not self.revisionExpr.startswith(R_TAGS):
  1235. return self.GetRevisionId(self._allrefs)
  1236. try:
  1237. return self.bare_git.rev_list(self.revisionExpr, '-1')[0]
  1238. except GitError:
  1239. raise ManifestInvalidRevisionError('revision %s in %s not found' %
  1240. (self.revisionExpr, self.name))
  1241. def GetRevisionId(self, all_refs=None):
  1242. if self.revisionId:
  1243. return self.revisionId
  1244. rem = self.GetRemote(self.remote.name)
  1245. rev = rem.ToLocal(self.revisionExpr)
  1246. if all_refs is not None and rev in all_refs:
  1247. return all_refs[rev]
  1248. try:
  1249. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  1250. except GitError:
  1251. raise ManifestInvalidRevisionError('revision %s in %s not found' %
  1252. (self.revisionExpr, self.name))
  1253. def Sync_LocalHalf(self, syncbuf, force_sync=False, submodules=False):
  1254. """Perform only the local IO portion of the sync process.
  1255. Network access is not required.
  1256. """
  1257. self._InitWorkTree(force_sync=force_sync, submodules=submodules)
  1258. all_refs = self.bare_ref.all
  1259. self.CleanPublishedCache(all_refs)
  1260. revid = self.GetRevisionId(all_refs)
  1261. def _doff():
  1262. self._FastForward(revid)
  1263. self._CopyAndLinkFiles()
  1264. def _dosubmodules():
  1265. self._SyncSubmodules(quiet=True)
  1266. head = self.work_git.GetHead()
  1267. if head.startswith(R_HEADS):
  1268. branch = head[len(R_HEADS):]
  1269. try:
  1270. head = all_refs[head]
  1271. except KeyError:
  1272. head = None
  1273. else:
  1274. branch = None
  1275. if branch is None or syncbuf.detach_head:
  1276. # Currently on a detached HEAD. The user is assumed to
  1277. # not have any local modifications worth worrying about.
  1278. #
  1279. if self.IsRebaseInProgress():
  1280. syncbuf.fail(self, _PriorSyncFailedError())
  1281. return
  1282. if head == revid:
  1283. # No changes; don't do anything further.
  1284. # Except if the head needs to be detached
  1285. #
  1286. if not syncbuf.detach_head:
  1287. # The copy/linkfile config may have changed.
  1288. self._CopyAndLinkFiles()
  1289. return
  1290. else:
  1291. lost = self._revlist(not_rev(revid), HEAD)
  1292. if lost:
  1293. syncbuf.info(self, "discarding %d commits", len(lost))
  1294. try:
  1295. self._Checkout(revid, quiet=True)
  1296. if submodules:
  1297. self._SyncSubmodules(quiet=True)
  1298. except GitError as e:
  1299. syncbuf.fail(self, e)
  1300. return
  1301. self._CopyAndLinkFiles()
  1302. return
  1303. if head == revid:
  1304. # No changes; don't do anything further.
  1305. #
  1306. # The copy/linkfile config may have changed.
  1307. self._CopyAndLinkFiles()
  1308. return
  1309. branch = self.GetBranch(branch)
  1310. if not branch.LocalMerge:
  1311. # The current branch has no tracking configuration.
  1312. # Jump off it to a detached HEAD.
  1313. #
  1314. syncbuf.info(self,
  1315. "leaving %s; does not track upstream",
  1316. branch.name)
  1317. try:
  1318. self._Checkout(revid, quiet=True)
  1319. if submodules:
  1320. self._SyncSubmodules(quiet=True)
  1321. except GitError as e:
  1322. syncbuf.fail(self, e)
  1323. return
  1324. self._CopyAndLinkFiles()
  1325. return
  1326. upstream_gain = self._revlist(not_rev(HEAD), revid)
  1327. pub = self.WasPublished(branch.name, all_refs)
  1328. if pub:
  1329. not_merged = self._revlist(not_rev(revid), pub)
  1330. if not_merged:
  1331. if upstream_gain:
  1332. # The user has published this branch and some of those
  1333. # commits are not yet merged upstream. We do not want
  1334. # to rewrite the published commits so we punt.
  1335. #
  1336. syncbuf.fail(self,
  1337. "branch %s is published (but not merged) and is now "
  1338. "%d commits behind" % (branch.name, len(upstream_gain)))
  1339. return
  1340. elif pub == head:
  1341. # All published commits are merged, and thus we are a
  1342. # strict subset. We can fast-forward safely.
  1343. #
  1344. syncbuf.later1(self, _doff)
  1345. if submodules:
  1346. syncbuf.later1(self, _dosubmodules)
  1347. return
  1348. # Examine the local commits not in the remote. Find the
  1349. # last one attributed to this user, if any.
  1350. #
  1351. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  1352. last_mine = None
  1353. cnt_mine = 0
  1354. for commit in local_changes:
  1355. commit_id, committer_email = commit.split(' ', 1)
  1356. if committer_email == self.UserEmail:
  1357. last_mine = commit_id
  1358. cnt_mine += 1
  1359. if not upstream_gain and cnt_mine == len(local_changes):
  1360. return
  1361. if self.IsDirty(consider_untracked=False):
  1362. syncbuf.fail(self, _DirtyError())
  1363. return
  1364. # If the upstream switched on us, warn the user.
  1365. #
  1366. if branch.merge != self.revisionExpr:
  1367. if branch.merge and self.revisionExpr:
  1368. syncbuf.info(self,
  1369. 'manifest switched %s...%s',
  1370. branch.merge,
  1371. self.revisionExpr)
  1372. elif branch.merge:
  1373. syncbuf.info(self,
  1374. 'manifest no longer tracks %s',
  1375. branch.merge)
  1376. if cnt_mine < len(local_changes):
  1377. # Upstream rebased. Not everything in HEAD
  1378. # was created by this user.
  1379. #
  1380. syncbuf.info(self,
  1381. "discarding %d commits removed from upstream",
  1382. len(local_changes) - cnt_mine)
  1383. branch.remote = self.GetRemote(self.remote.name)
  1384. if not ID_RE.match(self.revisionExpr):
  1385. # in case of manifest sync the revisionExpr might be a SHA1
  1386. branch.merge = self.revisionExpr
  1387. if not branch.merge.startswith('refs/'):
  1388. branch.merge = R_HEADS + branch.merge
  1389. branch.Save()
  1390. if cnt_mine > 0 and self.rebase:
  1391. def _docopyandlink():
  1392. self._CopyAndLinkFiles()
  1393. def _dorebase():
  1394. self._Rebase(upstream='%s^1' % last_mine, onto=revid)
  1395. syncbuf.later2(self, _dorebase)
  1396. if submodules:
  1397. syncbuf.later2(self, _dosubmodules)
  1398. syncbuf.later2(self, _docopyandlink)
  1399. elif local_changes:
  1400. try:
  1401. self._ResetHard(revid)
  1402. if submodules:
  1403. self._SyncSubmodules(quiet=True)
  1404. self._CopyAndLinkFiles()
  1405. except GitError as e:
  1406. syncbuf.fail(self, e)
  1407. return
  1408. else:
  1409. syncbuf.later1(self, _doff)
  1410. if submodules:
  1411. syncbuf.later1(self, _dosubmodules)
  1412. def AddCopyFile(self, src, dest, absdest):
  1413. # dest should already be an absolute path, but src is project relative
  1414. # make src an absolute path
  1415. abssrc = os.path.join(self.worktree, src)
  1416. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1417. def AddLinkFile(self, src, dest, absdest):
  1418. # dest should already be an absolute path, but src is project relative
  1419. # make src relative path to dest
  1420. absdestdir = os.path.dirname(absdest)
  1421. relsrc = os.path.relpath(os.path.join(self.worktree, src), absdestdir)
  1422. self.linkfiles.append(_LinkFile(self.worktree, src, dest, relsrc, absdest))
  1423. def AddAnnotation(self, name, value, keep):
  1424. self.annotations.append(_Annotation(name, value, keep))
  1425. def DownloadPatchSet(self, change_id, patch_id):
  1426. """Download a single patch set of a single change to FETCH_HEAD.
  1427. """
  1428. remote = self.GetRemote(self.remote.name)
  1429. cmd = ['fetch', remote.name]
  1430. cmd.append('refs/changes/%2.2d/%d/%d'
  1431. % (change_id % 100, change_id, patch_id))
  1432. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1433. return None
  1434. return DownloadedChange(self,
  1435. self.GetRevisionId(),
  1436. change_id,
  1437. patch_id,
  1438. self.bare_git.rev_parse('FETCH_HEAD'))
  1439. # Branch Management ##
  1440. def StartBranch(self, name, branch_merge='', revision=None):
  1441. """Create a new branch off the manifest's revision.
  1442. """
  1443. if not branch_merge:
  1444. branch_merge = self.revisionExpr
  1445. head = self.work_git.GetHead()
  1446. if head == (R_HEADS + name):
  1447. return True
  1448. all_refs = self.bare_ref.all
  1449. if R_HEADS + name in all_refs:
  1450. return GitCommand(self,
  1451. ['checkout', name, '--'],
  1452. capture_stdout=True,
  1453. capture_stderr=True).Wait() == 0
  1454. branch = self.GetBranch(name)
  1455. branch.remote = self.GetRemote(self.remote.name)
  1456. branch.merge = branch_merge
  1457. if not branch.merge.startswith('refs/') and not ID_RE.match(branch_merge):
  1458. branch.merge = R_HEADS + branch_merge
  1459. if revision is None:
  1460. revid = self.GetRevisionId(all_refs)
  1461. else:
  1462. revid = self.work_git.rev_parse(revision)
  1463. if head.startswith(R_HEADS):
  1464. try:
  1465. head = all_refs[head]
  1466. except KeyError:
  1467. head = None
  1468. if revid and head and revid == head:
  1469. ref = os.path.join(self.gitdir, R_HEADS + name)
  1470. try:
  1471. os.makedirs(os.path.dirname(ref))
  1472. except OSError:
  1473. pass
  1474. _lwrite(ref, '%s\n' % revid)
  1475. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1476. 'ref: %s%s\n' % (R_HEADS, name))
  1477. branch.Save()
  1478. return True
  1479. if GitCommand(self,
  1480. ['checkout', '-b', branch.name, revid],
  1481. capture_stdout=True,
  1482. capture_stderr=True).Wait() == 0:
  1483. branch.Save()
  1484. return True
  1485. return False
  1486. def CheckoutBranch(self, name):
  1487. """Checkout a local topic branch.
  1488. Args:
  1489. name: The name of the branch to checkout.
  1490. Returns:
  1491. True if the checkout succeeded; False if it didn't; None if the branch
  1492. didn't exist.
  1493. """
  1494. rev = R_HEADS + name
  1495. head = self.work_git.GetHead()
  1496. if head == rev:
  1497. # Already on the branch
  1498. #
  1499. return True
  1500. all_refs = self.bare_ref.all
  1501. try:
  1502. revid = all_refs[rev]
  1503. except KeyError:
  1504. # Branch does not exist in this project
  1505. #
  1506. return None
  1507. if head.startswith(R_HEADS):
  1508. try:
  1509. head = all_refs[head]
  1510. except KeyError:
  1511. head = None
  1512. if head == revid:
  1513. # Same revision; just update HEAD to point to the new
  1514. # target branch, but otherwise take no other action.
  1515. #
  1516. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1517. 'ref: %s%s\n' % (R_HEADS, name))
  1518. return True
  1519. return GitCommand(self,
  1520. ['checkout', name, '--'],
  1521. capture_stdout=True,
  1522. capture_stderr=True).Wait() == 0
  1523. def AbandonBranch(self, name):
  1524. """Destroy a local topic branch.
  1525. Args:
  1526. name: The name of the branch to abandon.
  1527. Returns:
  1528. True if the abandon succeeded; False if it didn't; None if the branch
  1529. didn't exist.
  1530. """
  1531. rev = R_HEADS + name
  1532. all_refs = self.bare_ref.all
  1533. if rev not in all_refs:
  1534. # Doesn't exist
  1535. return None
  1536. head = self.work_git.GetHead()
  1537. if head == rev:
  1538. # We can't destroy the branch while we are sitting
  1539. # on it. Switch to a detached HEAD.
  1540. #
  1541. head = all_refs[head]
  1542. revid = self.GetRevisionId(all_refs)
  1543. if head == revid:
  1544. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1545. '%s\n' % revid)
  1546. else:
  1547. self._Checkout(revid, quiet=True)
  1548. return GitCommand(self,
  1549. ['branch', '-D', name],
  1550. capture_stdout=True,
  1551. capture_stderr=True).Wait() == 0
  1552. def PruneHeads(self):
  1553. """Prune any topic branches already merged into upstream.
  1554. """
  1555. cb = self.CurrentBranch
  1556. kill = []
  1557. left = self._allrefs
  1558. for name in left.keys():
  1559. if name.startswith(R_HEADS):
  1560. name = name[len(R_HEADS):]
  1561. if cb is None or name != cb:
  1562. kill.append(name)
  1563. rev = self.GetRevisionId(left)
  1564. if cb is not None \
  1565. and not self._revlist(HEAD + '...' + rev) \
  1566. and not self.IsDirty(consider_untracked=False):
  1567. self.work_git.DetachHead(HEAD)
  1568. kill.append(cb)
  1569. if kill:
  1570. old = self.bare_git.GetHead()
  1571. try:
  1572. self.bare_git.DetachHead(rev)
  1573. b = ['branch', '-d']
  1574. b.extend(kill)
  1575. b = GitCommand(self, b, bare=True,
  1576. capture_stdout=True,
  1577. capture_stderr=True)
  1578. b.Wait()
  1579. finally:
  1580. if ID_RE.match(old):
  1581. self.bare_git.DetachHead(old)
  1582. else:
  1583. self.bare_git.SetHead(old)
  1584. left = self._allrefs
  1585. for branch in kill:
  1586. if (R_HEADS + branch) not in left:
  1587. self.CleanPublishedCache()
  1588. break
  1589. if cb and cb not in kill:
  1590. kill.append(cb)
  1591. kill.sort()
  1592. kept = []
  1593. for branch in kill:
  1594. if R_HEADS + branch in left:
  1595. branch = self.GetBranch(branch)
  1596. base = branch.LocalMerge
  1597. if not base:
  1598. base = rev
  1599. kept.append(ReviewableBranch(self, branch, base))
  1600. return kept
  1601. # Submodule Management ##
  1602. def GetRegisteredSubprojects(self):
  1603. result = []
  1604. def rec(subprojects):
  1605. if not subprojects:
  1606. return
  1607. result.extend(subprojects)
  1608. for p in subprojects:
  1609. rec(p.subprojects)
  1610. rec(self.subprojects)
  1611. return result
  1612. def _GetSubmodules(self):
  1613. # Unfortunately we cannot call `git submodule status --recursive` here
  1614. # because the working tree might not exist yet, and it cannot be used
  1615. # without a working tree in its current implementation.
  1616. def get_submodules(gitdir, rev):
  1617. # Parse .gitmodules for submodule sub_paths and sub_urls
  1618. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1619. if not sub_paths:
  1620. return []
  1621. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1622. # revision of submodule repository
  1623. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1624. submodules = []
  1625. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1626. try:
  1627. sub_rev = sub_revs[sub_path]
  1628. except KeyError:
  1629. # Ignore non-exist submodules
  1630. continue
  1631. submodules.append((sub_rev, sub_path, sub_url))
  1632. return submodules
  1633. re_path = re.compile(r'^submodule\.(.+)\.path=(.*)$')
  1634. re_url = re.compile(r'^submodule\.(.+)\.url=(.*)$')
  1635. def parse_gitmodules(gitdir, rev):
  1636. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1637. try:
  1638. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1639. bare=True, gitdir=gitdir)
  1640. except GitError:
  1641. return [], []
  1642. if p.Wait() != 0:
  1643. return [], []
  1644. gitmodules_lines = []
  1645. fd, temp_gitmodules_path = tempfile.mkstemp()
  1646. try:
  1647. os.write(fd, p.stdout)
  1648. os.close(fd)
  1649. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1650. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1651. bare=True, gitdir=gitdir)
  1652. if p.Wait() != 0:
  1653. return [], []
  1654. gitmodules_lines = p.stdout.split('\n')
  1655. except GitError:
  1656. return [], []
  1657. finally:
  1658. platform_utils.remove(temp_gitmodules_path)
  1659. names = set()
  1660. paths = {}
  1661. urls = {}
  1662. for line in gitmodules_lines:
  1663. if not line:
  1664. continue
  1665. m = re_path.match(line)
  1666. if m:
  1667. names.add(m.group(1))
  1668. paths[m.group(1)] = m.group(2)
  1669. continue
  1670. m = re_url.match(line)
  1671. if m:
  1672. names.add(m.group(1))
  1673. urls[m.group(1)] = m.group(2)
  1674. continue
  1675. names = sorted(names)
  1676. return ([paths.get(name, '') for name in names],
  1677. [urls.get(name, '') for name in names])
  1678. def git_ls_tree(gitdir, rev, paths):
  1679. cmd = ['ls-tree', rev, '--']
  1680. cmd.extend(paths)
  1681. try:
  1682. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1683. bare=True, gitdir=gitdir)
  1684. except GitError:
  1685. return []
  1686. if p.Wait() != 0:
  1687. return []
  1688. objects = {}
  1689. for line in p.stdout.split('\n'):
  1690. if not line.strip():
  1691. continue
  1692. object_rev, object_path = line.split()[2:4]
  1693. objects[object_path] = object_rev
  1694. return objects
  1695. try:
  1696. rev = self.GetRevisionId()
  1697. except GitError:
  1698. return []
  1699. return get_submodules(self.gitdir, rev)
  1700. def GetDerivedSubprojects(self):
  1701. result = []
  1702. if not self.Exists:
  1703. # If git repo does not exist yet, querying its submodules will
  1704. # mess up its states; so return here.
  1705. return result
  1706. for rev, path, url in self._GetSubmodules():
  1707. name = self.manifest.GetSubprojectName(self, path)
  1708. relpath, worktree, gitdir, objdir = \
  1709. self.manifest.GetSubprojectPaths(self, name, path)
  1710. project = self.manifest.paths.get(relpath)
  1711. if project:
  1712. result.extend(project.GetDerivedSubprojects())
  1713. continue
  1714. if url.startswith('..'):
  1715. url = urllib.parse.urljoin("%s/" % self.remote.url, url)
  1716. remote = RemoteSpec(self.remote.name,
  1717. url=url,
  1718. pushUrl=self.remote.pushUrl,
  1719. review=self.remote.review,
  1720. revision=self.remote.revision)
  1721. subproject = Project(manifest=self.manifest,
  1722. name=name,
  1723. remote=remote,
  1724. gitdir=gitdir,
  1725. objdir=objdir,
  1726. worktree=worktree,
  1727. relpath=relpath,
  1728. revisionExpr=rev,
  1729. revisionId=rev,
  1730. rebase=self.rebase,
  1731. groups=self.groups,
  1732. sync_c=self.sync_c,
  1733. sync_s=self.sync_s,
  1734. sync_tags=self.sync_tags,
  1735. parent=self,
  1736. is_derived=True)
  1737. result.append(subproject)
  1738. result.extend(subproject.GetDerivedSubprojects())
  1739. return result
  1740. # Direct Git Commands ##
  1741. def _CheckForImmutableRevision(self):
  1742. try:
  1743. # if revision (sha or tag) is not present then following function
  1744. # throws an error.
  1745. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1746. return True
  1747. except GitError:
  1748. # There is no such persistent revision. We have to fetch it.
  1749. return False
  1750. def _FetchArchive(self, tarpath, cwd=None):
  1751. cmd = ['archive', '-v', '-o', tarpath]
  1752. cmd.append('--remote=%s' % self.remote.url)
  1753. cmd.append('--prefix=%s/' % self.relpath)
  1754. cmd.append(self.revisionExpr)
  1755. command = GitCommand(self, cmd, cwd=cwd,
  1756. capture_stdout=True,
  1757. capture_stderr=True)
  1758. if command.Wait() != 0:
  1759. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1760. def _RemoteFetch(self, name=None,
  1761. current_branch_only=False,
  1762. initial=False,
  1763. quiet=False,
  1764. alt_dir=None,
  1765. no_tags=False,
  1766. prune=False,
  1767. depth=None,
  1768. submodules=False,
  1769. force_sync=False,
  1770. clone_filter=None):
  1771. is_sha1 = False
  1772. tag_name = None
  1773. # The depth should not be used when fetching to a mirror because
  1774. # it will result in a shallow repository that cannot be cloned or
  1775. # fetched from.
  1776. # The repo project should also never be synced with partial depth.
  1777. if self.manifest.IsMirror or self.relpath == '.repo/repo':
  1778. depth = None
  1779. if depth:
  1780. current_branch_only = True
  1781. if ID_RE.match(self.revisionExpr) is not None:
  1782. is_sha1 = True
  1783. if current_branch_only:
  1784. if self.revisionExpr.startswith(R_TAGS):
  1785. # this is a tag and its sha1 value should never change
  1786. tag_name = self.revisionExpr[len(R_TAGS):]
  1787. if is_sha1 or tag_name is not None:
  1788. if self._CheckForImmutableRevision():
  1789. if not quiet:
  1790. print('Skipped fetching project %s (already have persistent ref)'
  1791. % self.name)
  1792. return True
  1793. if is_sha1 and not depth:
  1794. # When syncing a specific commit and --depth is not set:
  1795. # * if upstream is explicitly specified and is not a sha1, fetch only
  1796. # upstream as users expect only upstream to be fetch.
  1797. # Note: The commit might not be in upstream in which case the sync
  1798. # will fail.
  1799. # * otherwise, fetch all branches to make sure we end up with the
  1800. # specific commit.
  1801. if self.upstream:
  1802. current_branch_only = not ID_RE.match(self.upstream)
  1803. else:
  1804. current_branch_only = False
  1805. if not name:
  1806. name = self.remote.name
  1807. ssh_proxy = False
  1808. remote = self.GetRemote(name)
  1809. if remote.PreConnectFetch():
  1810. ssh_proxy = True
  1811. if initial:
  1812. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1813. ref_dir = os.path.dirname(alt_dir)
  1814. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1815. remote = self.GetRemote(name)
  1816. all_refs = self.bare_ref.all
  1817. ids = set(all_refs.values())
  1818. tmp = set()
  1819. for r, ref_id in GitRefs(ref_dir).all.items():
  1820. if r not in all_refs:
  1821. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1822. all_refs[r] = ref_id
  1823. ids.add(ref_id)
  1824. continue
  1825. if ref_id in ids:
  1826. continue
  1827. r = 'refs/_alt/%s' % ref_id
  1828. all_refs[r] = ref_id
  1829. ids.add(ref_id)
  1830. tmp.add(r)
  1831. tmp_packed_lines = []
  1832. old_packed_lines = []
  1833. for r in sorted(all_refs):
  1834. line = '%s %s\n' % (all_refs[r], r)
  1835. tmp_packed_lines.append(line)
  1836. if r not in tmp:
  1837. old_packed_lines.append(line)
  1838. tmp_packed = ''.join(tmp_packed_lines)
  1839. old_packed = ''.join(old_packed_lines)
  1840. _lwrite(packed_refs, tmp_packed)
  1841. else:
  1842. alt_dir = None
  1843. cmd = ['fetch']
  1844. if clone_filter:
  1845. git_require((2, 19, 0), fail=True, msg='partial clones')
  1846. cmd.append('--filter=%s' % clone_filter)
  1847. self.config.SetString('extensions.partialclone', self.remote.name)
  1848. if depth:
  1849. cmd.append('--depth=%s' % depth)
  1850. else:
  1851. # If this repo has shallow objects, then we don't know which refs have
  1852. # shallow objects or not. Tell git to unshallow all fetched refs. Don't
  1853. # do this with projects that don't have shallow objects, since it is less
  1854. # efficient.
  1855. if os.path.exists(os.path.join(self.gitdir, 'shallow')):
  1856. cmd.append('--depth=2147483647')
  1857. if quiet:
  1858. cmd.append('--quiet')
  1859. if not self.worktree:
  1860. cmd.append('--update-head-ok')
  1861. cmd.append(name)
  1862. # If using depth then we should not get all the tags since they may
  1863. # be outside of the depth.
  1864. if no_tags or depth:
  1865. cmd.append('--no-tags')
  1866. else:
  1867. cmd.append('--tags')
  1868. if force_sync:
  1869. cmd.append('--force')
  1870. if prune:
  1871. cmd.append('--prune')
  1872. if submodules:
  1873. cmd.append('--recurse-submodules=on-demand')
  1874. spec = []
  1875. if not current_branch_only:
  1876. # Fetch whole repo
  1877. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1878. if not (no_tags or depth):
  1879. spec.append(str((u'+refs/tags/*:') + remote.ToLocal('refs/tags/*')))
  1880. elif tag_name is not None:
  1881. spec.append('tag')
  1882. spec.append(tag_name)
  1883. if not self.manifest.IsMirror:
  1884. branch = self.revisionExpr
  1885. if is_sha1 and depth and git_require((1, 8, 3)):
  1886. # Shallow checkout of a specific commit, fetch from that commit and not
  1887. # the heads only as the commit might be deeper in the history.
  1888. spec.append(branch)
  1889. else:
  1890. if is_sha1:
  1891. branch = self.upstream
  1892. if branch is not None and branch.strip():
  1893. if not branch.startswith('refs/'):
  1894. branch = R_HEADS + branch
  1895. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1896. cmd.extend(spec)
  1897. ok = False
  1898. for _i in range(2):
  1899. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
  1900. ret = gitcmd.Wait()
  1901. if ret == 0:
  1902. ok = True
  1903. break
  1904. # If needed, run the 'git remote prune' the first time through the loop
  1905. elif (not _i and
  1906. "error:" in gitcmd.stderr and
  1907. "git remote prune" in gitcmd.stderr):
  1908. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1909. ssh_proxy=ssh_proxy)
  1910. ret = prunecmd.Wait()
  1911. if ret:
  1912. break
  1913. continue
  1914. elif current_branch_only and is_sha1 and ret == 128:
  1915. # Exit code 128 means "couldn't find the ref you asked for"; if we're
  1916. # in sha1 mode, we just tried sync'ing from the upstream field; it
  1917. # doesn't exist, thus abort the optimization attempt and do a full sync.
  1918. break
  1919. elif ret < 0:
  1920. # Git died with a signal, exit immediately
  1921. break
  1922. time.sleep(random.randint(30, 45))
  1923. if initial:
  1924. if alt_dir:
  1925. if old_packed != '':
  1926. _lwrite(packed_refs, old_packed)
  1927. else:
  1928. platform_utils.remove(packed_refs)
  1929. self.bare_git.pack_refs('--all', '--prune')
  1930. if is_sha1 and current_branch_only:
  1931. # We just synced the upstream given branch; verify we
  1932. # got what we wanted, else trigger a second run of all
  1933. # refs.
  1934. if not self._CheckForImmutableRevision():
  1935. if current_branch_only and depth:
  1936. # Sync the current branch only with depth set to None
  1937. return self._RemoteFetch(name=name,
  1938. current_branch_only=current_branch_only,
  1939. initial=False, quiet=quiet, alt_dir=alt_dir,
  1940. depth=None, clone_filter=clone_filter)
  1941. else:
  1942. # Avoid infinite recursion: sync all branches with depth set to None
  1943. return self._RemoteFetch(name=name, current_branch_only=False,
  1944. initial=False, quiet=quiet, alt_dir=alt_dir,
  1945. depth=None, clone_filter=clone_filter)
  1946. return ok
  1947. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1948. if initial and \
  1949. (self.manifest.manifestProject.config.GetString('repo.depth') or
  1950. self.clone_depth):
  1951. return False
  1952. remote = self.GetRemote(self.remote.name)
  1953. bundle_url = remote.url + '/clone.bundle'
  1954. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1955. if GetSchemeFromUrl(bundle_url) not in ('http', 'https',
  1956. 'persistent-http',
  1957. 'persistent-https'):
  1958. return False
  1959. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1960. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1961. exist_dst = os.path.exists(bundle_dst)
  1962. exist_tmp = os.path.exists(bundle_tmp)
  1963. if not initial and not exist_dst and not exist_tmp:
  1964. return False
  1965. if not exist_dst:
  1966. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1967. if not exist_dst:
  1968. return False
  1969. cmd = ['fetch']
  1970. if quiet:
  1971. cmd.append('--quiet')
  1972. if not self.worktree:
  1973. cmd.append('--update-head-ok')
  1974. cmd.append(bundle_dst)
  1975. for f in remote.fetch:
  1976. cmd.append(str(f))
  1977. cmd.append('+refs/tags/*:refs/tags/*')
  1978. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1979. if os.path.exists(bundle_dst):
  1980. platform_utils.remove(bundle_dst)
  1981. if os.path.exists(bundle_tmp):
  1982. platform_utils.remove(bundle_tmp)
  1983. return ok
  1984. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1985. if os.path.exists(dstPath):
  1986. platform_utils.remove(dstPath)
  1987. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1988. if quiet:
  1989. cmd += ['--silent']
  1990. if os.path.exists(tmpPath):
  1991. size = os.stat(tmpPath).st_size
  1992. if size >= 1024:
  1993. cmd += ['--continue-at', '%d' % (size,)]
  1994. else:
  1995. platform_utils.remove(tmpPath)
  1996. with GetUrlCookieFile(srcUrl, quiet) as (cookiefile, proxy):
  1997. if cookiefile:
  1998. cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
  1999. if proxy:
  2000. cmd += ['--proxy', proxy]
  2001. elif 'http_proxy' in os.environ and 'darwin' == sys.platform:
  2002. cmd += ['--proxy', os.environ['http_proxy']]
  2003. if srcUrl.startswith('persistent-https'):
  2004. srcUrl = 'http' + srcUrl[len('persistent-https'):]
  2005. elif srcUrl.startswith('persistent-http'):
  2006. srcUrl = 'http' + srcUrl[len('persistent-http'):]
  2007. cmd += [srcUrl]
  2008. if IsTrace():
  2009. Trace('%s', ' '.join(cmd))
  2010. try:
  2011. proc = subprocess.Popen(cmd)
  2012. except OSError:
  2013. return False
  2014. curlret = proc.wait()
  2015. if curlret == 22:
  2016. # From curl man page:
  2017. # 22: HTTP page not retrieved. The requested url was not found or
  2018. # returned another error with the HTTP error code being 400 or above.
  2019. # This return code only appears if -f, --fail is used.
  2020. if not quiet:
  2021. print("Server does not provide clone.bundle; ignoring.",
  2022. file=sys.stderr)
  2023. return False
  2024. if os.path.exists(tmpPath):
  2025. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  2026. platform_utils.rename(tmpPath, dstPath)
  2027. return True
  2028. else:
  2029. platform_utils.remove(tmpPath)
  2030. return False
  2031. else:
  2032. return False
  2033. def _IsValidBundle(self, path, quiet):
  2034. try:
  2035. with open(path, 'rb') as f:
  2036. if f.read(16) == b'# v2 git bundle\n':
  2037. return True
  2038. else:
  2039. if not quiet:
  2040. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  2041. return False
  2042. except OSError:
  2043. return False
  2044. def _Checkout(self, rev, quiet=False):
  2045. cmd = ['checkout']
  2046. if quiet:
  2047. cmd.append('-q')
  2048. cmd.append(rev)
  2049. cmd.append('--')
  2050. if GitCommand(self, cmd).Wait() != 0:
  2051. if self._allrefs:
  2052. raise GitError('%s checkout %s ' % (self.name, rev))
  2053. def _CherryPick(self, rev):
  2054. cmd = ['cherry-pick']
  2055. cmd.append(rev)
  2056. cmd.append('--')
  2057. if GitCommand(self, cmd).Wait() != 0:
  2058. if self._allrefs:
  2059. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  2060. def _LsRemote(self, refs):
  2061. cmd = ['ls-remote', self.remote.name, refs]
  2062. p = GitCommand(self, cmd, capture_stdout=True)
  2063. if p.Wait() == 0:
  2064. return p.stdout
  2065. return None
  2066. def _Revert(self, rev):
  2067. cmd = ['revert']
  2068. cmd.append('--no-edit')
  2069. cmd.append(rev)
  2070. cmd.append('--')
  2071. if GitCommand(self, cmd).Wait() != 0:
  2072. if self._allrefs:
  2073. raise GitError('%s revert %s ' % (self.name, rev))
  2074. def _ResetHard(self, rev, quiet=True):
  2075. cmd = ['reset', '--hard']
  2076. if quiet:
  2077. cmd.append('-q')
  2078. cmd.append(rev)
  2079. if GitCommand(self, cmd).Wait() != 0:
  2080. raise GitError('%s reset --hard %s ' % (self.name, rev))
  2081. def _SyncSubmodules(self, quiet=True):
  2082. cmd = ['submodule', 'update', '--init', '--recursive']
  2083. if quiet:
  2084. cmd.append('-q')
  2085. if GitCommand(self, cmd).Wait() != 0:
  2086. raise GitError('%s submodule update --init --recursive %s ' % self.name)
  2087. def _Rebase(self, upstream, onto=None):
  2088. cmd = ['rebase']
  2089. if onto is not None:
  2090. cmd.extend(['--onto', onto])
  2091. cmd.append(upstream)
  2092. if GitCommand(self, cmd).Wait() != 0:
  2093. raise GitError('%s rebase %s ' % (self.name, upstream))
  2094. def _FastForward(self, head, ffonly=False):
  2095. cmd = ['merge', head]
  2096. if ffonly:
  2097. cmd.append("--ff-only")
  2098. if GitCommand(self, cmd).Wait() != 0:
  2099. raise GitError('%s merge %s ' % (self.name, head))
  2100. def _InitGitDir(self, mirror_git=None, force_sync=False):
  2101. init_git_dir = not os.path.exists(self.gitdir)
  2102. init_obj_dir = not os.path.exists(self.objdir)
  2103. try:
  2104. # Initialize the bare repository, which contains all of the objects.
  2105. if init_obj_dir:
  2106. os.makedirs(self.objdir)
  2107. self.bare_objdir.init()
  2108. # If we have a separate directory to hold refs, initialize it as well.
  2109. if self.objdir != self.gitdir:
  2110. if init_git_dir:
  2111. os.makedirs(self.gitdir)
  2112. if init_obj_dir or init_git_dir:
  2113. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  2114. copy_all=True)
  2115. try:
  2116. self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
  2117. except GitError as e:
  2118. if force_sync:
  2119. print("Retrying clone after deleting %s" %
  2120. self.gitdir, file=sys.stderr)
  2121. try:
  2122. platform_utils.rmtree(platform_utils.realpath(self.gitdir))
  2123. if self.worktree and os.path.exists(platform_utils.realpath
  2124. (self.worktree)):
  2125. platform_utils.rmtree(platform_utils.realpath(self.worktree))
  2126. return self._InitGitDir(mirror_git=mirror_git, force_sync=False)
  2127. except:
  2128. raise e
  2129. raise e
  2130. if init_git_dir:
  2131. mp = self.manifest.manifestProject
  2132. ref_dir = mp.config.GetString('repo.reference') or ''
  2133. if ref_dir or mirror_git:
  2134. if not mirror_git:
  2135. mirror_git = os.path.join(ref_dir, self.name + '.git')
  2136. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  2137. self.relpath + '.git')
  2138. if os.path.exists(mirror_git):
  2139. ref_dir = mirror_git
  2140. elif os.path.exists(repo_git):
  2141. ref_dir = repo_git
  2142. else:
  2143. ref_dir = None
  2144. if ref_dir:
  2145. if not os.path.isabs(ref_dir):
  2146. # The alternate directory is relative to the object database.
  2147. ref_dir = os.path.relpath(ref_dir,
  2148. os.path.join(self.objdir, 'objects'))
  2149. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  2150. os.path.join(ref_dir, 'objects') + '\n')
  2151. self._UpdateHooks()
  2152. m = self.manifest.manifestProject.config
  2153. for key in ['user.name', 'user.email']:
  2154. if m.Has(key, include_defaults=False):
  2155. self.config.SetString(key, m.GetString(key))
  2156. self.config.SetString('filter.lfs.smudge', 'git-lfs smudge --skip -- %f')
  2157. self.config.SetString('filter.lfs.process', 'git-lfs filter-process --skip')
  2158. if self.manifest.IsMirror:
  2159. self.config.SetString('core.bare', 'true')
  2160. else:
  2161. self.config.SetString('core.bare', None)
  2162. except Exception:
  2163. if init_obj_dir and os.path.exists(self.objdir):
  2164. platform_utils.rmtree(self.objdir)
  2165. if init_git_dir and os.path.exists(self.gitdir):
  2166. platform_utils.rmtree(self.gitdir)
  2167. raise
  2168. def _UpdateHooks(self):
  2169. if os.path.exists(self.gitdir):
  2170. self._InitHooks()
  2171. def _InitHooks(self):
  2172. hooks = platform_utils.realpath(self._gitdir_path('hooks'))
  2173. if not os.path.exists(hooks):
  2174. os.makedirs(hooks)
  2175. for stock_hook in _ProjectHooks():
  2176. name = os.path.basename(stock_hook)
  2177. if name in ('commit-msg',) and not self.remote.review \
  2178. and self is not self.manifest.manifestProject:
  2179. # Don't install a Gerrit Code Review hook if this
  2180. # project does not appear to use it for reviews.
  2181. #
  2182. # Since the manifest project is one of those, but also
  2183. # managed through gerrit, it's excluded
  2184. continue
  2185. dst = os.path.join(hooks, name)
  2186. if platform_utils.islink(dst):
  2187. continue
  2188. if os.path.exists(dst):
  2189. if filecmp.cmp(stock_hook, dst, shallow=False):
  2190. platform_utils.remove(dst)
  2191. else:
  2192. _warn("%s: Not replacing locally modified %s hook",
  2193. self.relpath, name)
  2194. continue
  2195. try:
  2196. platform_utils.symlink(
  2197. os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  2198. except OSError as e:
  2199. if e.errno == errno.EPERM:
  2200. raise GitError(self._get_symlink_error_message())
  2201. else:
  2202. raise
  2203. def _InitRemote(self):
  2204. if self.remote.url:
  2205. remote = self.GetRemote(self.remote.name)
  2206. remote.url = self.remote.url
  2207. remote.pushUrl = self.remote.pushUrl
  2208. remote.review = self.remote.review
  2209. remote.projectname = self.name
  2210. if self.worktree:
  2211. remote.ResetFetch(mirror=False)
  2212. else:
  2213. remote.ResetFetch(mirror=True)
  2214. remote.Save()
  2215. def _InitMRef(self):
  2216. if self.manifest.branch:
  2217. self._InitAnyMRef(R_M + self.manifest.branch)
  2218. def _InitMirrorHead(self):
  2219. self._InitAnyMRef(HEAD)
  2220. def _InitAnyMRef(self, ref):
  2221. cur = self.bare_ref.symref(ref)
  2222. if self.revisionId:
  2223. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  2224. msg = 'manifest set to %s' % self.revisionId
  2225. dst = self.revisionId + '^0'
  2226. self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
  2227. else:
  2228. remote = self.GetRemote(self.remote.name)
  2229. dst = remote.ToLocal(self.revisionExpr)
  2230. if cur != dst:
  2231. msg = 'manifest set to %s' % self.revisionExpr
  2232. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  2233. def _CheckDirReference(self, srcdir, destdir, share_refs):
  2234. symlink_files = self.shareable_files[:]
  2235. symlink_dirs = self.shareable_dirs[:]
  2236. if share_refs:
  2237. symlink_files += self.working_tree_files
  2238. symlink_dirs += self.working_tree_dirs
  2239. to_symlink = symlink_files + symlink_dirs
  2240. for name in set(to_symlink):
  2241. dst = platform_utils.realpath(os.path.join(destdir, name))
  2242. if os.path.lexists(dst):
  2243. src = platform_utils.realpath(os.path.join(srcdir, name))
  2244. # Fail if the links are pointing to the wrong place
  2245. if src != dst:
  2246. _error('%s is different in %s vs %s', name, destdir, srcdir)
  2247. raise GitError('--force-sync not enabled; cannot overwrite a local '
  2248. 'work tree. If you\'re comfortable with the '
  2249. 'possibility of losing the work tree\'s git metadata,'
  2250. ' use `repo sync --force-sync {0}` to '
  2251. 'proceed.'.format(self.relpath))
  2252. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  2253. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  2254. Args:
  2255. gitdir: The bare git repository. Must already be initialized.
  2256. dotgit: The repository you would like to initialize.
  2257. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  2258. Only one work tree can store refs under a given |gitdir|.
  2259. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  2260. This saves you the effort of initializing |dotgit| yourself.
  2261. """
  2262. symlink_files = self.shareable_files[:]
  2263. symlink_dirs = self.shareable_dirs[:]
  2264. if share_refs:
  2265. symlink_files += self.working_tree_files
  2266. symlink_dirs += self.working_tree_dirs
  2267. to_symlink = symlink_files + symlink_dirs
  2268. to_copy = []
  2269. if copy_all:
  2270. to_copy = platform_utils.listdir(gitdir)
  2271. dotgit = platform_utils.realpath(dotgit)
  2272. for name in set(to_copy).union(to_symlink):
  2273. try:
  2274. src = platform_utils.realpath(os.path.join(gitdir, name))
  2275. dst = os.path.join(dotgit, name)
  2276. if os.path.lexists(dst):
  2277. continue
  2278. # If the source dir doesn't exist, create an empty dir.
  2279. if name in symlink_dirs and not os.path.lexists(src):
  2280. os.makedirs(src)
  2281. if name in to_symlink:
  2282. platform_utils.symlink(
  2283. os.path.relpath(src, os.path.dirname(dst)), dst)
  2284. elif copy_all and not platform_utils.islink(dst):
  2285. if platform_utils.isdir(src):
  2286. shutil.copytree(src, dst)
  2287. elif os.path.isfile(src):
  2288. shutil.copy(src, dst)
  2289. # If the source file doesn't exist, ensure the destination
  2290. # file doesn't either.
  2291. if name in symlink_files and not os.path.lexists(src):
  2292. try:
  2293. platform_utils.remove(dst)
  2294. except OSError:
  2295. pass
  2296. except OSError as e:
  2297. if e.errno == errno.EPERM:
  2298. raise DownloadError(self._get_symlink_error_message())
  2299. else:
  2300. raise
  2301. def _InitWorkTree(self, force_sync=False, submodules=False):
  2302. dotgit = os.path.join(self.worktree, '.git')
  2303. init_dotgit = not os.path.exists(dotgit)
  2304. try:
  2305. if init_dotgit:
  2306. os.makedirs(dotgit)
  2307. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  2308. copy_all=False)
  2309. try:
  2310. self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
  2311. except GitError as e:
  2312. if force_sync:
  2313. try:
  2314. platform_utils.rmtree(dotgit)
  2315. return self._InitWorkTree(force_sync=False, submodules=submodules)
  2316. except:
  2317. raise e
  2318. raise e
  2319. if init_dotgit:
  2320. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  2321. cmd = ['read-tree', '--reset', '-u']
  2322. cmd.append('-v')
  2323. cmd.append(HEAD)
  2324. if GitCommand(self, cmd).Wait() != 0:
  2325. raise GitError("cannot initialize work tree for " + self.name)
  2326. if submodules:
  2327. self._SyncSubmodules(quiet=True)
  2328. self._CopyAndLinkFiles()
  2329. except Exception:
  2330. if init_dotgit:
  2331. platform_utils.rmtree(dotgit)
  2332. raise
  2333. def _get_symlink_error_message(self):
  2334. if platform_utils.isWindows():
  2335. return ('Unable to create symbolic link. Please re-run the command as '
  2336. 'Administrator, or see '
  2337. 'https://github.com/git-for-windows/git/wiki/Symbolic-Links '
  2338. 'for other options.')
  2339. return 'filesystem must support symlinks'
  2340. def _gitdir_path(self, path):
  2341. return platform_utils.realpath(os.path.join(self.gitdir, path))
  2342. def _revlist(self, *args, **kw):
  2343. a = []
  2344. a.extend(args)
  2345. a.append('--')
  2346. return self.work_git.rev_list(*a, **kw)
  2347. @property
  2348. def _allrefs(self):
  2349. return self.bare_ref.all
  2350. def _getLogs(self, rev1, rev2, oneline=False, color=True, pretty_format=None):
  2351. """Get logs between two revisions of this project."""
  2352. comp = '..'
  2353. if rev1:
  2354. revs = [rev1]
  2355. if rev2:
  2356. revs.extend([comp, rev2])
  2357. cmd = ['log', ''.join(revs)]
  2358. out = DiffColoring(self.config)
  2359. if out.is_on and color:
  2360. cmd.append('--color')
  2361. if pretty_format is not None:
  2362. cmd.append('--pretty=format:%s' % pretty_format)
  2363. if oneline:
  2364. cmd.append('--oneline')
  2365. try:
  2366. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2367. if log.Wait() == 0:
  2368. return log.stdout
  2369. except GitError:
  2370. # worktree may not exist if groups changed for example. In that case,
  2371. # try in gitdir instead.
  2372. if not os.path.exists(self.worktree):
  2373. return self.bare_git.log(*cmd[1:])
  2374. else:
  2375. raise
  2376. return None
  2377. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True,
  2378. pretty_format=None):
  2379. """Get the list of logs from this revision to given revisionId"""
  2380. logs = {}
  2381. selfId = self.GetRevisionId(self._allrefs)
  2382. toId = toProject.GetRevisionId(toProject._allrefs)
  2383. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color,
  2384. pretty_format=pretty_format)
  2385. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color,
  2386. pretty_format=pretty_format)
  2387. return logs
  2388. class _GitGetByExec(object):
  2389. def __init__(self, project, bare, gitdir):
  2390. self._project = project
  2391. self._bare = bare
  2392. self._gitdir = gitdir
  2393. def LsOthers(self):
  2394. p = GitCommand(self._project,
  2395. ['ls-files',
  2396. '-z',
  2397. '--others',
  2398. '--exclude-standard'],
  2399. bare=False,
  2400. gitdir=self._gitdir,
  2401. capture_stdout=True,
  2402. capture_stderr=True)
  2403. if p.Wait() == 0:
  2404. out = p.stdout
  2405. if out:
  2406. # Backslash is not anomalous
  2407. return out[:-1].split('\0')
  2408. return []
  2409. def DiffZ(self, name, *args):
  2410. cmd = [name]
  2411. cmd.append('-z')
  2412. cmd.append('--ignore-submodules')
  2413. cmd.extend(args)
  2414. p = GitCommand(self._project,
  2415. cmd,
  2416. gitdir=self._gitdir,
  2417. bare=False,
  2418. capture_stdout=True,
  2419. capture_stderr=True)
  2420. try:
  2421. out = p.process.stdout.read()
  2422. if not hasattr(out, 'encode'):
  2423. out = out.decode()
  2424. r = {}
  2425. if out:
  2426. out = iter(out[:-1].split('\0'))
  2427. while out:
  2428. try:
  2429. info = next(out)
  2430. path = next(out)
  2431. except StopIteration:
  2432. break
  2433. class _Info(object):
  2434. def __init__(self, path, omode, nmode, oid, nid, state):
  2435. self.path = path
  2436. self.src_path = None
  2437. self.old_mode = omode
  2438. self.new_mode = nmode
  2439. self.old_id = oid
  2440. self.new_id = nid
  2441. if len(state) == 1:
  2442. self.status = state
  2443. self.level = None
  2444. else:
  2445. self.status = state[:1]
  2446. self.level = state[1:]
  2447. while self.level.startswith('0'):
  2448. self.level = self.level[1:]
  2449. info = info[1:].split(' ')
  2450. info = _Info(path, *info)
  2451. if info.status in ('R', 'C'):
  2452. info.src_path = info.path
  2453. info.path = next(out)
  2454. r[info.path] = info
  2455. return r
  2456. finally:
  2457. p.Wait()
  2458. def GetHead(self):
  2459. if self._bare:
  2460. path = os.path.join(self._project.gitdir, HEAD)
  2461. else:
  2462. path = os.path.join(self._project.worktree, '.git', HEAD)
  2463. try:
  2464. fd = open(path)
  2465. except IOError as e:
  2466. raise NoManifestException(path, str(e))
  2467. try:
  2468. line = fd.readline()
  2469. finally:
  2470. fd.close()
  2471. try:
  2472. line = line.decode()
  2473. except AttributeError:
  2474. pass
  2475. if line.startswith('ref: '):
  2476. return line[5:-1]
  2477. return line[:-1]
  2478. def SetHead(self, ref, message=None):
  2479. cmdv = []
  2480. if message is not None:
  2481. cmdv.extend(['-m', message])
  2482. cmdv.append(HEAD)
  2483. cmdv.append(ref)
  2484. self.symbolic_ref(*cmdv)
  2485. def DetachHead(self, new, message=None):
  2486. cmdv = ['--no-deref']
  2487. if message is not None:
  2488. cmdv.extend(['-m', message])
  2489. cmdv.append(HEAD)
  2490. cmdv.append(new)
  2491. self.update_ref(*cmdv)
  2492. def UpdateRef(self, name, new, old=None,
  2493. message=None,
  2494. detach=False):
  2495. cmdv = []
  2496. if message is not None:
  2497. cmdv.extend(['-m', message])
  2498. if detach:
  2499. cmdv.append('--no-deref')
  2500. cmdv.append(name)
  2501. cmdv.append(new)
  2502. if old is not None:
  2503. cmdv.append(old)
  2504. self.update_ref(*cmdv)
  2505. def DeleteRef(self, name, old=None):
  2506. if not old:
  2507. old = self.rev_parse(name)
  2508. self.update_ref('-d', name, old)
  2509. self._project.bare_ref.deleted(name)
  2510. def rev_list(self, *args, **kw):
  2511. if 'format' in kw:
  2512. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2513. else:
  2514. cmdv = ['rev-list']
  2515. cmdv.extend(args)
  2516. p = GitCommand(self._project,
  2517. cmdv,
  2518. bare=self._bare,
  2519. gitdir=self._gitdir,
  2520. capture_stdout=True,
  2521. capture_stderr=True)
  2522. if p.Wait() != 0:
  2523. raise GitError('%s rev-list %s: %s' %
  2524. (self._project.name, str(args), p.stderr))
  2525. return p.stdout.splitlines()
  2526. def __getattr__(self, name):
  2527. """Allow arbitrary git commands using pythonic syntax.
  2528. This allows you to do things like:
  2529. git_obj.rev_parse('HEAD')
  2530. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2531. run. We'll replace the '_' with a '-' and try to run a git command.
  2532. Any other positional arguments will be passed to the git command, and the
  2533. following keyword arguments are supported:
  2534. config: An optional dict of git config options to be passed with '-c'.
  2535. Args:
  2536. name: The name of the git command to call. Any '_' characters will
  2537. be replaced with '-'.
  2538. Returns:
  2539. A callable object that will try to call git with the named command.
  2540. """
  2541. name = name.replace('_', '-')
  2542. def runner(*args, **kwargs):
  2543. cmdv = []
  2544. config = kwargs.pop('config', None)
  2545. for k in kwargs:
  2546. raise TypeError('%s() got an unexpected keyword argument %r'
  2547. % (name, k))
  2548. if config is not None:
  2549. if not git_require((1, 7, 2)):
  2550. raise ValueError('cannot set config on command line for %s()'
  2551. % name)
  2552. for k, v in config.items():
  2553. cmdv.append('-c')
  2554. cmdv.append('%s=%s' % (k, v))
  2555. cmdv.append(name)
  2556. cmdv.extend(args)
  2557. p = GitCommand(self._project,
  2558. cmdv,
  2559. bare=self._bare,
  2560. gitdir=self._gitdir,
  2561. capture_stdout=True,
  2562. capture_stderr=True)
  2563. if p.Wait() != 0:
  2564. raise GitError('%s %s: %s' %
  2565. (self._project.name, name, p.stderr))
  2566. r = p.stdout
  2567. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2568. return r[:-1]
  2569. return r
  2570. return runner
  2571. class _PriorSyncFailedError(Exception):
  2572. def __str__(self):
  2573. return 'prior sync failed; rebase still in progress'
  2574. class _DirtyError(Exception):
  2575. def __str__(self):
  2576. return 'contains uncommitted changes'
  2577. class _InfoMessage(object):
  2578. def __init__(self, project, text):
  2579. self.project = project
  2580. self.text = text
  2581. def Print(self, syncbuf):
  2582. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2583. syncbuf.out.nl()
  2584. class _Failure(object):
  2585. def __init__(self, project, why):
  2586. self.project = project
  2587. self.why = why
  2588. def Print(self, syncbuf):
  2589. syncbuf.out.fail('error: %s/: %s',
  2590. self.project.relpath,
  2591. str(self.why))
  2592. syncbuf.out.nl()
  2593. class _Later(object):
  2594. def __init__(self, project, action):
  2595. self.project = project
  2596. self.action = action
  2597. def Run(self, syncbuf):
  2598. out = syncbuf.out
  2599. out.project('project %s/', self.project.relpath)
  2600. out.nl()
  2601. try:
  2602. self.action()
  2603. out.nl()
  2604. return True
  2605. except GitError:
  2606. out.nl()
  2607. return False
  2608. class _SyncColoring(Coloring):
  2609. def __init__(self, config):
  2610. Coloring.__init__(self, config, 'reposync')
  2611. self.project = self.printer('header', attr='bold')
  2612. self.info = self.printer('info')
  2613. self.fail = self.printer('fail', fg='red')
  2614. class SyncBuffer(object):
  2615. def __init__(self, config, detach_head=False):
  2616. self._messages = []
  2617. self._failures = []
  2618. self._later_queue1 = []
  2619. self._later_queue2 = []
  2620. self.out = _SyncColoring(config)
  2621. self.out.redirect(sys.stderr)
  2622. self.detach_head = detach_head
  2623. self.clean = True
  2624. self.recent_clean = True
  2625. def info(self, project, fmt, *args):
  2626. self._messages.append(_InfoMessage(project, fmt % args))
  2627. def fail(self, project, err=None):
  2628. self._failures.append(_Failure(project, err))
  2629. self._MarkUnclean()
  2630. def later1(self, project, what):
  2631. self._later_queue1.append(_Later(project, what))
  2632. def later2(self, project, what):
  2633. self._later_queue2.append(_Later(project, what))
  2634. def Finish(self):
  2635. self._PrintMessages()
  2636. self._RunLater()
  2637. self._PrintMessages()
  2638. return self.clean
  2639. def Recently(self):
  2640. recent_clean = self.recent_clean
  2641. self.recent_clean = True
  2642. return recent_clean
  2643. def _MarkUnclean(self):
  2644. self.clean = False
  2645. self.recent_clean = False
  2646. def _RunLater(self):
  2647. for q in ['_later_queue1', '_later_queue2']:
  2648. if not self._RunQueue(q):
  2649. return
  2650. def _RunQueue(self, queue):
  2651. for m in getattr(self, queue):
  2652. if not m.Run(self):
  2653. self._MarkUnclean()
  2654. return False
  2655. setattr(self, queue, [])
  2656. return True
  2657. def _PrintMessages(self):
  2658. for m in self._messages:
  2659. m.Print(self)
  2660. for m in self._failures:
  2661. m.Print(self)
  2662. self._messages = []
  2663. self._failures = []
  2664. class MetaProject(Project):
  2665. """A special project housed under .repo.
  2666. """
  2667. def __init__(self, manifest, name, gitdir, worktree):
  2668. Project.__init__(self,
  2669. manifest=manifest,
  2670. name=name,
  2671. gitdir=gitdir,
  2672. objdir=gitdir,
  2673. worktree=worktree,
  2674. remote=RemoteSpec('origin'),
  2675. relpath='.repo/%s' % name,
  2676. revisionExpr='refs/heads/master',
  2677. revisionId=None,
  2678. groups=None)
  2679. def PreSync(self):
  2680. if self.Exists:
  2681. cb = self.CurrentBranch
  2682. if cb:
  2683. base = self.GetBranch(cb).merge
  2684. if base:
  2685. self.revisionExpr = base
  2686. self.revisionId = None
  2687. def MetaBranchSwitch(self, submodules=False):
  2688. """ Prepare MetaProject for manifest branch switch
  2689. """
  2690. # detach and delete manifest branch, allowing a new
  2691. # branch to take over
  2692. syncbuf = SyncBuffer(self.config, detach_head=True)
  2693. self.Sync_LocalHalf(syncbuf, submodules=submodules)
  2694. syncbuf.Finish()
  2695. return GitCommand(self,
  2696. ['update-ref', '-d', 'refs/heads/default'],
  2697. capture_stdout=True,
  2698. capture_stderr=True).Wait() == 0
  2699. @property
  2700. def LastFetch(self):
  2701. try:
  2702. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2703. return os.path.getmtime(fh)
  2704. except OSError:
  2705. return 0
  2706. @property
  2707. def HasChanges(self):
  2708. """Has the remote received new commits not yet checked out?
  2709. """
  2710. if not self.remote or not self.revisionExpr:
  2711. return False
  2712. all_refs = self.bare_ref.all
  2713. revid = self.GetRevisionId(all_refs)
  2714. head = self.work_git.GetHead()
  2715. if head.startswith(R_HEADS):
  2716. try:
  2717. head = all_refs[head]
  2718. except KeyError:
  2719. head = None
  2720. if revid == head:
  2721. return False
  2722. elif self._revlist(not_rev(HEAD), revid):
  2723. return True
  2724. return False