project.py 100 KB

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