project.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923
  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. import traceback
  15. import errno
  16. import filecmp
  17. import os
  18. import re
  19. import shutil
  20. import stat
  21. import sys
  22. import urllib2
  23. from color import Coloring
  24. from git_command import GitCommand
  25. from git_config import GitConfig, IsId
  26. from error import GitError, HookError, ImportError, UploadError
  27. from error import ManifestInvalidRevisionError
  28. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  29. def _lwrite(path, content):
  30. lock = '%s.lock' % path
  31. fd = open(lock, 'wb')
  32. try:
  33. fd.write(content)
  34. finally:
  35. fd.close()
  36. try:
  37. os.rename(lock, path)
  38. except OSError:
  39. os.remove(lock)
  40. raise
  41. def _error(fmt, *args):
  42. msg = fmt % args
  43. print >>sys.stderr, 'error: %s' % msg
  44. def not_rev(r):
  45. return '^' + r
  46. def sq(r):
  47. return "'" + r.replace("'", "'\''") + "'"
  48. _project_hook_list = None
  49. def _ProjectHooks():
  50. """List the hooks present in the 'hooks' directory.
  51. These hooks are project hooks and are copied to the '.git/hooks' directory
  52. of all subprojects.
  53. This function caches the list of hooks (based on the contents of the
  54. 'repo/hooks' directory) on the first call.
  55. Returns:
  56. A list of absolute paths to all of the files in the hooks directory.
  57. """
  58. global _project_hook_list
  59. if _project_hook_list is None:
  60. d = os.path.abspath(os.path.dirname(__file__))
  61. d = os.path.join(d , 'hooks')
  62. _project_hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
  63. return _project_hook_list
  64. def relpath(dst, src):
  65. src = os.path.dirname(src)
  66. top = os.path.commonprefix([dst, src])
  67. if top.endswith('/'):
  68. top = top[:-1]
  69. else:
  70. top = os.path.dirname(top)
  71. tmp = src
  72. rel = ''
  73. while top != tmp:
  74. rel += '../'
  75. tmp = os.path.dirname(tmp)
  76. return rel + dst[len(top) + 1:]
  77. class DownloadedChange(object):
  78. _commit_cache = None
  79. def __init__(self, project, base, change_id, ps_id, commit):
  80. self.project = project
  81. self.base = base
  82. self.change_id = change_id
  83. self.ps_id = ps_id
  84. self.commit = commit
  85. @property
  86. def commits(self):
  87. if self._commit_cache is None:
  88. self._commit_cache = self.project.bare_git.rev_list(
  89. '--abbrev=8',
  90. '--abbrev-commit',
  91. '--pretty=oneline',
  92. '--reverse',
  93. '--date-order',
  94. not_rev(self.base),
  95. self.commit,
  96. '--')
  97. return self._commit_cache
  98. class ReviewableBranch(object):
  99. _commit_cache = None
  100. def __init__(self, project, branch, base):
  101. self.project = project
  102. self.branch = branch
  103. self.base = base
  104. @property
  105. def name(self):
  106. return self.branch.name
  107. @property
  108. def commits(self):
  109. if self._commit_cache is None:
  110. self._commit_cache = self.project.bare_git.rev_list(
  111. '--abbrev=8',
  112. '--abbrev-commit',
  113. '--pretty=oneline',
  114. '--reverse',
  115. '--date-order',
  116. not_rev(self.base),
  117. R_HEADS + self.name,
  118. '--')
  119. return self._commit_cache
  120. @property
  121. def unabbrev_commits(self):
  122. r = dict()
  123. for commit in self.project.bare_git.rev_list(
  124. not_rev(self.base),
  125. R_HEADS + self.name,
  126. '--'):
  127. r[commit[0:8]] = commit
  128. return r
  129. @property
  130. def date(self):
  131. return self.project.bare_git.log(
  132. '--pretty=format:%cd',
  133. '-n', '1',
  134. R_HEADS + self.name,
  135. '--')
  136. def UploadForReview(self, people, auto_topic=False):
  137. self.project.UploadForReview(self.name,
  138. people,
  139. auto_topic=auto_topic)
  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 _CopyFile:
  167. def __init__(self, src, dest, abssrc, absdest):
  168. self.src = src
  169. self.dest = dest
  170. self.abs_src = abssrc
  171. self.abs_dest = absdest
  172. def _Copy(self):
  173. src = self.abs_src
  174. dest = self.abs_dest
  175. # copy file if it does not exist or is out of date
  176. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  177. try:
  178. # remove existing file first, since it might be read-only
  179. if os.path.exists(dest):
  180. os.remove(dest)
  181. else:
  182. dir = os.path.dirname(dest)
  183. if not os.path.isdir(dir):
  184. os.makedirs(dir)
  185. shutil.copy(src, dest)
  186. # make the file read-only
  187. mode = os.stat(dest)[stat.ST_MODE]
  188. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  189. os.chmod(dest, mode)
  190. except IOError:
  191. _error('Cannot copy file %s to %s', src, dest)
  192. class RemoteSpec(object):
  193. def __init__(self,
  194. name,
  195. url = None,
  196. review = None):
  197. self.name = name
  198. self.url = url
  199. self.review = review
  200. class RepoHook(object):
  201. """A RepoHook contains information about a script to run as a hook.
  202. Hooks are used to run a python script before running an upload (for instance,
  203. to run presubmit checks). Eventually, we may have hooks for other actions.
  204. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  205. files are copied into each '.git/hooks' folder for each project. Repo-level
  206. hooks are associated instead with repo actions.
  207. Hooks are always python. When a hook is run, we will load the hook into the
  208. interpreter and execute its main() function.
  209. """
  210. def __init__(self,
  211. hook_type,
  212. hooks_project,
  213. topdir,
  214. abort_if_user_denies=False):
  215. """RepoHook constructor.
  216. Params:
  217. hook_type: A string representing the type of hook. This is also used
  218. to figure out the name of the file containing the hook. For
  219. example: 'pre-upload'.
  220. hooks_project: The project containing the repo hooks. If you have a
  221. manifest, this is manifest.repo_hooks_project. OK if this is None,
  222. which will make the hook a no-op.
  223. topdir: Repo's top directory (the one containing the .repo directory).
  224. Scripts will run with CWD as this directory. If you have a manifest,
  225. this is manifest.topdir
  226. abort_if_user_denies: If True, we'll throw a HookError() if the user
  227. doesn't allow us to run the hook.
  228. """
  229. self._hook_type = hook_type
  230. self._hooks_project = hooks_project
  231. self._topdir = topdir
  232. self._abort_if_user_denies = abort_if_user_denies
  233. # Store the full path to the script for convenience.
  234. if self._hooks_project:
  235. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  236. self._hook_type + '.py')
  237. else:
  238. self._script_fullpath = None
  239. def _GetHash(self):
  240. """Return a hash of the contents of the hooks directory.
  241. We'll just use git to do this. This hash has the property that if anything
  242. changes in the directory we will return a different has.
  243. SECURITY CONSIDERATION:
  244. This hash only represents the contents of files in the hook directory, not
  245. any other files imported or called by hooks. Changes to imported files
  246. can change the script behavior without affecting the hash.
  247. Returns:
  248. A string representing the hash. This will always be ASCII so that it can
  249. be printed to the user easily.
  250. """
  251. assert self._hooks_project, "Must have hooks to calculate their hash."
  252. # We will use the work_git object rather than just calling GetRevisionId().
  253. # That gives us a hash of the latest checked in version of the files that
  254. # the user will actually be executing. Specifically, GetRevisionId()
  255. # doesn't appear to change even if a user checks out a different version
  256. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  257. #
  258. # NOTE: Local (non-committed) changes will not be factored into this hash.
  259. # I think this is OK, since we're really only worried about warning the user
  260. # about upstream changes.
  261. return self._hooks_project.work_git.rev_parse('HEAD')
  262. def _GetMustVerb(self):
  263. """Return 'must' if the hook is required; 'should' if not."""
  264. if self._abort_if_user_denies:
  265. return 'must'
  266. else:
  267. return 'should'
  268. def _CheckForHookApproval(self):
  269. """Check to see whether this hook has been approved.
  270. We'll look at the hash of all of the hooks. If this matches the hash that
  271. the user last approved, we're done. If it doesn't, we'll ask the user
  272. about approval.
  273. Note that we ask permission for each individual hook even though we use
  274. the hash of all hooks when detecting changes. We'd like the user to be
  275. able to approve / deny each hook individually. We only use the hash of all
  276. hooks because there is no other easy way to detect changes to local imports.
  277. Returns:
  278. True if this hook is approved to run; False otherwise.
  279. Raises:
  280. HookError: Raised if the user doesn't approve and abort_if_user_denies
  281. was passed to the consturctor.
  282. """
  283. hooks_dir = self._hooks_project.worktree
  284. hooks_config = self._hooks_project.config
  285. git_approval_key = 'repo.hooks.%s.approvedhash' % self._hook_type
  286. # Get the last hash that the user approved for this hook; may be None.
  287. old_hash = hooks_config.GetString(git_approval_key)
  288. # Get the current hash so we can tell if scripts changed since approval.
  289. new_hash = self._GetHash()
  290. if old_hash is not None:
  291. # User previously approved hook and asked not to be prompted again.
  292. if new_hash == old_hash:
  293. # Approval matched. We're done.
  294. return True
  295. else:
  296. # Give the user a reason why we're prompting, since they last told
  297. # us to "never ask again".
  298. prompt = 'WARNING: Scripts have changed since %s was allowed.\n\n' % (
  299. self._hook_type)
  300. else:
  301. prompt = ''
  302. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  303. if sys.stdout.isatty():
  304. prompt += ('Repo %s run the script:\n'
  305. ' %s\n'
  306. '\n'
  307. 'Do you want to allow this script to run '
  308. '(yes/yes-never-ask-again/NO)? ') % (
  309. self._GetMustVerb(), self._script_fullpath)
  310. response = raw_input(prompt).lower()
  311. print
  312. # User is doing a one-time approval.
  313. if response in ('y', 'yes'):
  314. return True
  315. elif response == 'yes-never-ask-again':
  316. hooks_config.SetString(git_approval_key, new_hash)
  317. return True
  318. # For anything else, we'll assume no approval.
  319. if self._abort_if_user_denies:
  320. raise HookError('You must allow the %s hook or use --no-verify.' %
  321. self._hook_type)
  322. return False
  323. def _ExecuteHook(self, **kwargs):
  324. """Actually execute the given hook.
  325. This will run the hook's 'main' function in our python interpreter.
  326. Args:
  327. kwargs: Keyword arguments to pass to the hook. These are often specific
  328. to the hook type. For instance, pre-upload hooks will contain
  329. a project_list.
  330. """
  331. # Keep sys.path and CWD stashed away so that we can always restore them
  332. # upon function exit.
  333. orig_path = os.getcwd()
  334. orig_syspath = sys.path
  335. try:
  336. # Always run hooks with CWD as topdir.
  337. os.chdir(self._topdir)
  338. # Put the hook dir as the first item of sys.path so hooks can do
  339. # relative imports. We want to replace the repo dir as [0] so
  340. # hooks can't import repo files.
  341. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  342. # Exec, storing global context in the context dict. We catch exceptions
  343. # and convert to a HookError w/ just the failing traceback.
  344. context = {}
  345. try:
  346. execfile(self._script_fullpath, context)
  347. except Exception:
  348. raise HookError('%s\nFailed to import %s hook; see traceback above.' % (
  349. traceback.format_exc(), self._hook_type))
  350. # Running the script should have defined a main() function.
  351. if 'main' not in context:
  352. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  353. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  354. # We don't actually want hooks to define their main with this argument--
  355. # it's there to remind them that their hook should always take **kwargs.
  356. # For instance, a pre-upload hook should be defined like:
  357. # def main(project_list, **kwargs):
  358. #
  359. # This allows us to later expand the API without breaking old hooks.
  360. kwargs = kwargs.copy()
  361. kwargs['hook_should_take_kwargs'] = True
  362. # Call the main function in the hook. If the hook should cause the
  363. # build to fail, it will raise an Exception. We'll catch that convert
  364. # to a HookError w/ just the failing traceback.
  365. try:
  366. context['main'](**kwargs)
  367. except Exception:
  368. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  369. 'above.' % (
  370. traceback.format_exc(), self._hook_type))
  371. finally:
  372. # Restore sys.path and CWD.
  373. sys.path = orig_syspath
  374. os.chdir(orig_path)
  375. def Run(self, user_allows_all_hooks, **kwargs):
  376. """Run the hook.
  377. If the hook doesn't exist (because there is no hooks project or because
  378. this particular hook is not enabled), this is a no-op.
  379. Args:
  380. user_allows_all_hooks: If True, we will never prompt about running the
  381. hook--we'll just assume it's OK to run it.
  382. kwargs: Keyword arguments to pass to the hook. These are often specific
  383. to the hook type. For instance, pre-upload hooks will contain
  384. a project_list.
  385. Raises:
  386. HookError: If there was a problem finding the hook or the user declined
  387. to run a required hook (from _CheckForHookApproval).
  388. """
  389. # No-op if there is no hooks project or if hook is disabled.
  390. if ((not self._hooks_project) or
  391. (self._hook_type not in self._hooks_project.enabled_repo_hooks)):
  392. return
  393. # Bail with a nice error if we can't find the hook.
  394. if not os.path.isfile(self._script_fullpath):
  395. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  396. # Make sure the user is OK with running the hook.
  397. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  398. return
  399. # Run the hook with the same version of python we're using.
  400. self._ExecuteHook(**kwargs)
  401. class Project(object):
  402. def __init__(self,
  403. manifest,
  404. name,
  405. remote,
  406. gitdir,
  407. worktree,
  408. relpath,
  409. revisionExpr,
  410. revisionId):
  411. self.manifest = manifest
  412. self.name = name
  413. self.remote = remote
  414. self.gitdir = gitdir.replace('\\', '/')
  415. if worktree:
  416. self.worktree = worktree.replace('\\', '/')
  417. else:
  418. self.worktree = None
  419. self.relpath = relpath
  420. self.revisionExpr = revisionExpr
  421. if revisionId is None \
  422. and revisionExpr \
  423. and IsId(revisionExpr):
  424. self.revisionId = revisionExpr
  425. else:
  426. self.revisionId = revisionId
  427. self.snapshots = {}
  428. self.copyfiles = []
  429. self.config = GitConfig.ForRepository(
  430. gitdir = self.gitdir,
  431. defaults = self.manifest.globalConfig)
  432. if self.worktree:
  433. self.work_git = self._GitGetByExec(self, bare=False)
  434. else:
  435. self.work_git = None
  436. self.bare_git = self._GitGetByExec(self, bare=True)
  437. self.bare_ref = GitRefs(gitdir)
  438. # This will be filled in if a project is later identified to be the
  439. # project containing repo hooks.
  440. self.enabled_repo_hooks = []
  441. @property
  442. def Exists(self):
  443. return os.path.isdir(self.gitdir)
  444. @property
  445. def CurrentBranch(self):
  446. """Obtain the name of the currently checked out branch.
  447. The branch name omits the 'refs/heads/' prefix.
  448. None is returned if the project is on a detached HEAD.
  449. """
  450. b = self.work_git.GetHead()
  451. if b.startswith(R_HEADS):
  452. return b[len(R_HEADS):]
  453. return None
  454. def IsRebaseInProgress(self):
  455. w = self.worktree
  456. g = os.path.join(w, '.git')
  457. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  458. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  459. or os.path.exists(os.path.join(w, '.dotest'))
  460. def IsDirty(self, consider_untracked=True):
  461. """Is the working directory modified in some way?
  462. """
  463. self.work_git.update_index('-q',
  464. '--unmerged',
  465. '--ignore-missing',
  466. '--refresh')
  467. if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
  468. return True
  469. if self.work_git.DiffZ('diff-files'):
  470. return True
  471. if consider_untracked and self.work_git.LsOthers():
  472. return True
  473. return False
  474. _userident_name = None
  475. _userident_email = None
  476. @property
  477. def UserName(self):
  478. """Obtain the user's personal name.
  479. """
  480. if self._userident_name is None:
  481. self._LoadUserIdentity()
  482. return self._userident_name
  483. @property
  484. def UserEmail(self):
  485. """Obtain the user's email address. This is very likely
  486. to be their Gerrit login.
  487. """
  488. if self._userident_email is None:
  489. self._LoadUserIdentity()
  490. return self._userident_email
  491. def _LoadUserIdentity(self):
  492. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  493. m = re.compile("^(.*) <([^>]*)> ").match(u)
  494. if m:
  495. self._userident_name = m.group(1)
  496. self._userident_email = m.group(2)
  497. else:
  498. self._userident_name = ''
  499. self._userident_email = ''
  500. def GetRemote(self, name):
  501. """Get the configuration for a single remote.
  502. """
  503. return self.config.GetRemote(name)
  504. def GetBranch(self, name):
  505. """Get the configuration for a single branch.
  506. """
  507. return self.config.GetBranch(name)
  508. def GetBranches(self):
  509. """Get all existing local branches.
  510. """
  511. current = self.CurrentBranch
  512. all = self._allrefs
  513. heads = {}
  514. pubd = {}
  515. for name, id in all.iteritems():
  516. if name.startswith(R_HEADS):
  517. name = name[len(R_HEADS):]
  518. b = self.GetBranch(name)
  519. b.current = name == current
  520. b.published = None
  521. b.revision = id
  522. heads[name] = b
  523. for name, id in all.iteritems():
  524. if name.startswith(R_PUB):
  525. name = name[len(R_PUB):]
  526. b = heads.get(name)
  527. if b:
  528. b.published = id
  529. return heads
  530. ## Status Display ##
  531. def HasChanges(self):
  532. """Returns true if there are uncommitted changes.
  533. """
  534. self.work_git.update_index('-q',
  535. '--unmerged',
  536. '--ignore-missing',
  537. '--refresh')
  538. if self.IsRebaseInProgress():
  539. return True
  540. if self.work_git.DiffZ('diff-index', '--cached', HEAD):
  541. return True
  542. if self.work_git.DiffZ('diff-files'):
  543. return True
  544. if self.work_git.LsOthers():
  545. return True
  546. return False
  547. def PrintWorkTreeStatus(self, output_redir=None):
  548. """Prints the status of the repository to stdout.
  549. Args:
  550. output: If specified, redirect the output to this object.
  551. """
  552. if not os.path.isdir(self.worktree):
  553. if output_redir == None:
  554. output_redir = sys.stdout
  555. print >>output_redir, ''
  556. print >>output_redir, 'project %s/' % self.relpath
  557. print >>output_redir, ' missing (run "repo sync")'
  558. return
  559. self.work_git.update_index('-q',
  560. '--unmerged',
  561. '--ignore-missing',
  562. '--refresh')
  563. rb = self.IsRebaseInProgress()
  564. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  565. df = self.work_git.DiffZ('diff-files')
  566. do = self.work_git.LsOthers()
  567. if not rb and not di and not df and not do:
  568. return 'CLEAN'
  569. out = StatusColoring(self.config)
  570. if not output_redir == None:
  571. out.redirect(output_redir)
  572. out.project('project %-40s', self.relpath + '/')
  573. branch = self.CurrentBranch
  574. if branch is None:
  575. out.nobranch('(*** NO BRANCH ***)')
  576. else:
  577. out.branch('branch %s', branch)
  578. out.nl()
  579. if rb:
  580. out.important('prior sync failed; rebase still in progress')
  581. out.nl()
  582. paths = list()
  583. paths.extend(di.keys())
  584. paths.extend(df.keys())
  585. paths.extend(do)
  586. paths = list(set(paths))
  587. paths.sort()
  588. for p in paths:
  589. try: i = di[p]
  590. except KeyError: i = None
  591. try: f = df[p]
  592. except KeyError: f = None
  593. if i: i_status = i.status.upper()
  594. else: i_status = '-'
  595. if f: f_status = f.status.lower()
  596. else: f_status = '-'
  597. if i and i.src_path:
  598. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  599. i.src_path, p, i.level)
  600. else:
  601. line = ' %s%s\t%s' % (i_status, f_status, p)
  602. if i and not f:
  603. out.added('%s', line)
  604. elif (i and f) or (not i and f):
  605. out.changed('%s', line)
  606. elif not i and not f:
  607. out.untracked('%s', line)
  608. else:
  609. out.write('%s', line)
  610. out.nl()
  611. return 'DIRTY'
  612. def PrintWorkTreeDiff(self):
  613. """Prints the status of the repository to stdout.
  614. """
  615. out = DiffColoring(self.config)
  616. cmd = ['diff']
  617. if out.is_on:
  618. cmd.append('--color')
  619. cmd.append(HEAD)
  620. cmd.append('--')
  621. p = GitCommand(self,
  622. cmd,
  623. capture_stdout = True,
  624. capture_stderr = True)
  625. has_diff = False
  626. for line in p.process.stdout:
  627. if not has_diff:
  628. out.nl()
  629. out.project('project %s/' % self.relpath)
  630. out.nl()
  631. has_diff = True
  632. print line[:-1]
  633. p.Wait()
  634. ## Publish / Upload ##
  635. def WasPublished(self, branch, all=None):
  636. """Was the branch published (uploaded) for code review?
  637. If so, returns the SHA-1 hash of the last published
  638. state for the branch.
  639. """
  640. key = R_PUB + branch
  641. if all is None:
  642. try:
  643. return self.bare_git.rev_parse(key)
  644. except GitError:
  645. return None
  646. else:
  647. try:
  648. return all[key]
  649. except KeyError:
  650. return None
  651. def CleanPublishedCache(self, all=None):
  652. """Prunes any stale published refs.
  653. """
  654. if all is None:
  655. all = self._allrefs
  656. heads = set()
  657. canrm = {}
  658. for name, id in all.iteritems():
  659. if name.startswith(R_HEADS):
  660. heads.add(name)
  661. elif name.startswith(R_PUB):
  662. canrm[name] = id
  663. for name, id in canrm.iteritems():
  664. n = name[len(R_PUB):]
  665. if R_HEADS + n not in heads:
  666. self.bare_git.DeleteRef(name, id)
  667. def GetUploadableBranches(self):
  668. """List any branches which can be uploaded for review.
  669. """
  670. heads = {}
  671. pubed = {}
  672. for name, id in self._allrefs.iteritems():
  673. if name.startswith(R_HEADS):
  674. heads[name[len(R_HEADS):]] = id
  675. elif name.startswith(R_PUB):
  676. pubed[name[len(R_PUB):]] = id
  677. ready = []
  678. for branch, id in heads.iteritems():
  679. if branch in pubed and pubed[branch] == id:
  680. continue
  681. rb = self.GetUploadableBranch(branch)
  682. if rb:
  683. ready.append(rb)
  684. return ready
  685. def GetUploadableBranch(self, branch_name):
  686. """Get a single uploadable branch, or None.
  687. """
  688. branch = self.GetBranch(branch_name)
  689. base = branch.LocalMerge
  690. if branch.LocalMerge:
  691. rb = ReviewableBranch(self, branch, base)
  692. if rb.commits:
  693. return rb
  694. return None
  695. def UploadForReview(self, branch=None,
  696. people=([],[]),
  697. auto_topic=False):
  698. """Uploads the named branch for code review.
  699. """
  700. if branch is None:
  701. branch = self.CurrentBranch
  702. if branch is None:
  703. raise GitError('not currently on a branch')
  704. branch = self.GetBranch(branch)
  705. if not branch.LocalMerge:
  706. raise GitError('branch %s does not track a remote' % branch.name)
  707. if not branch.remote.review:
  708. raise GitError('remote %s has no review url' % branch.remote.name)
  709. dest_branch = branch.merge
  710. if not dest_branch.startswith(R_HEADS):
  711. dest_branch = R_HEADS + dest_branch
  712. if not branch.remote.projectname:
  713. branch.remote.projectname = self.name
  714. branch.remote.Save()
  715. if branch.remote.ReviewProtocol == 'ssh':
  716. if dest_branch.startswith(R_HEADS):
  717. dest_branch = dest_branch[len(R_HEADS):]
  718. rp = ['gerrit receive-pack']
  719. for e in people[0]:
  720. rp.append('--reviewer=%s' % sq(e))
  721. for e in people[1]:
  722. rp.append('--cc=%s' % sq(e))
  723. ref_spec = '%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch)
  724. if auto_topic:
  725. ref_spec = ref_spec + '/' + branch.name
  726. cmd = ['push']
  727. cmd.append('--receive-pack=%s' % " ".join(rp))
  728. cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
  729. cmd.append(ref_spec)
  730. if GitCommand(self, cmd, bare = True).Wait() != 0:
  731. raise UploadError('Upload failed')
  732. else:
  733. raise UploadError('Unsupported protocol %s' \
  734. % branch.remote.review)
  735. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  736. self.bare_git.UpdateRef(R_PUB + branch.name,
  737. R_HEADS + branch.name,
  738. message = msg)
  739. ## Sync ##
  740. def Sync_NetworkHalf(self, quiet=False):
  741. """Perform only the network IO portion of the sync process.
  742. Local working directory/branch state is not affected.
  743. """
  744. is_new = not self.Exists
  745. if is_new:
  746. if not quiet:
  747. print >>sys.stderr
  748. print >>sys.stderr, 'Initializing project %s ...' % self.name
  749. self._InitGitDir()
  750. self._InitRemote()
  751. if not self._RemoteFetch(initial=is_new, quiet=quiet):
  752. return False
  753. #Check that the requested ref was found after fetch
  754. #
  755. try:
  756. self.GetRevisionId()
  757. except ManifestInvalidRevisionError:
  758. # if the ref is a tag. We can try fetching
  759. # the tag manually as a last resort
  760. #
  761. rev = self.revisionExpr
  762. if rev.startswith(R_TAGS):
  763. self._RemoteFetch(None, rev[len(R_TAGS):], quiet=quiet)
  764. if self.worktree:
  765. self._InitMRef()
  766. else:
  767. self._InitMirrorHead()
  768. try:
  769. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  770. except OSError:
  771. pass
  772. return True
  773. def PostRepoUpgrade(self):
  774. self._InitHooks()
  775. def _CopyFiles(self):
  776. for file in self.copyfiles:
  777. file._Copy()
  778. def GetRevisionId(self, all=None):
  779. if self.revisionId:
  780. return self.revisionId
  781. rem = self.GetRemote(self.remote.name)
  782. rev = rem.ToLocal(self.revisionExpr)
  783. if all is not None and rev in all:
  784. return all[rev]
  785. try:
  786. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  787. except GitError:
  788. raise ManifestInvalidRevisionError(
  789. 'revision %s in %s not found' % (self.revisionExpr,
  790. self.name))
  791. def Sync_LocalHalf(self, syncbuf):
  792. """Perform only the local IO portion of the sync process.
  793. Network access is not required.
  794. """
  795. all = self.bare_ref.all
  796. self.CleanPublishedCache(all)
  797. revid = self.GetRevisionId(all)
  798. self._InitWorkTree()
  799. head = self.work_git.GetHead()
  800. if head.startswith(R_HEADS):
  801. branch = head[len(R_HEADS):]
  802. try:
  803. head = all[head]
  804. except KeyError:
  805. head = None
  806. else:
  807. branch = None
  808. if branch is None or syncbuf.detach_head:
  809. # Currently on a detached HEAD. The user is assumed to
  810. # not have any local modifications worth worrying about.
  811. #
  812. if self.IsRebaseInProgress():
  813. syncbuf.fail(self, _PriorSyncFailedError())
  814. return
  815. if head == revid:
  816. # No changes; don't do anything further.
  817. #
  818. return
  819. lost = self._revlist(not_rev(revid), HEAD)
  820. if lost:
  821. syncbuf.info(self, "discarding %d commits", len(lost))
  822. try:
  823. self._Checkout(revid, quiet=True)
  824. except GitError, e:
  825. syncbuf.fail(self, e)
  826. return
  827. self._CopyFiles()
  828. return
  829. if head == revid:
  830. # No changes; don't do anything further.
  831. #
  832. return
  833. branch = self.GetBranch(branch)
  834. if not branch.LocalMerge:
  835. # The current branch has no tracking configuration.
  836. # Jump off it to a deatched HEAD.
  837. #
  838. syncbuf.info(self,
  839. "leaving %s; does not track upstream",
  840. branch.name)
  841. try:
  842. self._Checkout(revid, quiet=True)
  843. except GitError, e:
  844. syncbuf.fail(self, e)
  845. return
  846. self._CopyFiles()
  847. return
  848. upstream_gain = self._revlist(not_rev(HEAD), revid)
  849. pub = self.WasPublished(branch.name, all)
  850. if pub:
  851. not_merged = self._revlist(not_rev(revid), pub)
  852. if not_merged:
  853. if upstream_gain:
  854. # The user has published this branch and some of those
  855. # commits are not yet merged upstream. We do not want
  856. # to rewrite the published commits so we punt.
  857. #
  858. syncbuf.fail(self,
  859. "branch %s is published (but not merged) and is now %d commits behind"
  860. % (branch.name, len(upstream_gain)))
  861. return
  862. elif pub == head:
  863. # All published commits are merged, and thus we are a
  864. # strict subset. We can fast-forward safely.
  865. #
  866. def _doff():
  867. self._FastForward(revid)
  868. self._CopyFiles()
  869. syncbuf.later1(self, _doff)
  870. return
  871. # Examine the local commits not in the remote. Find the
  872. # last one attributed to this user, if any.
  873. #
  874. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  875. last_mine = None
  876. cnt_mine = 0
  877. for commit in local_changes:
  878. commit_id, committer_email = commit.split(' ', 1)
  879. if committer_email == self.UserEmail:
  880. last_mine = commit_id
  881. cnt_mine += 1
  882. if not upstream_gain and cnt_mine == len(local_changes):
  883. return
  884. if self.IsDirty(consider_untracked=False):
  885. syncbuf.fail(self, _DirtyError())
  886. return
  887. # If the upstream switched on us, warn the user.
  888. #
  889. if branch.merge != self.revisionExpr:
  890. if branch.merge and self.revisionExpr:
  891. syncbuf.info(self,
  892. 'manifest switched %s...%s',
  893. branch.merge,
  894. self.revisionExpr)
  895. elif branch.merge:
  896. syncbuf.info(self,
  897. 'manifest no longer tracks %s',
  898. branch.merge)
  899. if cnt_mine < len(local_changes):
  900. # Upstream rebased. Not everything in HEAD
  901. # was created by this user.
  902. #
  903. syncbuf.info(self,
  904. "discarding %d commits removed from upstream",
  905. len(local_changes) - cnt_mine)
  906. branch.remote = self.GetRemote(self.remote.name)
  907. branch.merge = self.revisionExpr
  908. branch.Save()
  909. if cnt_mine > 0:
  910. def _dorebase():
  911. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  912. self._CopyFiles()
  913. syncbuf.later2(self, _dorebase)
  914. elif local_changes:
  915. try:
  916. self._ResetHard(revid)
  917. self._CopyFiles()
  918. except GitError, e:
  919. syncbuf.fail(self, e)
  920. return
  921. else:
  922. def _doff():
  923. self._FastForward(revid)
  924. self._CopyFiles()
  925. syncbuf.later1(self, _doff)
  926. def AddCopyFile(self, src, dest, absdest):
  927. # dest should already be an absolute path, but src is project relative
  928. # make src an absolute path
  929. abssrc = os.path.join(self.worktree, src)
  930. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  931. def DownloadPatchSet(self, change_id, patch_id):
  932. """Download a single patch set of a single change to FETCH_HEAD.
  933. """
  934. remote = self.GetRemote(self.remote.name)
  935. cmd = ['fetch', remote.name]
  936. cmd.append('refs/changes/%2.2d/%d/%d' \
  937. % (change_id % 100, change_id, patch_id))
  938. cmd.extend(map(lambda x: str(x), remote.fetch))
  939. if GitCommand(self, cmd, bare=True).Wait() != 0:
  940. return None
  941. return DownloadedChange(self,
  942. self.GetRevisionId(),
  943. change_id,
  944. patch_id,
  945. self.bare_git.rev_parse('FETCH_HEAD'))
  946. ## Branch Management ##
  947. def StartBranch(self, name):
  948. """Create a new branch off the manifest's revision.
  949. """
  950. head = self.work_git.GetHead()
  951. if head == (R_HEADS + name):
  952. return True
  953. all = self.bare_ref.all
  954. if (R_HEADS + name) in all:
  955. return GitCommand(self,
  956. ['checkout', name, '--'],
  957. capture_stdout = True,
  958. capture_stderr = True).Wait() == 0
  959. branch = self.GetBranch(name)
  960. branch.remote = self.GetRemote(self.remote.name)
  961. branch.merge = self.revisionExpr
  962. revid = self.GetRevisionId(all)
  963. if head.startswith(R_HEADS):
  964. try:
  965. head = all[head]
  966. except KeyError:
  967. head = None
  968. if revid and head and revid == head:
  969. ref = os.path.join(self.gitdir, R_HEADS + name)
  970. try:
  971. os.makedirs(os.path.dirname(ref))
  972. except OSError:
  973. pass
  974. _lwrite(ref, '%s\n' % revid)
  975. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  976. 'ref: %s%s\n' % (R_HEADS, name))
  977. branch.Save()
  978. return True
  979. if GitCommand(self,
  980. ['checkout', '-b', branch.name, revid],
  981. capture_stdout = True,
  982. capture_stderr = True).Wait() == 0:
  983. branch.Save()
  984. return True
  985. return False
  986. def CheckoutBranch(self, name):
  987. """Checkout a local topic branch.
  988. """
  989. rev = R_HEADS + name
  990. head = self.work_git.GetHead()
  991. if head == rev:
  992. # Already on the branch
  993. #
  994. return True
  995. all = self.bare_ref.all
  996. try:
  997. revid = all[rev]
  998. except KeyError:
  999. # Branch does not exist in this project
  1000. #
  1001. return False
  1002. if head.startswith(R_HEADS):
  1003. try:
  1004. head = all[head]
  1005. except KeyError:
  1006. head = None
  1007. if head == revid:
  1008. # Same revision; just update HEAD to point to the new
  1009. # target branch, but otherwise take no other action.
  1010. #
  1011. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1012. 'ref: %s%s\n' % (R_HEADS, name))
  1013. return True
  1014. return GitCommand(self,
  1015. ['checkout', name, '--'],
  1016. capture_stdout = True,
  1017. capture_stderr = True).Wait() == 0
  1018. def AbandonBranch(self, name):
  1019. """Destroy a local topic branch.
  1020. Args:
  1021. name: The name of the branch to abandon.
  1022. Returns:
  1023. True if the abandon succeeded; False if it didn't; None if the branch
  1024. didn't exist.
  1025. """
  1026. rev = R_HEADS + name
  1027. all = self.bare_ref.all
  1028. if rev not in all:
  1029. # Doesn't exist
  1030. return None
  1031. head = self.work_git.GetHead()
  1032. if head == rev:
  1033. # We can't destroy the branch while we are sitting
  1034. # on it. Switch to a detached HEAD.
  1035. #
  1036. head = all[head]
  1037. revid = self.GetRevisionId(all)
  1038. if head == revid:
  1039. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1040. '%s\n' % revid)
  1041. else:
  1042. self._Checkout(revid, quiet=True)
  1043. return GitCommand(self,
  1044. ['branch', '-D', name],
  1045. capture_stdout = True,
  1046. capture_stderr = True).Wait() == 0
  1047. def PruneHeads(self):
  1048. """Prune any topic branches already merged into upstream.
  1049. """
  1050. cb = self.CurrentBranch
  1051. kill = []
  1052. left = self._allrefs
  1053. for name in left.keys():
  1054. if name.startswith(R_HEADS):
  1055. name = name[len(R_HEADS):]
  1056. if cb is None or name != cb:
  1057. kill.append(name)
  1058. rev = self.GetRevisionId(left)
  1059. if cb is not None \
  1060. and not self._revlist(HEAD + '...' + rev) \
  1061. and not self.IsDirty(consider_untracked = False):
  1062. self.work_git.DetachHead(HEAD)
  1063. kill.append(cb)
  1064. if kill:
  1065. old = self.bare_git.GetHead()
  1066. if old is None:
  1067. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1068. try:
  1069. self.bare_git.DetachHead(rev)
  1070. b = ['branch', '-d']
  1071. b.extend(kill)
  1072. b = GitCommand(self, b, bare=True,
  1073. capture_stdout=True,
  1074. capture_stderr=True)
  1075. b.Wait()
  1076. finally:
  1077. self.bare_git.SetHead(old)
  1078. left = self._allrefs
  1079. for branch in kill:
  1080. if (R_HEADS + branch) not in left:
  1081. self.CleanPublishedCache()
  1082. break
  1083. if cb and cb not in kill:
  1084. kill.append(cb)
  1085. kill.sort()
  1086. kept = []
  1087. for branch in kill:
  1088. if (R_HEADS + branch) in left:
  1089. branch = self.GetBranch(branch)
  1090. base = branch.LocalMerge
  1091. if not base:
  1092. base = rev
  1093. kept.append(ReviewableBranch(self, branch, base))
  1094. return kept
  1095. ## Direct Git Commands ##
  1096. def _RemoteFetch(self, name=None, tag=None,
  1097. initial=False,
  1098. quiet=False):
  1099. if not name:
  1100. name = self.remote.name
  1101. ssh_proxy = False
  1102. if self.GetRemote(name).PreConnectFetch():
  1103. ssh_proxy = True
  1104. if initial:
  1105. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  1106. try:
  1107. fd = open(alt, 'rb')
  1108. try:
  1109. ref_dir = fd.readline()
  1110. if ref_dir and ref_dir.endswith('\n'):
  1111. ref_dir = ref_dir[:-1]
  1112. finally:
  1113. fd.close()
  1114. except IOError, e:
  1115. ref_dir = None
  1116. if ref_dir and 'objects' == os.path.basename(ref_dir):
  1117. ref_dir = os.path.dirname(ref_dir)
  1118. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1119. remote = self.GetRemote(name)
  1120. all = self.bare_ref.all
  1121. ids = set(all.values())
  1122. tmp = set()
  1123. for r, id in GitRefs(ref_dir).all.iteritems():
  1124. if r not in all:
  1125. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1126. all[r] = id
  1127. ids.add(id)
  1128. continue
  1129. if id in ids:
  1130. continue
  1131. r = 'refs/_alt/%s' % id
  1132. all[r] = id
  1133. ids.add(id)
  1134. tmp.add(r)
  1135. ref_names = list(all.keys())
  1136. ref_names.sort()
  1137. tmp_packed = ''
  1138. old_packed = ''
  1139. for r in ref_names:
  1140. line = '%s %s\n' % (all[r], r)
  1141. tmp_packed += line
  1142. if r not in tmp:
  1143. old_packed += line
  1144. _lwrite(packed_refs, tmp_packed)
  1145. else:
  1146. ref_dir = None
  1147. cmd = ['fetch']
  1148. if quiet:
  1149. cmd.append('--quiet')
  1150. if not self.worktree:
  1151. cmd.append('--update-head-ok')
  1152. cmd.append(name)
  1153. if tag is not None:
  1154. cmd.append('tag')
  1155. cmd.append(tag)
  1156. ok = GitCommand(self,
  1157. cmd,
  1158. bare = True,
  1159. ssh_proxy = ssh_proxy).Wait() == 0
  1160. if initial:
  1161. if ref_dir:
  1162. if old_packed != '':
  1163. _lwrite(packed_refs, old_packed)
  1164. else:
  1165. os.remove(packed_refs)
  1166. self.bare_git.pack_refs('--all', '--prune')
  1167. return ok
  1168. def _Checkout(self, rev, quiet=False):
  1169. cmd = ['checkout']
  1170. if quiet:
  1171. cmd.append('-q')
  1172. cmd.append(rev)
  1173. cmd.append('--')
  1174. if GitCommand(self, cmd).Wait() != 0:
  1175. if self._allrefs:
  1176. raise GitError('%s checkout %s ' % (self.name, rev))
  1177. def _ResetHard(self, rev, quiet=True):
  1178. cmd = ['reset', '--hard']
  1179. if quiet:
  1180. cmd.append('-q')
  1181. cmd.append(rev)
  1182. if GitCommand(self, cmd).Wait() != 0:
  1183. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1184. def _Rebase(self, upstream, onto = None):
  1185. cmd = ['rebase']
  1186. if onto is not None:
  1187. cmd.extend(['--onto', onto])
  1188. cmd.append(upstream)
  1189. if GitCommand(self, cmd).Wait() != 0:
  1190. raise GitError('%s rebase %s ' % (self.name, upstream))
  1191. def _FastForward(self, head):
  1192. cmd = ['merge', head]
  1193. if GitCommand(self, cmd).Wait() != 0:
  1194. raise GitError('%s merge %s ' % (self.name, head))
  1195. def _InitGitDir(self):
  1196. if not os.path.exists(self.gitdir):
  1197. os.makedirs(self.gitdir)
  1198. self.bare_git.init()
  1199. mp = self.manifest.manifestProject
  1200. ref_dir = mp.config.GetString('repo.reference')
  1201. if ref_dir:
  1202. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1203. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1204. self.relpath + '.git')
  1205. if os.path.exists(mirror_git):
  1206. ref_dir = mirror_git
  1207. elif os.path.exists(repo_git):
  1208. ref_dir = repo_git
  1209. else:
  1210. ref_dir = None
  1211. if ref_dir:
  1212. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1213. os.path.join(ref_dir, 'objects') + '\n')
  1214. if self.manifest.IsMirror:
  1215. self.config.SetString('core.bare', 'true')
  1216. else:
  1217. self.config.SetString('core.bare', None)
  1218. hooks = self._gitdir_path('hooks')
  1219. try:
  1220. to_rm = os.listdir(hooks)
  1221. except OSError:
  1222. to_rm = []
  1223. for old_hook in to_rm:
  1224. os.remove(os.path.join(hooks, old_hook))
  1225. self._InitHooks()
  1226. m = self.manifest.manifestProject.config
  1227. for key in ['user.name', 'user.email']:
  1228. if m.Has(key, include_defaults = False):
  1229. self.config.SetString(key, m.GetString(key))
  1230. def _InitHooks(self):
  1231. hooks = self._gitdir_path('hooks')
  1232. if not os.path.exists(hooks):
  1233. os.makedirs(hooks)
  1234. for stock_hook in _ProjectHooks():
  1235. name = os.path.basename(stock_hook)
  1236. if name in ('commit-msg',) and not self.remote.review:
  1237. # Don't install a Gerrit Code Review hook if this
  1238. # project does not appear to use it for reviews.
  1239. #
  1240. continue
  1241. dst = os.path.join(hooks, name)
  1242. if os.path.islink(dst):
  1243. continue
  1244. if os.path.exists(dst):
  1245. if filecmp.cmp(stock_hook, dst, shallow=False):
  1246. os.remove(dst)
  1247. else:
  1248. _error("%s: Not replacing %s hook", self.relpath, name)
  1249. continue
  1250. try:
  1251. os.symlink(relpath(stock_hook, dst), dst)
  1252. except OSError, e:
  1253. if e.errno == errno.EPERM:
  1254. raise GitError('filesystem must support symlinks')
  1255. else:
  1256. raise
  1257. def _InitRemote(self):
  1258. if self.remote.url:
  1259. remote = self.GetRemote(self.remote.name)
  1260. remote.url = self.remote.url
  1261. remote.review = self.remote.review
  1262. remote.projectname = self.name
  1263. if self.worktree:
  1264. remote.ResetFetch(mirror=False)
  1265. else:
  1266. remote.ResetFetch(mirror=True)
  1267. remote.Save()
  1268. def _InitMRef(self):
  1269. if self.manifest.branch:
  1270. self._InitAnyMRef(R_M + self.manifest.branch)
  1271. def _InitMirrorHead(self):
  1272. self._InitAnyMRef(HEAD)
  1273. def _InitAnyMRef(self, ref):
  1274. cur = self.bare_ref.symref(ref)
  1275. if self.revisionId:
  1276. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1277. msg = 'manifest set to %s' % self.revisionId
  1278. dst = self.revisionId + '^0'
  1279. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1280. else:
  1281. remote = self.GetRemote(self.remote.name)
  1282. dst = remote.ToLocal(self.revisionExpr)
  1283. if cur != dst:
  1284. msg = 'manifest set to %s' % self.revisionExpr
  1285. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1286. def _InitWorkTree(self):
  1287. dotgit = os.path.join(self.worktree, '.git')
  1288. if not os.path.exists(dotgit):
  1289. os.makedirs(dotgit)
  1290. for name in ['config',
  1291. 'description',
  1292. 'hooks',
  1293. 'info',
  1294. 'logs',
  1295. 'objects',
  1296. 'packed-refs',
  1297. 'refs',
  1298. 'rr-cache',
  1299. 'svn']:
  1300. try:
  1301. src = os.path.join(self.gitdir, name)
  1302. dst = os.path.join(dotgit, name)
  1303. if os.path.islink(dst) or not os.path.exists(dst):
  1304. os.symlink(relpath(src, dst), dst)
  1305. else:
  1306. raise GitError('cannot overwrite a local work tree')
  1307. except OSError, e:
  1308. if e.errno == errno.EPERM:
  1309. raise GitError('filesystem must support symlinks')
  1310. else:
  1311. raise
  1312. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1313. cmd = ['read-tree', '--reset', '-u']
  1314. cmd.append('-v')
  1315. cmd.append(HEAD)
  1316. if GitCommand(self, cmd).Wait() != 0:
  1317. raise GitError("cannot initialize work tree")
  1318. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1319. if not os.path.exists(rr_cache):
  1320. os.makedirs(rr_cache)
  1321. self._CopyFiles()
  1322. def _gitdir_path(self, path):
  1323. return os.path.join(self.gitdir, path)
  1324. def _revlist(self, *args, **kw):
  1325. a = []
  1326. a.extend(args)
  1327. a.append('--')
  1328. return self.work_git.rev_list(*a, **kw)
  1329. @property
  1330. def _allrefs(self):
  1331. return self.bare_ref.all
  1332. class _GitGetByExec(object):
  1333. def __init__(self, project, bare):
  1334. self._project = project
  1335. self._bare = bare
  1336. def LsOthers(self):
  1337. p = GitCommand(self._project,
  1338. ['ls-files',
  1339. '-z',
  1340. '--others',
  1341. '--exclude-standard'],
  1342. bare = False,
  1343. capture_stdout = True,
  1344. capture_stderr = True)
  1345. if p.Wait() == 0:
  1346. out = p.stdout
  1347. if out:
  1348. return out[:-1].split("\0")
  1349. return []
  1350. def DiffZ(self, name, *args):
  1351. cmd = [name]
  1352. cmd.append('-z')
  1353. cmd.extend(args)
  1354. p = GitCommand(self._project,
  1355. cmd,
  1356. bare = False,
  1357. capture_stdout = True,
  1358. capture_stderr = True)
  1359. try:
  1360. out = p.process.stdout.read()
  1361. r = {}
  1362. if out:
  1363. out = iter(out[:-1].split('\0'))
  1364. while out:
  1365. try:
  1366. info = out.next()
  1367. path = out.next()
  1368. except StopIteration:
  1369. break
  1370. class _Info(object):
  1371. def __init__(self, path, omode, nmode, oid, nid, state):
  1372. self.path = path
  1373. self.src_path = None
  1374. self.old_mode = omode
  1375. self.new_mode = nmode
  1376. self.old_id = oid
  1377. self.new_id = nid
  1378. if len(state) == 1:
  1379. self.status = state
  1380. self.level = None
  1381. else:
  1382. self.status = state[:1]
  1383. self.level = state[1:]
  1384. while self.level.startswith('0'):
  1385. self.level = self.level[1:]
  1386. info = info[1:].split(' ')
  1387. info =_Info(path, *info)
  1388. if info.status in ('R', 'C'):
  1389. info.src_path = info.path
  1390. info.path = out.next()
  1391. r[info.path] = info
  1392. return r
  1393. finally:
  1394. p.Wait()
  1395. def GetHead(self):
  1396. if self._bare:
  1397. path = os.path.join(self._project.gitdir, HEAD)
  1398. else:
  1399. path = os.path.join(self._project.worktree, '.git', HEAD)
  1400. fd = open(path, 'rb')
  1401. try:
  1402. line = fd.read()
  1403. finally:
  1404. fd.close()
  1405. if line.startswith('ref: '):
  1406. return line[5:-1]
  1407. return line[:-1]
  1408. def SetHead(self, ref, message=None):
  1409. cmdv = []
  1410. if message is not None:
  1411. cmdv.extend(['-m', message])
  1412. cmdv.append(HEAD)
  1413. cmdv.append(ref)
  1414. self.symbolic_ref(*cmdv)
  1415. def DetachHead(self, new, message=None):
  1416. cmdv = ['--no-deref']
  1417. if message is not None:
  1418. cmdv.extend(['-m', message])
  1419. cmdv.append(HEAD)
  1420. cmdv.append(new)
  1421. self.update_ref(*cmdv)
  1422. def UpdateRef(self, name, new, old=None,
  1423. message=None,
  1424. detach=False):
  1425. cmdv = []
  1426. if message is not None:
  1427. cmdv.extend(['-m', message])
  1428. if detach:
  1429. cmdv.append('--no-deref')
  1430. cmdv.append(name)
  1431. cmdv.append(new)
  1432. if old is not None:
  1433. cmdv.append(old)
  1434. self.update_ref(*cmdv)
  1435. def DeleteRef(self, name, old=None):
  1436. if not old:
  1437. old = self.rev_parse(name)
  1438. self.update_ref('-d', name, old)
  1439. self._project.bare_ref.deleted(name)
  1440. def rev_list(self, *args, **kw):
  1441. if 'format' in kw:
  1442. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1443. else:
  1444. cmdv = ['rev-list']
  1445. cmdv.extend(args)
  1446. p = GitCommand(self._project,
  1447. cmdv,
  1448. bare = self._bare,
  1449. capture_stdout = True,
  1450. capture_stderr = True)
  1451. r = []
  1452. for line in p.process.stdout:
  1453. if line[-1] == '\n':
  1454. line = line[:-1]
  1455. r.append(line)
  1456. if p.Wait() != 0:
  1457. raise GitError('%s rev-list %s: %s' % (
  1458. self._project.name,
  1459. str(args),
  1460. p.stderr))
  1461. return r
  1462. def __getattr__(self, name):
  1463. """Allow arbitrary git commands using pythonic syntax.
  1464. This allows you to do things like:
  1465. git_obj.rev_parse('HEAD')
  1466. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1467. run. We'll replace the '_' with a '-' and try to run a git command.
  1468. Any other arguments will be passed to the git command.
  1469. Args:
  1470. name: The name of the git command to call. Any '_' characters will
  1471. be replaced with '-'.
  1472. Returns:
  1473. A callable object that will try to call git with the named command.
  1474. """
  1475. name = name.replace('_', '-')
  1476. def runner(*args):
  1477. cmdv = [name]
  1478. cmdv.extend(args)
  1479. p = GitCommand(self._project,
  1480. cmdv,
  1481. bare = self._bare,
  1482. capture_stdout = True,
  1483. capture_stderr = True)
  1484. if p.Wait() != 0:
  1485. raise GitError('%s %s: %s' % (
  1486. self._project.name,
  1487. name,
  1488. p.stderr))
  1489. r = p.stdout
  1490. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1491. return r[:-1]
  1492. return r
  1493. return runner
  1494. class _PriorSyncFailedError(Exception):
  1495. def __str__(self):
  1496. return 'prior sync failed; rebase still in progress'
  1497. class _DirtyError(Exception):
  1498. def __str__(self):
  1499. return 'contains uncommitted changes'
  1500. class _InfoMessage(object):
  1501. def __init__(self, project, text):
  1502. self.project = project
  1503. self.text = text
  1504. def Print(self, syncbuf):
  1505. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1506. syncbuf.out.nl()
  1507. class _Failure(object):
  1508. def __init__(self, project, why):
  1509. self.project = project
  1510. self.why = why
  1511. def Print(self, syncbuf):
  1512. syncbuf.out.fail('error: %s/: %s',
  1513. self.project.relpath,
  1514. str(self.why))
  1515. syncbuf.out.nl()
  1516. class _Later(object):
  1517. def __init__(self, project, action):
  1518. self.project = project
  1519. self.action = action
  1520. def Run(self, syncbuf):
  1521. out = syncbuf.out
  1522. out.project('project %s/', self.project.relpath)
  1523. out.nl()
  1524. try:
  1525. self.action()
  1526. out.nl()
  1527. return True
  1528. except GitError, e:
  1529. out.nl()
  1530. return False
  1531. class _SyncColoring(Coloring):
  1532. def __init__(self, config):
  1533. Coloring.__init__(self, config, 'reposync')
  1534. self.project = self.printer('header', attr = 'bold')
  1535. self.info = self.printer('info')
  1536. self.fail = self.printer('fail', fg='red')
  1537. class SyncBuffer(object):
  1538. def __init__(self, config, detach_head=False):
  1539. self._messages = []
  1540. self._failures = []
  1541. self._later_queue1 = []
  1542. self._later_queue2 = []
  1543. self.out = _SyncColoring(config)
  1544. self.out.redirect(sys.stderr)
  1545. self.detach_head = detach_head
  1546. self.clean = True
  1547. def info(self, project, fmt, *args):
  1548. self._messages.append(_InfoMessage(project, fmt % args))
  1549. def fail(self, project, err=None):
  1550. self._failures.append(_Failure(project, err))
  1551. self.clean = False
  1552. def later1(self, project, what):
  1553. self._later_queue1.append(_Later(project, what))
  1554. def later2(self, project, what):
  1555. self._later_queue2.append(_Later(project, what))
  1556. def Finish(self):
  1557. self._PrintMessages()
  1558. self._RunLater()
  1559. self._PrintMessages()
  1560. return self.clean
  1561. def _RunLater(self):
  1562. for q in ['_later_queue1', '_later_queue2']:
  1563. if not self._RunQueue(q):
  1564. return
  1565. def _RunQueue(self, queue):
  1566. for m in getattr(self, queue):
  1567. if not m.Run(self):
  1568. self.clean = False
  1569. return False
  1570. setattr(self, queue, [])
  1571. return True
  1572. def _PrintMessages(self):
  1573. for m in self._messages:
  1574. m.Print(self)
  1575. for m in self._failures:
  1576. m.Print(self)
  1577. self._messages = []
  1578. self._failures = []
  1579. class MetaProject(Project):
  1580. """A special project housed under .repo.
  1581. """
  1582. def __init__(self, manifest, name, gitdir, worktree):
  1583. repodir = manifest.repodir
  1584. Project.__init__(self,
  1585. manifest = manifest,
  1586. name = name,
  1587. gitdir = gitdir,
  1588. worktree = worktree,
  1589. remote = RemoteSpec('origin'),
  1590. relpath = '.repo/%s' % name,
  1591. revisionExpr = 'refs/heads/master',
  1592. revisionId = None)
  1593. def PreSync(self):
  1594. if self.Exists:
  1595. cb = self.CurrentBranch
  1596. if cb:
  1597. base = self.GetBranch(cb).merge
  1598. if base:
  1599. self.revisionExpr = base
  1600. self.revisionId = None
  1601. @property
  1602. def LastFetch(self):
  1603. try:
  1604. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  1605. return os.path.getmtime(fh)
  1606. except OSError:
  1607. return 0
  1608. @property
  1609. def HasChanges(self):
  1610. """Has the remote received new commits not yet checked out?
  1611. """
  1612. if not self.remote or not self.revisionExpr:
  1613. return False
  1614. all = self.bare_ref.all
  1615. revid = self.GetRevisionId(all)
  1616. head = self.work_git.GetHead()
  1617. if head.startswith(R_HEADS):
  1618. try:
  1619. head = all[head]
  1620. except KeyError:
  1621. head = None
  1622. if revid == head:
  1623. return False
  1624. elif self._revlist(not_rev(HEAD), revid):
  1625. return True
  1626. return False