project.py 95 KB

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