project.py 83 KB

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