project.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751
  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, relsrc, absdest):
  201. self.src = src
  202. self.dest = dest
  203. self.src_rel_to_dest = relsrc
  204. self.abs_dest = absdest
  205. def _Link(self):
  206. src = self.src_rel_to_dest
  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 relative path to dest
  1167. absdestdir = os.path.dirname(absdest)
  1168. relsrc = os.path.relpath(os.path.join(self.worktree, src), absdestdir)
  1169. self.linkfiles.append(_LinkFile(src, dest, relsrc, absdest))
  1170. def AddAnnotation(self, name, value, keep):
  1171. self.annotations.append(_Annotation(name, value, keep))
  1172. def DownloadPatchSet(self, change_id, patch_id):
  1173. """Download a single patch set of a single change to FETCH_HEAD.
  1174. """
  1175. remote = self.GetRemote(self.remote.name)
  1176. cmd = ['fetch', remote.name]
  1177. cmd.append('refs/changes/%2.2d/%d/%d' \
  1178. % (change_id % 100, change_id, patch_id))
  1179. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1180. return None
  1181. return DownloadedChange(self,
  1182. self.GetRevisionId(),
  1183. change_id,
  1184. patch_id,
  1185. self.bare_git.rev_parse('FETCH_HEAD'))
  1186. ## Branch Management ##
  1187. def StartBranch(self, name):
  1188. """Create a new branch off the manifest's revision.
  1189. """
  1190. head = self.work_git.GetHead()
  1191. if head == (R_HEADS + name):
  1192. return True
  1193. all_refs = self.bare_ref.all
  1194. if R_HEADS + name in all_refs:
  1195. return GitCommand(self,
  1196. ['checkout', name, '--'],
  1197. capture_stdout=True,
  1198. capture_stderr=True).Wait() == 0
  1199. branch = self.GetBranch(name)
  1200. branch.remote = self.GetRemote(self.remote.name)
  1201. branch.merge = self.revisionExpr
  1202. if not branch.merge.startswith('refs/') and not ID_RE.match(self.revisionExpr):
  1203. branch.merge = R_HEADS + self.revisionExpr
  1204. revid = self.GetRevisionId(all_refs)
  1205. if head.startswith(R_HEADS):
  1206. try:
  1207. head = all_refs[head]
  1208. except KeyError:
  1209. head = None
  1210. if revid and head and revid == head:
  1211. ref = os.path.join(self.gitdir, R_HEADS + name)
  1212. try:
  1213. os.makedirs(os.path.dirname(ref))
  1214. except OSError:
  1215. pass
  1216. _lwrite(ref, '%s\n' % revid)
  1217. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1218. 'ref: %s%s\n' % (R_HEADS, name))
  1219. branch.Save()
  1220. return True
  1221. if GitCommand(self,
  1222. ['checkout', '-b', branch.name, revid],
  1223. capture_stdout=True,
  1224. capture_stderr=True).Wait() == 0:
  1225. branch.Save()
  1226. return True
  1227. return False
  1228. def CheckoutBranch(self, name):
  1229. """Checkout a local topic branch.
  1230. Args:
  1231. name: The name of the branch to checkout.
  1232. Returns:
  1233. True if the checkout succeeded; False if it didn't; None if the branch
  1234. didn't exist.
  1235. """
  1236. rev = R_HEADS + name
  1237. head = self.work_git.GetHead()
  1238. if head == rev:
  1239. # Already on the branch
  1240. #
  1241. return True
  1242. all_refs = self.bare_ref.all
  1243. try:
  1244. revid = all_refs[rev]
  1245. except KeyError:
  1246. # Branch does not exist in this project
  1247. #
  1248. return None
  1249. if head.startswith(R_HEADS):
  1250. try:
  1251. head = all_refs[head]
  1252. except KeyError:
  1253. head = None
  1254. if head == revid:
  1255. # Same revision; just update HEAD to point to the new
  1256. # target branch, but otherwise take no other action.
  1257. #
  1258. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1259. 'ref: %s%s\n' % (R_HEADS, name))
  1260. return True
  1261. return GitCommand(self,
  1262. ['checkout', name, '--'],
  1263. capture_stdout=True,
  1264. capture_stderr=True).Wait() == 0
  1265. def AbandonBranch(self, name):
  1266. """Destroy a local topic branch.
  1267. Args:
  1268. name: The name of the branch to abandon.
  1269. Returns:
  1270. True if the abandon succeeded; False if it didn't; None if the branch
  1271. didn't exist.
  1272. """
  1273. rev = R_HEADS + name
  1274. all_refs = self.bare_ref.all
  1275. if rev not in all_refs:
  1276. # Doesn't exist
  1277. return None
  1278. head = self.work_git.GetHead()
  1279. if head == rev:
  1280. # We can't destroy the branch while we are sitting
  1281. # on it. Switch to a detached HEAD.
  1282. #
  1283. head = all_refs[head]
  1284. revid = self.GetRevisionId(all_refs)
  1285. if head == revid:
  1286. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1287. '%s\n' % revid)
  1288. else:
  1289. self._Checkout(revid, quiet=True)
  1290. return GitCommand(self,
  1291. ['branch', '-D', name],
  1292. capture_stdout=True,
  1293. capture_stderr=True).Wait() == 0
  1294. def PruneHeads(self):
  1295. """Prune any topic branches already merged into upstream.
  1296. """
  1297. cb = self.CurrentBranch
  1298. kill = []
  1299. left = self._allrefs
  1300. for name in left.keys():
  1301. if name.startswith(R_HEADS):
  1302. name = name[len(R_HEADS):]
  1303. if cb is None or name != cb:
  1304. kill.append(name)
  1305. rev = self.GetRevisionId(left)
  1306. if cb is not None \
  1307. and not self._revlist(HEAD + '...' + rev) \
  1308. and not self.IsDirty(consider_untracked=False):
  1309. self.work_git.DetachHead(HEAD)
  1310. kill.append(cb)
  1311. if kill:
  1312. old = self.bare_git.GetHead()
  1313. if old is None:
  1314. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1315. try:
  1316. self.bare_git.DetachHead(rev)
  1317. b = ['branch', '-d']
  1318. b.extend(kill)
  1319. b = GitCommand(self, b, bare=True,
  1320. capture_stdout=True,
  1321. capture_stderr=True)
  1322. b.Wait()
  1323. finally:
  1324. self.bare_git.SetHead(old)
  1325. left = self._allrefs
  1326. for branch in kill:
  1327. if (R_HEADS + branch) not in left:
  1328. self.CleanPublishedCache()
  1329. break
  1330. if cb and cb not in kill:
  1331. kill.append(cb)
  1332. kill.sort()
  1333. kept = []
  1334. for branch in kill:
  1335. if R_HEADS + branch in left:
  1336. branch = self.GetBranch(branch)
  1337. base = branch.LocalMerge
  1338. if not base:
  1339. base = rev
  1340. kept.append(ReviewableBranch(self, branch, base))
  1341. return kept
  1342. ## Submodule Management ##
  1343. def GetRegisteredSubprojects(self):
  1344. result = []
  1345. def rec(subprojects):
  1346. if not subprojects:
  1347. return
  1348. result.extend(subprojects)
  1349. for p in subprojects:
  1350. rec(p.subprojects)
  1351. rec(self.subprojects)
  1352. return result
  1353. def _GetSubmodules(self):
  1354. # Unfortunately we cannot call `git submodule status --recursive` here
  1355. # because the working tree might not exist yet, and it cannot be used
  1356. # without a working tree in its current implementation.
  1357. def get_submodules(gitdir, rev):
  1358. # Parse .gitmodules for submodule sub_paths and sub_urls
  1359. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1360. if not sub_paths:
  1361. return []
  1362. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1363. # revision of submodule repository
  1364. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1365. submodules = []
  1366. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1367. try:
  1368. sub_rev = sub_revs[sub_path]
  1369. except KeyError:
  1370. # Ignore non-exist submodules
  1371. continue
  1372. submodules.append((sub_rev, sub_path, sub_url))
  1373. return submodules
  1374. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1375. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1376. def parse_gitmodules(gitdir, rev):
  1377. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1378. try:
  1379. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1380. bare=True, gitdir=gitdir)
  1381. except GitError:
  1382. return [], []
  1383. if p.Wait() != 0:
  1384. return [], []
  1385. gitmodules_lines = []
  1386. fd, temp_gitmodules_path = tempfile.mkstemp()
  1387. try:
  1388. os.write(fd, p.stdout)
  1389. os.close(fd)
  1390. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1391. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1392. bare=True, gitdir=gitdir)
  1393. if p.Wait() != 0:
  1394. return [], []
  1395. gitmodules_lines = p.stdout.split('\n')
  1396. except GitError:
  1397. return [], []
  1398. finally:
  1399. os.remove(temp_gitmodules_path)
  1400. names = set()
  1401. paths = {}
  1402. urls = {}
  1403. for line in gitmodules_lines:
  1404. if not line:
  1405. continue
  1406. m = re_path.match(line)
  1407. if m:
  1408. names.add(m.group(1))
  1409. paths[m.group(1)] = m.group(2)
  1410. continue
  1411. m = re_url.match(line)
  1412. if m:
  1413. names.add(m.group(1))
  1414. urls[m.group(1)] = m.group(2)
  1415. continue
  1416. names = sorted(names)
  1417. return ([paths.get(name, '') for name in names],
  1418. [urls.get(name, '') for name in names])
  1419. def git_ls_tree(gitdir, rev, paths):
  1420. cmd = ['ls-tree', rev, '--']
  1421. cmd.extend(paths)
  1422. try:
  1423. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1424. bare=True, gitdir=gitdir)
  1425. except GitError:
  1426. return []
  1427. if p.Wait() != 0:
  1428. return []
  1429. objects = {}
  1430. for line in p.stdout.split('\n'):
  1431. if not line.strip():
  1432. continue
  1433. object_rev, object_path = line.split()[2:4]
  1434. objects[object_path] = object_rev
  1435. return objects
  1436. try:
  1437. rev = self.GetRevisionId()
  1438. except GitError:
  1439. return []
  1440. return get_submodules(self.gitdir, rev)
  1441. def GetDerivedSubprojects(self):
  1442. result = []
  1443. if not self.Exists:
  1444. # If git repo does not exist yet, querying its submodules will
  1445. # mess up its states; so return here.
  1446. return result
  1447. for rev, path, url in self._GetSubmodules():
  1448. name = self.manifest.GetSubprojectName(self, path)
  1449. relpath, worktree, gitdir, objdir = \
  1450. self.manifest.GetSubprojectPaths(self, name, path)
  1451. project = self.manifest.paths.get(relpath)
  1452. if project:
  1453. result.extend(project.GetDerivedSubprojects())
  1454. continue
  1455. remote = RemoteSpec(self.remote.name,
  1456. url=url,
  1457. review=self.remote.review,
  1458. revision=self.remote.revision)
  1459. subproject = Project(manifest=self.manifest,
  1460. name=name,
  1461. remote=remote,
  1462. gitdir=gitdir,
  1463. objdir=objdir,
  1464. worktree=worktree,
  1465. relpath=relpath,
  1466. revisionExpr=self.revisionExpr,
  1467. revisionId=rev,
  1468. rebase=self.rebase,
  1469. groups=self.groups,
  1470. sync_c=self.sync_c,
  1471. sync_s=self.sync_s,
  1472. parent=self,
  1473. is_derived=True)
  1474. result.append(subproject)
  1475. result.extend(subproject.GetDerivedSubprojects())
  1476. return result
  1477. ## Direct Git Commands ##
  1478. def _CheckForSha1(self):
  1479. try:
  1480. # if revision (sha or tag) is not present then following function
  1481. # throws an error.
  1482. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1483. return True
  1484. except GitError:
  1485. # There is no such persistent revision. We have to fetch it.
  1486. return False
  1487. def _FetchArchive(self, tarpath, cwd=None):
  1488. cmd = ['archive', '-v', '-o', tarpath]
  1489. cmd.append('--remote=%s' % self.remote.url)
  1490. cmd.append('--prefix=%s/' % self.relpath)
  1491. cmd.append(self.revisionExpr)
  1492. command = GitCommand(self, cmd, cwd=cwd,
  1493. capture_stdout=True,
  1494. capture_stderr=True)
  1495. if command.Wait() != 0:
  1496. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1497. def _RemoteFetch(self, name=None,
  1498. current_branch_only=False,
  1499. initial=False,
  1500. quiet=False,
  1501. alt_dir=None,
  1502. no_tags=False):
  1503. is_sha1 = False
  1504. tag_name = None
  1505. depth = None
  1506. # The depth should not be used when fetching to a mirror because
  1507. # it will result in a shallow repository that cannot be cloned or
  1508. # fetched from.
  1509. if not self.manifest.IsMirror:
  1510. if self.clone_depth:
  1511. depth = self.clone_depth
  1512. else:
  1513. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1514. # The repo project should never be synced with partial depth
  1515. if self.relpath == '.repo/repo':
  1516. depth = None
  1517. if depth:
  1518. current_branch_only = True
  1519. if ID_RE.match(self.revisionExpr) is not None:
  1520. is_sha1 = True
  1521. if current_branch_only:
  1522. if self.revisionExpr.startswith(R_TAGS):
  1523. # this is a tag and its sha1 value should never change
  1524. tag_name = self.revisionExpr[len(R_TAGS):]
  1525. if is_sha1 or tag_name is not None:
  1526. if self._CheckForSha1():
  1527. return True
  1528. if is_sha1 and not depth:
  1529. # When syncing a specific commit and --depth is not set:
  1530. # * if upstream is explicitly specified and is not a sha1, fetch only
  1531. # upstream as users expect only upstream to be fetch.
  1532. # Note: The commit might not be in upstream in which case the sync
  1533. # will fail.
  1534. # * otherwise, fetch all branches to make sure we end up with the
  1535. # specific commit.
  1536. current_branch_only = self.upstream and not ID_RE.match(self.upstream)
  1537. if not name:
  1538. name = self.remote.name
  1539. ssh_proxy = False
  1540. remote = self.GetRemote(name)
  1541. if remote.PreConnectFetch():
  1542. ssh_proxy = True
  1543. if initial:
  1544. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1545. ref_dir = os.path.dirname(alt_dir)
  1546. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1547. remote = self.GetRemote(name)
  1548. all_refs = self.bare_ref.all
  1549. ids = set(all_refs.values())
  1550. tmp = set()
  1551. for r, ref_id in GitRefs(ref_dir).all.items():
  1552. if r not in all_refs:
  1553. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1554. all_refs[r] = ref_id
  1555. ids.add(ref_id)
  1556. continue
  1557. if ref_id in ids:
  1558. continue
  1559. r = 'refs/_alt/%s' % ref_id
  1560. all_refs[r] = ref_id
  1561. ids.add(ref_id)
  1562. tmp.add(r)
  1563. tmp_packed = ''
  1564. old_packed = ''
  1565. for r in sorted(all_refs):
  1566. line = '%s %s\n' % (all_refs[r], r)
  1567. tmp_packed += line
  1568. if r not in tmp:
  1569. old_packed += line
  1570. _lwrite(packed_refs, tmp_packed)
  1571. else:
  1572. alt_dir = None
  1573. cmd = ['fetch']
  1574. if depth:
  1575. cmd.append('--depth=%s' % depth)
  1576. if quiet:
  1577. cmd.append('--quiet')
  1578. if not self.worktree:
  1579. cmd.append('--update-head-ok')
  1580. if self.manifest.IsMirror:
  1581. cmd.append('--prune')
  1582. cmd.append(name)
  1583. # If using depth then we should not get all the tags since they may
  1584. # be outside of the depth.
  1585. if no_tags or depth:
  1586. cmd.append('--no-tags')
  1587. else:
  1588. cmd.append('--tags')
  1589. spec = []
  1590. if not current_branch_only:
  1591. # Fetch whole repo
  1592. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1593. elif tag_name is not None:
  1594. spec.append('tag')
  1595. spec.append(tag_name)
  1596. if not self.manifest.IsMirror:
  1597. branch = self.revisionExpr
  1598. if is_sha1 and depth:
  1599. # Shallow checkout of a specific commit, fetch from that commit and not
  1600. # the heads only as the commit might be deeper in the history.
  1601. spec.append(branch)
  1602. else:
  1603. if is_sha1:
  1604. branch = self.upstream
  1605. if branch is not None and branch.strip():
  1606. if not branch.startswith('refs/'):
  1607. branch = R_HEADS + branch
  1608. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1609. cmd.extend(spec)
  1610. shallowfetch = self.config.GetString('repo.shallowfetch')
  1611. if shallowfetch and shallowfetch != ' '.join(spec):
  1612. GitCommand(self, ['fetch', '--depth=2147483647', name]
  1613. + shallowfetch.split(),
  1614. bare=True, ssh_proxy=ssh_proxy).Wait()
  1615. if depth:
  1616. self.config.SetString('repo.shallowfetch', ' '.join(spec))
  1617. else:
  1618. self.config.SetString('repo.shallowfetch', None)
  1619. ok = False
  1620. for _i in range(2):
  1621. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
  1622. ret = gitcmd.Wait()
  1623. if ret == 0:
  1624. ok = True
  1625. break
  1626. # If needed, run the 'git remote prune' the first time through the loop
  1627. elif (not _i and
  1628. "error:" in gitcmd.stderr and
  1629. "git remote prune" in gitcmd.stderr):
  1630. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1631. ssh_proxy=ssh_proxy)
  1632. ret = prunecmd.Wait()
  1633. if ret:
  1634. break
  1635. continue
  1636. elif current_branch_only and is_sha1 and ret == 128:
  1637. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1638. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1639. # abort the optimization attempt and do a full sync.
  1640. break
  1641. time.sleep(random.randint(30, 45))
  1642. if initial:
  1643. if alt_dir:
  1644. if old_packed != '':
  1645. _lwrite(packed_refs, old_packed)
  1646. else:
  1647. os.remove(packed_refs)
  1648. self.bare_git.pack_refs('--all', '--prune')
  1649. if is_sha1 and current_branch_only and self.upstream:
  1650. # We just synced the upstream given branch; verify we
  1651. # got what we wanted, else trigger a second run of all
  1652. # refs.
  1653. if not self._CheckForSha1():
  1654. return self._RemoteFetch(name=name, current_branch_only=False,
  1655. initial=False, quiet=quiet, alt_dir=alt_dir)
  1656. return ok
  1657. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1658. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1659. return False
  1660. remote = self.GetRemote(self.remote.name)
  1661. bundle_url = remote.url + '/clone.bundle'
  1662. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1663. if GetSchemeFromUrl(bundle_url) not in (
  1664. 'http', 'https', 'persistent-http', 'persistent-https'):
  1665. return False
  1666. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1667. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1668. exist_dst = os.path.exists(bundle_dst)
  1669. exist_tmp = os.path.exists(bundle_tmp)
  1670. if not initial and not exist_dst and not exist_tmp:
  1671. return False
  1672. if not exist_dst:
  1673. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1674. if not exist_dst:
  1675. return False
  1676. cmd = ['fetch']
  1677. if quiet:
  1678. cmd.append('--quiet')
  1679. if not self.worktree:
  1680. cmd.append('--update-head-ok')
  1681. cmd.append(bundle_dst)
  1682. for f in remote.fetch:
  1683. cmd.append(str(f))
  1684. cmd.append('refs/tags/*:refs/tags/*')
  1685. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1686. if os.path.exists(bundle_dst):
  1687. os.remove(bundle_dst)
  1688. if os.path.exists(bundle_tmp):
  1689. os.remove(bundle_tmp)
  1690. return ok
  1691. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1692. if os.path.exists(dstPath):
  1693. os.remove(dstPath)
  1694. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1695. if quiet:
  1696. cmd += ['--silent']
  1697. if os.path.exists(tmpPath):
  1698. size = os.stat(tmpPath).st_size
  1699. if size >= 1024:
  1700. cmd += ['--continue-at', '%d' % (size,)]
  1701. else:
  1702. os.remove(tmpPath)
  1703. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1704. cmd += ['--proxy', os.environ['http_proxy']]
  1705. with self._GetBundleCookieFile(srcUrl, quiet) as cookiefile:
  1706. if cookiefile:
  1707. cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
  1708. if srcUrl.startswith('persistent-'):
  1709. srcUrl = srcUrl[len('persistent-'):]
  1710. cmd += [srcUrl]
  1711. if IsTrace():
  1712. Trace('%s', ' '.join(cmd))
  1713. try:
  1714. proc = subprocess.Popen(cmd)
  1715. except OSError:
  1716. return False
  1717. curlret = proc.wait()
  1718. if curlret == 22:
  1719. # From curl man page:
  1720. # 22: HTTP page not retrieved. The requested url was not found or
  1721. # returned another error with the HTTP error code being 400 or above.
  1722. # This return code only appears if -f, --fail is used.
  1723. if not quiet:
  1724. print("Server does not provide clone.bundle; ignoring.",
  1725. file=sys.stderr)
  1726. return False
  1727. if os.path.exists(tmpPath):
  1728. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  1729. os.rename(tmpPath, dstPath)
  1730. return True
  1731. else:
  1732. os.remove(tmpPath)
  1733. return False
  1734. else:
  1735. return False
  1736. def _IsValidBundle(self, path, quiet):
  1737. try:
  1738. with open(path) as f:
  1739. if f.read(16) == '# v2 git bundle\n':
  1740. return True
  1741. else:
  1742. if not quiet:
  1743. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  1744. return False
  1745. except OSError:
  1746. return False
  1747. @contextlib.contextmanager
  1748. def _GetBundleCookieFile(self, url, quiet):
  1749. if url.startswith('persistent-'):
  1750. try:
  1751. p = subprocess.Popen(
  1752. ['git-remote-persistent-https', '-print_config', url],
  1753. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1754. stderr=subprocess.PIPE)
  1755. try:
  1756. prefix = 'http.cookiefile='
  1757. cookiefile = None
  1758. for line in p.stdout:
  1759. line = line.strip()
  1760. if line.startswith(prefix):
  1761. cookiefile = line[len(prefix):]
  1762. break
  1763. # Leave subprocess open, as cookie file may be transient.
  1764. if cookiefile:
  1765. yield cookiefile
  1766. return
  1767. finally:
  1768. p.stdin.close()
  1769. if p.wait():
  1770. err_msg = p.stderr.read()
  1771. if ' -print_config' in err_msg:
  1772. pass # Persistent proxy doesn't support -print_config.
  1773. elif not quiet:
  1774. print(err_msg, file=sys.stderr)
  1775. except OSError as e:
  1776. if e.errno == errno.ENOENT:
  1777. pass # No persistent proxy.
  1778. raise
  1779. yield GitConfig.ForUser().GetString('http.cookiefile')
  1780. def _Checkout(self, rev, quiet=False):
  1781. cmd = ['checkout']
  1782. if quiet:
  1783. cmd.append('-q')
  1784. cmd.append(rev)
  1785. cmd.append('--')
  1786. if GitCommand(self, cmd).Wait() != 0:
  1787. if self._allrefs:
  1788. raise GitError('%s checkout %s ' % (self.name, rev))
  1789. def _CherryPick(self, rev):
  1790. cmd = ['cherry-pick']
  1791. cmd.append(rev)
  1792. cmd.append('--')
  1793. if GitCommand(self, cmd).Wait() != 0:
  1794. if self._allrefs:
  1795. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1796. def _Revert(self, rev):
  1797. cmd = ['revert']
  1798. cmd.append('--no-edit')
  1799. cmd.append(rev)
  1800. cmd.append('--')
  1801. if GitCommand(self, cmd).Wait() != 0:
  1802. if self._allrefs:
  1803. raise GitError('%s revert %s ' % (self.name, rev))
  1804. def _ResetHard(self, rev, quiet=True):
  1805. cmd = ['reset', '--hard']
  1806. if quiet:
  1807. cmd.append('-q')
  1808. cmd.append(rev)
  1809. if GitCommand(self, cmd).Wait() != 0:
  1810. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1811. def _Rebase(self, upstream, onto=None):
  1812. cmd = ['rebase']
  1813. if onto is not None:
  1814. cmd.extend(['--onto', onto])
  1815. cmd.append(upstream)
  1816. if GitCommand(self, cmd).Wait() != 0:
  1817. raise GitError('%s rebase %s ' % (self.name, upstream))
  1818. def _FastForward(self, head, ffonly=False):
  1819. cmd = ['merge', head]
  1820. if ffonly:
  1821. cmd.append("--ff-only")
  1822. if GitCommand(self, cmd).Wait() != 0:
  1823. raise GitError('%s merge %s ' % (self.name, head))
  1824. def _InitGitDir(self, mirror_git=None):
  1825. if not os.path.exists(self.gitdir):
  1826. # Initialize the bare repository, which contains all of the objects.
  1827. if not os.path.exists(self.objdir):
  1828. os.makedirs(self.objdir)
  1829. self.bare_objdir.init()
  1830. # If we have a separate directory to hold refs, initialize it as well.
  1831. if self.objdir != self.gitdir:
  1832. os.makedirs(self.gitdir)
  1833. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  1834. copy_all=True)
  1835. mp = self.manifest.manifestProject
  1836. ref_dir = mp.config.GetString('repo.reference') or ''
  1837. if ref_dir or mirror_git:
  1838. if not mirror_git:
  1839. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1840. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1841. self.relpath + '.git')
  1842. if os.path.exists(mirror_git):
  1843. ref_dir = mirror_git
  1844. elif os.path.exists(repo_git):
  1845. ref_dir = repo_git
  1846. else:
  1847. ref_dir = None
  1848. if ref_dir:
  1849. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1850. os.path.join(ref_dir, 'objects') + '\n')
  1851. self._UpdateHooks()
  1852. m = self.manifest.manifestProject.config
  1853. for key in ['user.name', 'user.email']:
  1854. if m.Has(key, include_defaults=False):
  1855. self.config.SetString(key, m.GetString(key))
  1856. if self.manifest.IsMirror:
  1857. self.config.SetString('core.bare', 'true')
  1858. else:
  1859. self.config.SetString('core.bare', None)
  1860. def _UpdateHooks(self):
  1861. if os.path.exists(self.gitdir):
  1862. self._InitHooks()
  1863. def _InitHooks(self):
  1864. hooks = os.path.realpath(self._gitdir_path('hooks'))
  1865. if not os.path.exists(hooks):
  1866. os.makedirs(hooks)
  1867. for stock_hook in _ProjectHooks():
  1868. name = os.path.basename(stock_hook)
  1869. if name in ('commit-msg',) and not self.remote.review \
  1870. and not self is self.manifest.manifestProject:
  1871. # Don't install a Gerrit Code Review hook if this
  1872. # project does not appear to use it for reviews.
  1873. #
  1874. # Since the manifest project is one of those, but also
  1875. # managed through gerrit, it's excluded
  1876. continue
  1877. dst = os.path.join(hooks, name)
  1878. if os.path.islink(dst):
  1879. continue
  1880. if os.path.exists(dst):
  1881. if filecmp.cmp(stock_hook, dst, shallow=False):
  1882. os.remove(dst)
  1883. else:
  1884. _error("%s: Not replacing %s hook", self.relpath, name)
  1885. continue
  1886. try:
  1887. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1888. except OSError as e:
  1889. if e.errno == errno.EPERM:
  1890. raise GitError('filesystem must support symlinks')
  1891. else:
  1892. raise
  1893. def _InitRemote(self):
  1894. if self.remote.url:
  1895. remote = self.GetRemote(self.remote.name)
  1896. remote.url = self.remote.url
  1897. remote.review = self.remote.review
  1898. remote.projectname = self.name
  1899. if self.worktree:
  1900. remote.ResetFetch(mirror=False)
  1901. else:
  1902. remote.ResetFetch(mirror=True)
  1903. remote.Save()
  1904. def _InitMRef(self):
  1905. if self.manifest.branch:
  1906. self._InitAnyMRef(R_M + self.manifest.branch)
  1907. def _InitMirrorHead(self):
  1908. self._InitAnyMRef(HEAD)
  1909. def _InitAnyMRef(self, ref):
  1910. cur = self.bare_ref.symref(ref)
  1911. if self.revisionId:
  1912. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1913. msg = 'manifest set to %s' % self.revisionId
  1914. dst = self.revisionId + '^0'
  1915. self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
  1916. else:
  1917. remote = self.GetRemote(self.remote.name)
  1918. dst = remote.ToLocal(self.revisionExpr)
  1919. if cur != dst:
  1920. msg = 'manifest set to %s' % self.revisionExpr
  1921. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1922. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  1923. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  1924. Args:
  1925. gitdir: The bare git repository. Must already be initialized.
  1926. dotgit: The repository you would like to initialize.
  1927. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  1928. Only one work tree can store refs under a given |gitdir|.
  1929. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  1930. This saves you the effort of initializing |dotgit| yourself.
  1931. """
  1932. # These objects can be shared between several working trees.
  1933. symlink_files = ['description', 'info']
  1934. symlink_dirs = ['hooks', 'objects', 'rr-cache', 'svn']
  1935. if share_refs:
  1936. # These objects can only be used by a single working tree.
  1937. symlink_files += ['config', 'packed-refs', 'shallow']
  1938. symlink_dirs += ['logs', 'refs']
  1939. to_symlink = symlink_files + symlink_dirs
  1940. to_copy = []
  1941. if copy_all:
  1942. to_copy = os.listdir(gitdir)
  1943. for name in set(to_copy).union(to_symlink):
  1944. try:
  1945. src = os.path.realpath(os.path.join(gitdir, name))
  1946. dst = os.path.realpath(os.path.join(dotgit, name))
  1947. if os.path.lexists(dst) and not os.path.islink(dst):
  1948. raise GitError('cannot overwrite a local work tree')
  1949. # If the source dir doesn't exist, create an empty dir.
  1950. if name in symlink_dirs and not os.path.lexists(src):
  1951. os.makedirs(src)
  1952. # If the source file doesn't exist, ensure the destination
  1953. # file doesn't either.
  1954. if name in symlink_files and not os.path.lexists(src):
  1955. try:
  1956. os.remove(dst)
  1957. except OSError:
  1958. pass
  1959. if name in to_symlink:
  1960. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  1961. elif copy_all and not os.path.islink(dst):
  1962. if os.path.isdir(src):
  1963. shutil.copytree(src, dst)
  1964. elif os.path.isfile(src):
  1965. shutil.copy(src, dst)
  1966. except OSError as e:
  1967. if e.errno == errno.EPERM:
  1968. raise GitError('filesystem must support symlinks')
  1969. else:
  1970. raise
  1971. def _InitWorkTree(self):
  1972. dotgit = os.path.join(self.worktree, '.git')
  1973. if not os.path.exists(dotgit):
  1974. os.makedirs(dotgit)
  1975. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  1976. copy_all=False)
  1977. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1978. cmd = ['read-tree', '--reset', '-u']
  1979. cmd.append('-v')
  1980. cmd.append(HEAD)
  1981. if GitCommand(self, cmd).Wait() != 0:
  1982. raise GitError("cannot initialize work tree")
  1983. self._CopyAndLinkFiles()
  1984. def _gitdir_path(self, path):
  1985. return os.path.realpath(os.path.join(self.gitdir, path))
  1986. def _revlist(self, *args, **kw):
  1987. a = []
  1988. a.extend(args)
  1989. a.append('--')
  1990. return self.work_git.rev_list(*a, **kw)
  1991. @property
  1992. def _allrefs(self):
  1993. return self.bare_ref.all
  1994. def _getLogs(self, rev1, rev2, oneline=False, color=True):
  1995. """Get logs between two revisions of this project."""
  1996. comp = '..'
  1997. if rev1:
  1998. revs = [rev1]
  1999. if rev2:
  2000. revs.extend([comp, rev2])
  2001. cmd = ['log', ''.join(revs)]
  2002. out = DiffColoring(self.config)
  2003. if out.is_on and color:
  2004. cmd.append('--color')
  2005. if oneline:
  2006. cmd.append('--oneline')
  2007. try:
  2008. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2009. if log.Wait() == 0:
  2010. return log.stdout
  2011. except GitError:
  2012. # worktree may not exist if groups changed for example. In that case,
  2013. # try in gitdir instead.
  2014. if not os.path.exists(self.worktree):
  2015. return self.bare_git.log(*cmd[1:])
  2016. else:
  2017. raise
  2018. return None
  2019. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True):
  2020. """Get the list of logs from this revision to given revisionId"""
  2021. logs = {}
  2022. selfId = self.GetRevisionId(self._allrefs)
  2023. toId = toProject.GetRevisionId(toProject._allrefs)
  2024. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color)
  2025. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color)
  2026. return logs
  2027. class _GitGetByExec(object):
  2028. def __init__(self, project, bare, gitdir):
  2029. self._project = project
  2030. self._bare = bare
  2031. self._gitdir = gitdir
  2032. def LsOthers(self):
  2033. p = GitCommand(self._project,
  2034. ['ls-files',
  2035. '-z',
  2036. '--others',
  2037. '--exclude-standard'],
  2038. bare=False,
  2039. gitdir=self._gitdir,
  2040. capture_stdout=True,
  2041. capture_stderr=True)
  2042. if p.Wait() == 0:
  2043. out = p.stdout
  2044. if out:
  2045. return out[:-1].split('\0') # pylint: disable=W1401
  2046. # Backslash is not anomalous
  2047. return []
  2048. def DiffZ(self, name, *args):
  2049. cmd = [name]
  2050. cmd.append('-z')
  2051. cmd.extend(args)
  2052. p = GitCommand(self._project,
  2053. cmd,
  2054. gitdir=self._gitdir,
  2055. bare=False,
  2056. capture_stdout=True,
  2057. capture_stderr=True)
  2058. try:
  2059. out = p.process.stdout.read()
  2060. r = {}
  2061. if out:
  2062. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  2063. while out:
  2064. try:
  2065. info = next(out)
  2066. path = next(out)
  2067. except StopIteration:
  2068. break
  2069. class _Info(object):
  2070. def __init__(self, path, omode, nmode, oid, nid, state):
  2071. self.path = path
  2072. self.src_path = None
  2073. self.old_mode = omode
  2074. self.new_mode = nmode
  2075. self.old_id = oid
  2076. self.new_id = nid
  2077. if len(state) == 1:
  2078. self.status = state
  2079. self.level = None
  2080. else:
  2081. self.status = state[:1]
  2082. self.level = state[1:]
  2083. while self.level.startswith('0'):
  2084. self.level = self.level[1:]
  2085. info = info[1:].split(' ')
  2086. info = _Info(path, *info)
  2087. if info.status in ('R', 'C'):
  2088. info.src_path = info.path
  2089. info.path = next(out)
  2090. r[info.path] = info
  2091. return r
  2092. finally:
  2093. p.Wait()
  2094. def GetHead(self):
  2095. if self._bare:
  2096. path = os.path.join(self._project.gitdir, HEAD)
  2097. else:
  2098. path = os.path.join(self._project.worktree, '.git', HEAD)
  2099. try:
  2100. fd = open(path, 'rb')
  2101. except IOError as e:
  2102. raise NoManifestException(path, str(e))
  2103. try:
  2104. line = fd.read()
  2105. finally:
  2106. fd.close()
  2107. try:
  2108. line = line.decode()
  2109. except AttributeError:
  2110. pass
  2111. if line.startswith('ref: '):
  2112. return line[5:-1]
  2113. return line[:-1]
  2114. def SetHead(self, ref, message=None):
  2115. cmdv = []
  2116. if message is not None:
  2117. cmdv.extend(['-m', message])
  2118. cmdv.append(HEAD)
  2119. cmdv.append(ref)
  2120. self.symbolic_ref(*cmdv)
  2121. def DetachHead(self, new, message=None):
  2122. cmdv = ['--no-deref']
  2123. if message is not None:
  2124. cmdv.extend(['-m', message])
  2125. cmdv.append(HEAD)
  2126. cmdv.append(new)
  2127. self.update_ref(*cmdv)
  2128. def UpdateRef(self, name, new, old=None,
  2129. message=None,
  2130. detach=False):
  2131. cmdv = []
  2132. if message is not None:
  2133. cmdv.extend(['-m', message])
  2134. if detach:
  2135. cmdv.append('--no-deref')
  2136. cmdv.append(name)
  2137. cmdv.append(new)
  2138. if old is not None:
  2139. cmdv.append(old)
  2140. self.update_ref(*cmdv)
  2141. def DeleteRef(self, name, old=None):
  2142. if not old:
  2143. old = self.rev_parse(name)
  2144. self.update_ref('-d', name, old)
  2145. self._project.bare_ref.deleted(name)
  2146. def rev_list(self, *args, **kw):
  2147. if 'format' in kw:
  2148. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2149. else:
  2150. cmdv = ['rev-list']
  2151. cmdv.extend(args)
  2152. p = GitCommand(self._project,
  2153. cmdv,
  2154. bare=self._bare,
  2155. gitdir=self._gitdir,
  2156. capture_stdout=True,
  2157. capture_stderr=True)
  2158. r = []
  2159. for line in p.process.stdout:
  2160. if line[-1] == '\n':
  2161. line = line[:-1]
  2162. r.append(line)
  2163. if p.Wait() != 0:
  2164. raise GitError('%s rev-list %s: %s' % (
  2165. self._project.name,
  2166. str(args),
  2167. p.stderr))
  2168. return r
  2169. def __getattr__(self, name):
  2170. """Allow arbitrary git commands using pythonic syntax.
  2171. This allows you to do things like:
  2172. git_obj.rev_parse('HEAD')
  2173. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2174. run. We'll replace the '_' with a '-' and try to run a git command.
  2175. Any other positional arguments will be passed to the git command, and the
  2176. following keyword arguments are supported:
  2177. config: An optional dict of git config options to be passed with '-c'.
  2178. Args:
  2179. name: The name of the git command to call. Any '_' characters will
  2180. be replaced with '-'.
  2181. Returns:
  2182. A callable object that will try to call git with the named command.
  2183. """
  2184. name = name.replace('_', '-')
  2185. def runner(*args, **kwargs):
  2186. cmdv = []
  2187. config = kwargs.pop('config', None)
  2188. for k in kwargs:
  2189. raise TypeError('%s() got an unexpected keyword argument %r'
  2190. % (name, k))
  2191. if config is not None:
  2192. if not git_require((1, 7, 2)):
  2193. raise ValueError('cannot set config on command line for %s()'
  2194. % name)
  2195. for k, v in config.items():
  2196. cmdv.append('-c')
  2197. cmdv.append('%s=%s' % (k, v))
  2198. cmdv.append(name)
  2199. cmdv.extend(args)
  2200. p = GitCommand(self._project,
  2201. cmdv,
  2202. bare=self._bare,
  2203. gitdir=self._gitdir,
  2204. capture_stdout=True,
  2205. capture_stderr=True)
  2206. if p.Wait() != 0:
  2207. raise GitError('%s %s: %s' % (
  2208. self._project.name,
  2209. name,
  2210. p.stderr))
  2211. r = p.stdout
  2212. try:
  2213. r = r.decode('utf-8')
  2214. except AttributeError:
  2215. pass
  2216. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2217. return r[:-1]
  2218. return r
  2219. return runner
  2220. class _PriorSyncFailedError(Exception):
  2221. def __str__(self):
  2222. return 'prior sync failed; rebase still in progress'
  2223. class _DirtyError(Exception):
  2224. def __str__(self):
  2225. return 'contains uncommitted changes'
  2226. class _InfoMessage(object):
  2227. def __init__(self, project, text):
  2228. self.project = project
  2229. self.text = text
  2230. def Print(self, syncbuf):
  2231. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2232. syncbuf.out.nl()
  2233. class _Failure(object):
  2234. def __init__(self, project, why):
  2235. self.project = project
  2236. self.why = why
  2237. def Print(self, syncbuf):
  2238. syncbuf.out.fail('error: %s/: %s',
  2239. self.project.relpath,
  2240. str(self.why))
  2241. syncbuf.out.nl()
  2242. class _Later(object):
  2243. def __init__(self, project, action):
  2244. self.project = project
  2245. self.action = action
  2246. def Run(self, syncbuf):
  2247. out = syncbuf.out
  2248. out.project('project %s/', self.project.relpath)
  2249. out.nl()
  2250. try:
  2251. self.action()
  2252. out.nl()
  2253. return True
  2254. except GitError:
  2255. out.nl()
  2256. return False
  2257. class _SyncColoring(Coloring):
  2258. def __init__(self, config):
  2259. Coloring.__init__(self, config, 'reposync')
  2260. self.project = self.printer('header', attr='bold')
  2261. self.info = self.printer('info')
  2262. self.fail = self.printer('fail', fg='red')
  2263. class SyncBuffer(object):
  2264. def __init__(self, config, detach_head=False):
  2265. self._messages = []
  2266. self._failures = []
  2267. self._later_queue1 = []
  2268. self._later_queue2 = []
  2269. self.out = _SyncColoring(config)
  2270. self.out.redirect(sys.stderr)
  2271. self.detach_head = detach_head
  2272. self.clean = True
  2273. def info(self, project, fmt, *args):
  2274. self._messages.append(_InfoMessage(project, fmt % args))
  2275. def fail(self, project, err=None):
  2276. self._failures.append(_Failure(project, err))
  2277. self.clean = False
  2278. def later1(self, project, what):
  2279. self._later_queue1.append(_Later(project, what))
  2280. def later2(self, project, what):
  2281. self._later_queue2.append(_Later(project, what))
  2282. def Finish(self):
  2283. self._PrintMessages()
  2284. self._RunLater()
  2285. self._PrintMessages()
  2286. return self.clean
  2287. def _RunLater(self):
  2288. for q in ['_later_queue1', '_later_queue2']:
  2289. if not self._RunQueue(q):
  2290. return
  2291. def _RunQueue(self, queue):
  2292. for m in getattr(self, queue):
  2293. if not m.Run(self):
  2294. self.clean = False
  2295. return False
  2296. setattr(self, queue, [])
  2297. return True
  2298. def _PrintMessages(self):
  2299. for m in self._messages:
  2300. m.Print(self)
  2301. for m in self._failures:
  2302. m.Print(self)
  2303. self._messages = []
  2304. self._failures = []
  2305. class MetaProject(Project):
  2306. """A special project housed under .repo.
  2307. """
  2308. def __init__(self, manifest, name, gitdir, worktree):
  2309. Project.__init__(self,
  2310. manifest=manifest,
  2311. name=name,
  2312. gitdir=gitdir,
  2313. objdir=gitdir,
  2314. worktree=worktree,
  2315. remote=RemoteSpec('origin'),
  2316. relpath='.repo/%s' % name,
  2317. revisionExpr='refs/heads/master',
  2318. revisionId=None,
  2319. groups=None)
  2320. def PreSync(self):
  2321. if self.Exists:
  2322. cb = self.CurrentBranch
  2323. if cb:
  2324. base = self.GetBranch(cb).merge
  2325. if base:
  2326. self.revisionExpr = base
  2327. self.revisionId = None
  2328. def MetaBranchSwitch(self):
  2329. """ Prepare MetaProject for manifest branch switch
  2330. """
  2331. # detach and delete manifest branch, allowing a new
  2332. # branch to take over
  2333. syncbuf = SyncBuffer(self.config, detach_head=True)
  2334. self.Sync_LocalHalf(syncbuf)
  2335. syncbuf.Finish()
  2336. return GitCommand(self,
  2337. ['update-ref', '-d', 'refs/heads/default'],
  2338. capture_stdout=True,
  2339. capture_stderr=True).Wait() == 0
  2340. @property
  2341. def LastFetch(self):
  2342. try:
  2343. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2344. return os.path.getmtime(fh)
  2345. except OSError:
  2346. return 0
  2347. @property
  2348. def HasChanges(self):
  2349. """Has the remote received new commits not yet checked out?
  2350. """
  2351. if not self.remote or not self.revisionExpr:
  2352. return False
  2353. all_refs = self.bare_ref.all
  2354. revid = self.GetRevisionId(all_refs)
  2355. head = self.work_git.GetHead()
  2356. if head.startswith(R_HEADS):
  2357. try:
  2358. head = all_refs[head]
  2359. except KeyError:
  2360. head = None
  2361. if revid == head:
  2362. return False
  2363. elif self._revlist(not_rev(HEAD), revid):
  2364. return True
  2365. return False