project.py 83 KB

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