project.py 72 KB

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