project.py 81 KB

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