Advertisement
Guest User

Untitled

a guest
Dec 20th, 2016
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 42.89 KB | None | 0 0
  1. # shelve.py - save/restore working directory state
  2. #
  3. # Copyright 2013 Facebook, Inc.
  4. #
  5. # This software may be used and distributed according to the terms of the
  6. # GNU General Public License version 2 or any later version.
  7.  
  8. """save and restore changes to the working directory
  9.  
  10. The "hg shelve" command saves changes made to the working directory
  11. and reverts those changes, resetting the working directory to a clean
  12. state.
  13.  
  14. Later on, the "hg unshelve" command restores the changes saved by "hg
  15. shelve". Changes can be restored even after updating to a different
  16. parent, in which case Mercurial's merge machinery will resolve any
  17. conflicts if necessary.
  18.  
  19. You can have more than one shelved change outstanding at a time; each
  20. shelved change has a distinct name. For details, see the help for "hg
  21. shelve".
  22. """
  23. from __future__ import absolute_import
  24.  
  25. import collections
  26. import errno
  27. import itertools
  28. import time
  29.  
  30. from mercurial.i18n import _
  31. from mercurial import (
  32.     bookmarks,
  33.     bundle2,
  34.     bundlerepo,
  35.     changegroup,
  36.     cmdutil,
  37.     commands,
  38.     error,
  39.     exchange,
  40.     hg,
  41.     lock as lockmod,
  42.     mdiff,
  43.     merge,
  44.     node as nodemod,
  45.     obsolete,
  46.     patch,
  47.     phases,
  48.     repair,
  49.     scmutil,
  50.     templatefilters,
  51.     util,
  52. )
  53.  
  54. from . import (
  55.     rebase,
  56. )
  57.  
  58. cmdtable = {}
  59. command = cmdutil.command(cmdtable)
  60. # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
  61. # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
  62. # be specifying the version(s) of Mercurial they are tested with, or
  63. # leave the attribute unspecified.
  64. testedwith = 'ships-with-hg-core'
  65.  
  66. backupdir = 'shelve-backup'
  67. shelvedir = 'shelved'
  68. shelvefileextensions = ['hg', 'patch', 'oshelve']
  69. # universal extension is present in all types of shelves
  70. patchextension = 'patch'
  71.  
  72. # we never need the user, so we use a
  73. # generic user for all shelve operations
  74. shelveuser = 'shelve@localhost'
  75.  
  76. def isobsshelve(repo, ui):
  77.     """Check whether obsolescense-based shelve is enabled"""
  78.     obsshelve = ui.configbool('experimental', 'obsshelve')
  79.     if not obsshelve:
  80.         return False
  81.     if not obsolete.isenabled(repo, obsolete.createmarkersopt):
  82.         w = _('ignoring experimental.obsshelve because createmarkers option '
  83.               'is disabled')
  84.         ui.warn(w)
  85.         return False
  86.     return True
  87.  
  88. class obsshelvefile(scmutil.simplekeyvaluefile):
  89.     KEYS = [('node', True)]
  90.  
  91. class shelvedfile(object):
  92.     """Helper for the file storing a single shelve
  93.  
  94.    Handles common functions on shelve files (.hg/.patch) using
  95.    the vfs layer"""
  96.     def __init__(self, repo, name, filetype=None):
  97.         self.repo = repo
  98.         self.name = name
  99.         self.vfs = scmutil.vfs(repo.join(shelvedir))
  100.         self.backupvfs = scmutil.vfs(repo.join(backupdir))
  101.         self.ui = self.repo.ui
  102.         if filetype:
  103.             self.fname = name + '.' + filetype
  104.         else:
  105.             self.fname = name
  106.  
  107.     def exists(self):
  108.         return self.vfs.exists(self.fname)
  109.  
  110.     def filename(self):
  111.         return self.vfs.join(self.fname)
  112.  
  113.     def backupfilename(self):
  114.         def gennames(base):
  115.             yield base
  116.             base, ext = base.rsplit('.', 1)
  117.             for i in itertools.count(1):
  118.                 yield '%s-%d.%s' % (base, i, ext)
  119.  
  120.         name = self.backupvfs.join(self.fname)
  121.         for n in gennames(name):
  122.             if not self.backupvfs.exists(n):
  123.                 return n
  124.  
  125.     def movetobackup(self):
  126.         if not self.backupvfs.isdir():
  127.             self.backupvfs.makedir()
  128.         util.rename(self.filename(), self.backupfilename())
  129.  
  130.     def stat(self):
  131.         return self.vfs.stat(self.fname)
  132.  
  133.     def opener(self, mode='rb'):
  134.         try:
  135.             return self.vfs(self.fname, mode)
  136.         except IOError as err:
  137.             if err.errno != errno.ENOENT:
  138.                 raise
  139.             raise error.Abort(_("shelved change '%s' not found") % self.name)
  140.  
  141.     def applybundle(self):
  142.         fp = self.opener()
  143.         try:
  144.             gen = exchange.readbundle(self.repo.ui, fp, self.fname, self.vfs)
  145.             if not isinstance(gen, bundle2.unbundle20):
  146.                 gen.apply(self.repo, 'unshelve',
  147.                           'bundle:' + self.vfs.join(self.fname),
  148.                           targetphase=phases.secret)
  149.             if isinstance(gen, bundle2.unbundle20):
  150.                 bundle2.applybundle(self.repo, gen,
  151.                                     self.repo.currenttransaction(),
  152.                                     source='unshelve',
  153.                                     url='bundle:' + self.vfs.join(self.fname))
  154.         finally:
  155.             fp.close()
  156.  
  157.     def bundlerepo(self):
  158.         return bundlerepo.bundlerepository(self.repo.baseui, self.repo.root,
  159.                                            self.vfs.join(self.fname))
  160.     def writebundle(self, bases, node):
  161.         cgversion = changegroup.safeversion(self.repo)
  162.         if cgversion == '01':
  163.             btype = 'HG10BZ'
  164.             compression = None
  165.         else:
  166.             btype = 'HG20'
  167.             compression = 'BZ'
  168.  
  169.         cg = changegroup.changegroupsubset(self.repo, bases, [node], 'shelve',
  170.                                            version=cgversion)
  171.         bundle2.writebundle(self.ui, cg, self.fname, btype, self.vfs,
  172.                                 compression=compression)
  173.  
  174.     def writeobsshelveinfo(self, info):
  175.         obsshelvefile(self.vfs, self.fname).write(info)
  176.  
  177.     def readobsshelveinfo(self):
  178.         return obsshelvefile(self.vfs, self.fname).read()
  179.  
  180. class shelvedstate(object):
  181.     """Handle persistence during unshelving operations.
  182.  
  183.    Handles saving and restoring a shelved state. Ensures that different
  184.    versions of a shelved state are possible and handles them appropriately.
  185.    """
  186.     _version = 1
  187.     _filename = 'shelvedstate'
  188.     _keep = 'keep'
  189.     _nokeep = 'nokeep'
  190.     _obsbased = 'obsbased'
  191.     _traditional = 'traditional'
  192.     # colon is essential to differentiate from a real bookmark name
  193.     _noactivebook = ':no-active-bookmark'
  194.  
  195.     def __init__(self, ui, repo):
  196.         self.ui = ui
  197.         self.repo = repo
  198.  
  199.     @classmethod
  200.     def load(cls, ui, repo):
  201.         fp = repo.vfs(cls._filename)
  202.         try:
  203.             version = int(fp.readline().strip())
  204.  
  205.             if version != cls._version:
  206.                 raise error.Abort(_('this version of shelve is incompatible '
  207.                                    'with the version used in this repo'))
  208.             name = fp.readline().strip()
  209.             wctx = nodemod.bin(fp.readline().strip())
  210.             pendingctx = nodemod.bin(fp.readline().strip())
  211.             parents = [nodemod.bin(h) for h in fp.readline().split()]
  212.             nodestoprune = [nodemod.bin(h) for h in fp.readline().split()]
  213.             branchtorestore = fp.readline().strip()
  214.             keep = fp.readline().strip() == cls._keep
  215.             obsshelve = fp.readline().strip() == cls._obsbased
  216.             activebook = fp.readline().strip()
  217.         except (ValueError, TypeError) as err:
  218.             raise error.CorruptedState(str(err))
  219.         finally:
  220.             fp.close()
  221.  
  222.         try:
  223.             obj = cls(ui, repo)
  224.             obj.name = name
  225.             obj.wctx = repo[wctx]
  226.             obj.pendingctx = repo[pendingctx]
  227.             obj.parents = parents
  228.             obj.nodestoprune = nodestoprune
  229.             obj.branchtorestore = branchtorestore
  230.             obj.keep = keep
  231.             obj.obsshelve = obsshelve
  232.             obj.activebookmark = ''
  233.             if activebook != cls._noactivebook:
  234.                 obj.activebookmark = activebook
  235.         except error.RepoLookupError as err:
  236.             raise error.CorruptedState(str(err))
  237.  
  238.         return obj
  239.  
  240.     @classmethod
  241.     def save(cls, repo, name, originalwctx, pendingctx, nodestoprune,
  242.              branchtorestore, keep=False, obsshelve=False, activebook=''):
  243.         fp = repo.vfs(cls._filename, 'wb')
  244.         fp.write('%i\n' % cls._version)
  245.         fp.write('%s\n' % name)
  246.         fp.write('%s\n' % nodemod.hex(originalwctx.node()))
  247.         fp.write('%s\n' % nodemod.hex(pendingctx.node()))
  248.         fp.write('%s\n' %
  249.                  ' '.join([nodemod.hex(p) for p in repo.dirstate.parents()]))
  250.         fp.write('%s\n' %
  251.                  ' '.join([nodemod.hex(n) for n in nodestoprune]))
  252.         fp.write('%s\n' % branchtorestore)
  253.         fp.write('%s\n' % (cls._keep if keep else cls._nokeep))
  254.         fp.write('%s\n' % (cls._obsbased if obsshelve else cls._traditional))
  255.         fp.write('%s\n' % (activebook or cls._noactivebook))
  256.         fp.close()
  257.  
  258.     @classmethod
  259.     def clear(cls, repo):
  260.         util.unlinkpath(repo.join(cls._filename), ignoremissing=True)
  261.  
  262.     def prunenodes(self):
  263.         """Cleanup temporary nodes from the repo"""
  264.         if self.obsshelve:
  265.             unfi = self.repo.unfiltered()
  266.             relations = [(unfi[n], ()) for n in self.nodestoprune]
  267.             obsolete.createmarkers(self.repo, relations)
  268.         else:
  269.             repair.strip(self.ui, self.repo, self.nodestoprune, backup=False,
  270.                          topic='shelve')
  271.  
  272. def cleanupoldbackups(repo):
  273.     vfs = scmutil.vfs(repo.join(backupdir))
  274.     maxbackups = repo.ui.configint('shelve', 'maxbackups', 10)
  275.     hgfiles = [f for f in vfs.listdir()
  276.                if f.endswith('.' + patchextension)]
  277.     hgfiles = sorted([(vfs.stat(f).st_mtime, f) for f in hgfiles])
  278.     if 0 < maxbackups and maxbackups < len(hgfiles):
  279.         bordermtime = hgfiles[-maxbackups][0]
  280.     else:
  281.         bordermtime = None
  282.     for mtime, f in hgfiles[:len(hgfiles) - maxbackups]:
  283.         if mtime == bordermtime:
  284.             # keep it, because timestamp can't decide exact order of backups
  285.             continue
  286.         base = f[:-(1 + len(patchextension))]
  287.         for ext in shelvefileextensions:
  288.             try:
  289.                 vfs.unlink(base + '.' + ext)
  290.             except OSError as err:
  291.                 if err.errno != errno.ENOENT:
  292.                     raise
  293.  
  294. def _backupactivebookmark(repo):
  295.     activebookmark = repo._activebookmark
  296.     if activebookmark:
  297.         bookmarks.deactivate(repo)
  298.     return activebookmark
  299.  
  300. def _restoreactivebookmark(repo, mark):
  301.     if mark:
  302.         bookmarks.activate(repo, mark)
  303.  
  304. def _aborttransaction(repo):
  305.     '''Abort current transaction for shelve/unshelve, but keep dirstate
  306.    '''
  307.     tr = repo.currenttransaction()
  308.     repo.dirstate.savebackup(tr, suffix='.shelve')
  309.     tr.abort()
  310.     repo.dirstate.restorebackup(None, suffix='.shelve')
  311.  
  312. def createcmd(ui, repo, pats, opts):
  313.     """subcommand that creates a new shelve"""
  314.     with repo.wlock():
  315.         cmdutil.checkunfinished(repo)
  316.         return _docreatecmd(ui, repo, pats, opts)
  317.  
  318. def getshelvename(repo, parent, opts):
  319.     """Decide on the name this shelve is going to have"""
  320.     def gennames():
  321.         yield label
  322.         for i in xrange(1, 100):
  323.             yield '%s-%02d' % (label, i)
  324.     name = opts.get('name')
  325.     label = repo._activebookmark or parent.branch() or 'default'
  326.     # slashes aren't allowed in filenames, therefore we rename it
  327.     label = label.replace('/', '_')
  328.  
  329.     if name:
  330.         if shelvedfile(repo, name, patchextension).exists():
  331.             e = _("a shelved change named '%s' already exists") % name
  332.             raise error.Abort(e)
  333.     else:
  334.         for n in gennames():
  335.             if not shelvedfile(repo, n, patchextension).exists():
  336.                 name = n
  337.                 break
  338.         else:
  339.             raise error.Abort(_("too many shelved changes named '%s'") % label)
  340.  
  341.     # ensure we are not creating a subdirectory or a hidden file
  342.     if '/' in name or '\\' in name:
  343.         raise error.Abort(_('shelved change names may not contain slashes'))
  344.     if name.startswith('.'):
  345.         raise error.Abort(_("shelved change names may not start with '.'"))
  346.     return name
  347.  
  348. def mutableancestors(ctx):
  349.     """return all mutable ancestors for ctx (included)
  350.  
  351.    Much faster than the revset ancestors(ctx) & draft()"""
  352.     seen = set([nodemod.nullrev])
  353.     visit = collections.deque()
  354.     visit.append(ctx)
  355.     while visit:
  356.         ctx = visit.popleft()
  357.         yield ctx.node()
  358.         for parent in ctx.parents():
  359.             rev = parent.rev()
  360.             if rev not in seen:
  361.                 seen.add(rev)
  362.                 if parent.mutable():
  363.                     visit.append(parent)
  364.  
  365. def getcommitfunc(extra, interactive, editor=False):
  366.     def commitfunc(ui, repo, message, match, opts):
  367.         hasmq = util.safehasattr(repo, 'mq')
  368.         if hasmq:
  369.             saved, repo.mq.checkapplied = repo.mq.checkapplied, False
  370.         try:
  371.             overrides = {('phases', 'new-commit'): phases.secret}
  372.             with repo.ui.configoverride(overrides):
  373.                 editor_ = False
  374.                 if editor:
  375.                     editor_ = cmdutil.getcommiteditor(editform='shelve.shelve',
  376.                                                       **opts)
  377.                 return repo.commit(message, shelveuser, opts.get('date'),
  378.                                    match, editor=editor_, extra=extra)
  379.         finally:
  380.             if hasmq:
  381.                 repo.mq.checkapplied = saved
  382.  
  383.     def interactivecommitfunc(ui, repo, *pats, **opts):
  384.         match = scmutil.match(repo['.'], pats, {})
  385.         message = opts['message']
  386.         return commitfunc(ui, repo, message, match, opts)
  387.  
  388.     return interactivecommitfunc if interactive else commitfunc
  389.  
  390. def _nothingtoshelvemessaging(ui, repo, pats, opts):
  391.     stat = repo.status(match=scmutil.match(repo[None], pats, opts))
  392.     if stat.deleted:
  393.         ui.status(_("nothing changed (%d missing files, see "
  394.                     "'hg status')\n") % len(stat.deleted))
  395.     else:
  396.         ui.status(_("nothing changed\n"))
  397.  
  398. def _shelvecreatedcommit(ui, repo, node, name, tr):
  399.     if isobsshelve(repo, ui):
  400.         shelvedfile(repo, name, 'oshelve').writeobsshelveinfo({
  401.             'node': nodemod.hex(node)
  402.         })
  403.     else:
  404.         bases = list(mutableancestors(repo[node]))
  405.         shelvedfile(repo, name, 'hg').writebundle(bases, node)
  406.     cmdutil.export(repo.unfiltered(), [node],
  407.                    fp=shelvedfile(repo, name, patchextension).opener('wb'),
  408.                    opts=mdiff.diffopts(git=True))
  409.  
  410. def _includeunknownfiles(repo, pats, opts, extra):
  411.     s = repo.status(match=scmutil.match(repo[None], pats, opts),
  412.                     unknown=True)
  413.     if s.unknown:
  414.         extra['shelve_unknown'] = '\0'.join(s.unknown)
  415.         repo[None].add(s.unknown)
  416.  
  417. def _finishshelve(ui, repo, tr, node, activebookmark):
  418.     if activebookmark:
  419.         bookmarks.activate(repo, activebookmark)
  420.     if isobsshelve(repo, ui):
  421.         obsolete.createmarkers(repo, [(repo.unfiltered()[node], ())])
  422.         tr.close()
  423.         tr.release()
  424.     else:
  425.         _aborttransaction(repo)
  426.  
  427. def _docreatecmd(ui, repo, pats, opts):
  428.     wctx = repo[None]
  429.     parents = wctx.parents()
  430.     if len(parents) > 1:
  431.         raise error.Abort(_('cannot shelve while merging'))
  432.     parent = parents[0]
  433.     origbranch = wctx.branch()
  434.  
  435.     if parent.node() != nodemod.nullid:
  436.         desc = "changes to: %s" % parent.description().split('\n', 1)[0]
  437.     else:
  438.         desc = '(changes in empty repository)'
  439.  
  440.     if not opts.get('message'):
  441.         opts['message'] = desc
  442.  
  443.     lock = tr = activebookmark = None
  444.     _obsinhibit = _notset = object()
  445.     try:
  446.         lock = repo.lock()
  447.         if util.safehasattr(repo, '_obsinhibit'):
  448.             _obsinhibit = getattr(repo, '_obsinhibit')
  449.             del repo._obsinhibit
  450.  
  451.         # depending on whether shelve is traditional or
  452.         # obsolescense-based, we either abort or commit this
  453.         # transaction in the end. If we abort it, we don't
  454.         # want to print anything to stderr
  455.         report = None if isobsshelve(repo, ui) else (lambda x: None)
  456.         tr = repo.transaction('commit', report=report)
  457.  
  458.         interactive = opts.get('interactive', False)
  459.         includeunknown = (opts.get('unknown', False) and
  460.                           not opts.get('addremove', False))
  461.  
  462.         name = getshelvename(repo, parent, opts)
  463.         activebookmark = _backupactivebookmark(repo)
  464.         extra = {}
  465.         if includeunknown:
  466.             _includeunknownfiles(repo, pats, opts, extra)
  467.  
  468.         if _iswctxonnewbranch(repo) and not _isbareshelve(pats, opts):
  469.             # In non-bare shelve we don't store newly created branch
  470.             # at bundled commit
  471.             repo.dirstate.setbranch(repo['.'].branch())
  472.  
  473.         commitfunc = getcommitfunc(extra, interactive, editor=True)
  474.         if not interactive:
  475.             node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
  476.         else:
  477.             node = cmdutil.dorecord(ui, repo, commitfunc, None,
  478.                                     False, cmdutil.recordfilter, *pats,
  479.                                     **opts)
  480.         if not node:
  481.             _nothingtoshelvemessaging(ui, repo, pats, opts)
  482.             return 1
  483.  
  484.         _shelvecreatedcommit(ui, repo, node, name, tr)
  485.  
  486.         if ui.formatted():
  487.             desc = util.ellipsis(desc, ui.termwidth())
  488.         ui.status(_('shelved as %s\n') % name)
  489.         # current wc parent may be already obsolete becuase
  490.         # it might have been created previously and shelve just
  491.         # reuses it
  492.         hg.update(repo.unfiltered(), parent.node())
  493.         if origbranch != repo['.'].branch() and not _isbareshelve(pats, opts):
  494.             repo.dirstate.setbranch(origbranch)
  495.  
  496.         _finishshelve(ui, repo, tr, node, activebookmark)
  497.     finally:
  498.         _restoreactivebookmark(repo, activebookmark)
  499.         if _obsinhibit is not _notset:
  500.             repo._obsinhibit = _obsinhibit
  501.         lockmod.release(tr, lock)
  502.  
  503. def _isbareshelve(pats, opts):
  504.     return (not pats
  505.             and not opts.get('interactive', False)
  506.             and not opts.get('include', False)
  507.             and not opts.get('exclude', False))
  508.  
  509. def _iswctxonnewbranch(repo):
  510.     return repo[None].branch() != repo['.'].branch()
  511.  
  512. def cleanupcmd(ui, repo):
  513.     """subcommand that deletes all shelves"""
  514.  
  515.     with repo.wlock():
  516.         for (name, _type) in repo.vfs.readdir(shelvedir):
  517.             suffix = name.rsplit('.', 1)[-1]
  518.             if suffix in shelvefileextensions:
  519.                 shelvedfile(repo, name).movetobackup()
  520.             cleanupoldbackups(repo)
  521.  
  522. def deletecmd(ui, repo, pats):
  523.     """subcommand that deletes a specific shelve"""
  524.     if not pats:
  525.         raise error.Abort(_('no shelved changes specified!'))
  526.     with repo.wlock():
  527.         try:
  528.             for name in pats:
  529.                 for suffix in shelvefileextensions:
  530.                     shfile = shelvedfile(repo, name, suffix)
  531.                     # patch file is necessary, as it should
  532.                     # be present for any kind of shelve,
  533.                     # but the .hg file is optional as in future we
  534.                     # will add obsolete shelve with does not create a
  535.                     # bundle
  536.                     if shfile.exists() or suffix == patchextension:
  537.                         shfile.movetobackup()
  538.             cleanupoldbackups(repo)
  539.         except OSError as err:
  540.             if err.errno != errno.ENOENT:
  541.                 raise
  542.             raise error.Abort(_("shelved change '%s' not found") % name)
  543.  
  544. def listshelves(repo):
  545.     """return all shelves in repo as list of (time, filename)"""
  546.     try:
  547.         names = repo.vfs.readdir(shelvedir)
  548.     except OSError as err:
  549.         if err.errno != errno.ENOENT:
  550.             raise
  551.         return []
  552.     info = []
  553.     for (name, _type) in names:
  554.         pfx, sfx = name.rsplit('.', 1)
  555.         if not pfx or sfx != patchextension:
  556.             continue
  557.         st = shelvedfile(repo, name).stat()
  558.         info.append((st.st_mtime, shelvedfile(repo, pfx).filename()))
  559.     return sorted(info, reverse=True)
  560.  
  561. def listcmd(ui, repo, pats, opts):
  562.     """subcommand that displays the list of shelves"""
  563.     pats = set(pats)
  564.     width = 80
  565.     if not ui.plain():
  566.         width = ui.termwidth()
  567.     namelabel = 'shelve.newest'
  568.     for mtime, name in listshelves(repo):
  569.         sname = util.split(name)[1]
  570.         if pats and sname not in pats:
  571.             continue
  572.         ui.write(sname, label=namelabel)
  573.         namelabel = 'shelve.name'
  574.         if ui.quiet:
  575.             ui.write('\n')
  576.             continue
  577.         ui.write(' ' * (16 - len(sname)))
  578.         used = 16
  579.         age = '(%s)' % templatefilters.age(util.makedate(mtime), abbrev=True)
  580.         ui.write(age, label='shelve.age')
  581.         ui.write(' ' * (12 - len(age)))
  582.         used += 12
  583.         with open(name + '.' + patchextension, 'rb') as fp:
  584.             while True:
  585.                 line = fp.readline()
  586.                 if not line:
  587.                     break
  588.                 if not line.startswith('#'):
  589.                     desc = line.rstrip()
  590.                     if ui.formatted():
  591.                         desc = util.ellipsis(desc, width - used)
  592.                     ui.write(desc)
  593.                     break
  594.             ui.write('\n')
  595.             if not (opts['patch'] or opts['stat']):
  596.                 continue
  597.             difflines = fp.readlines()
  598.             if opts['patch']:
  599.                 for chunk, label in patch.difflabel(iter, difflines):
  600.                     ui.write(chunk, label=label)
  601.             if opts['stat']:
  602.                 for chunk, label in patch.diffstatui(difflines, width=width):
  603.                     ui.write(chunk, label=label)
  604.  
  605. def singlepatchcmds(ui, repo, pats, opts, subcommand):
  606.     """subcommand that displays a single shelf"""
  607.     if len(pats) != 1:
  608.         raise error.Abort(_("--%s expects a single shelf") % subcommand)
  609.     shelfname = pats[0]
  610.  
  611.     if not shelvedfile(repo, shelfname, patchextension).exists():
  612.         raise error.Abort(_("cannot find shelf %s") % shelfname)
  613.  
  614.     listcmd(ui, repo, pats, opts)
  615.  
  616. def checkparents(repo, state):
  617.     """check parent while resuming an unshelve"""
  618.     if state.parents != repo.dirstate.parents():
  619.         raise error.Abort(_('working directory parents do not match unshelve '
  620.                            'state'))
  621.  
  622. def pathtofiles(repo, files):
  623.     cwd = repo.getcwd()
  624.     return [repo.pathto(f, cwd) for f in files]
  625.  
  626. def unshelveabort(ui, repo, state, opts):
  627.     """subcommand that abort an in-progress unshelve"""
  628.     with repo.lock():
  629.         try:
  630.             checkparents(repo, state)
  631.  
  632.             util.rename(repo.join('unshelverebasestate'),
  633.                         repo.join('rebasestate'))
  634.             try:
  635.                 rebase.rebase(ui, repo, **{
  636.                     'abort' : True
  637.                 })
  638.             except Exception:
  639.                 util.rename(repo.join('rebasestate'),
  640.                             repo.join('unshelverebasestate'))
  641.                 raise
  642.  
  643.             mergefiles(ui, repo, state.wctx, state.pendingctx)
  644.             state.prunenodes()
  645.         finally:
  646.             shelvedstate.clear(repo)
  647.             ui.warn(_("unshelve of '%s' aborted\n") % state.name)
  648.  
  649. def mergefiles(ui, repo, wctx, shelvectx):
  650.     """updates to wctx and merges the changes from shelvectx into the
  651.    dirstate."""
  652.     with ui.configoverride({('ui', 'quiet'): True}):
  653.         hg.update(repo, wctx.node())
  654.         files = []
  655.         files.extend(shelvectx.files())
  656.         files.extend(shelvectx.parents()[0].files())
  657.  
  658.         # revert will overwrite unknown files, so move them out of the way
  659.         for file in repo.status(unknown=True).unknown:
  660.             if file in files:
  661.                 util.rename(file, scmutil.origpath(ui, repo, file))
  662.         ui.pushbuffer(True)
  663.         cmdutil.revert(ui, repo, shelvectx, repo.dirstate.parents(),
  664.                        *pathtofiles(repo, files),
  665.                        **{'no_backup': True})
  666.         ui.popbuffer()
  667.  
  668. def restorebranch(ui, repo, branchtorestore):
  669.     if branchtorestore and branchtorestore != repo.dirstate.branch():
  670.         repo.dirstate.setbranch(branchtorestore)
  671.         ui.status(_('marked working directory as branch %s\n')
  672.                   % branchtorestore)
  673.  
  674. def unshelvecleanup(ui, repo, name, opts):
  675.     """remove related files after an unshelve"""
  676.     if not opts.get('keep'):
  677.         for filetype in shelvefileextensions:
  678.             shfile = shelvedfile(repo, name, filetype)
  679.             if shfile.exists():
  680.                 shfile.movetobackup()
  681.         cleanupoldbackups(repo)
  682.  
  683. def unshelvecontinue(ui, repo, state, opts):
  684.     """subcommand to continue an in-progress unshelve"""
  685.     # We're finishing off a merge. First parent is our original
  686.     # parent, second is the temporary "fake" commit we're unshelving.
  687.     with repo.lock():
  688.         checkparents(repo, state)
  689.         ms = merge.mergestate.read(repo)
  690.         if [f for f in ms if ms[f] == 'u']:
  691.             raise error.Abort(
  692.                 _("unresolved conflicts, can't continue"),
  693.                 hint=_("see 'hg resolve', then 'hg unshelve --continue'"))
  694.  
  695.         util.rename(repo.join('unshelverebasestate'),
  696.                     repo.join('rebasestate'))
  697.         try:
  698.             # if shelve is obs-based, we want rebase to be able
  699.             # to create markers to already-obsoleted commits
  700.             _repo = repo.unfiltered() if state.obsshelve else repo
  701.             with ui.configoverride({('experimental', 'rebaseskipobsolete'):
  702.                                     'off'}, 'unshelve'):
  703.                 rebase.rebase(ui, _repo, **{
  704.                     'continue' : True,
  705.                     })
  706.         except Exception:
  707.             util.rename(repo.join('rebasestate'),
  708.                         repo.join('unshelverebasestate'))
  709.             raise
  710.  
  711.         shelvectx = repo['tip']
  712.         if not shelvectx in state.pendingctx.children():
  713.             # rebase was a no-op, so it produced no child commit
  714.             shelvectx = state.pendingctx
  715.         else:
  716.             # only strip the shelvectx if the rebase produced it
  717.             state.nodestoprune.append(shelvectx.node())
  718.  
  719.         mergefiles(ui, repo, state.wctx, shelvectx)
  720.         restorebranch(ui, repo, state.branchtorestore)
  721.  
  722.         state.prunenodes()
  723.         _restoreactivebookmark(repo, state.activebookmark)
  724.         shelvedstate.clear(repo)
  725.         unshelvecleanup(ui, repo, state.name, opts)
  726.         ui.status(_("unshelve of '%s' complete\n") % state.name)
  727.  
  728. def _commitworkingcopychanges(ui, repo, opts, tmpwctx):
  729.     """Temporarily commit working copy changes before moving unshelve commit"""
  730.     # Store pending changes in a commit and remember added in case a shelve
  731.     # contains unknown files that are part of the pending change
  732.     s = repo.status()
  733.     addedbefore = frozenset(s.added)
  734.     if not (s.modified or s.added or s.removed or s.deleted):
  735.         return tmpwctx, addedbefore
  736.     ui.status(_("temporarily committing pending changes "
  737.                 "(restore with 'hg unshelve --abort')\n"))
  738.     commitfunc = getcommitfunc(extra=None, interactive=False,
  739.                                editor=False)
  740.     tempopts = {}
  741.     tempopts['message'] = "pending changes temporary commit"
  742.     tempopts['date'] = opts.get('date')
  743.     with ui.configoverride({('ui', 'quiet'): True}):
  744.         node = cmdutil.commit(ui, repo, commitfunc, [], tempopts)
  745.     tmpwctx = repo[node]
  746.     ui.debug("temporary working copy commit: %s:%s\n" %
  747.              (tmpwctx.rev(), nodemod.short(node)))
  748.     return tmpwctx, addedbefore
  749.  
  750. def _unshelverestorecommit(ui, repo, basename, obsshelve):
  751.     """Recreate commit in the repository during the unshelve"""
  752.     with ui.configoverride({('ui', 'quiet'): True}):
  753.         if obsshelve:
  754.             md = shelvedfile(repo, basename, 'oshelve').readobsshelveinfo()
  755.             shelvenode = nodemod.bin(md['node'])
  756.             repo = repo.unfiltered()
  757.             shelvectx = repo[shelvenode]
  758.         else:
  759.             shelvedfile(repo, basename, 'hg').applybundle()
  760.             shelvectx = repo['tip']
  761.     return repo, shelvectx
  762.  
  763. def _rebaserestoredcommit(ui, repo, opts, tr, oldtiprev, basename, pctx,
  764.                           tmpwctx, shelvectx, branchtorestore, obsshelve,
  765.                           activebookmark):
  766.     """Rebase restored commit from its original location to a destination"""
  767.     # If the shelve is not immediately on top of the commit
  768.     # we'll be merging with, rebase it to be on top.
  769.     if tmpwctx.node() == shelvectx.parents()[0].node():
  770.         # shelvectx is immediately on top of the tmpwctx
  771.         return shelvectx
  772.  
  773.     # we need a new commit extra every time we perform a rebase to ensure
  774.     # that "nothing to rebase" does not happen with obs-based shelve
  775.     # "nothing to rebase" means that tip does not point to a "successor"
  776.     # commit after a rebase and we have no way to learn which commit
  777.     # should be a "shelvectx". this is a dirty hack until we implement
  778.     # some way to learn the results of rebase operation, other than
  779.     # text output and return code
  780.     def extrafn(ctx, extra):
  781.         extra['unshelve_time'] = str(time.time())
  782.  
  783.     ui.status(_('rebasing shelved changes\n'))
  784.     try:
  785.         # we only want keep to be true if shelve is traditional, since
  786.         # for obs-based shelve, rebase will also be obs-based and
  787.         # markers created help us track the relationship between shelvectx
  788.         # and its new version
  789.         rebase.rebase(ui, repo, **{
  790.             'rev': [shelvectx.rev()],
  791.             'dest': str(tmpwctx.rev()),
  792.             'keep': not obsshelve,
  793.             'tool': opts.get('tool', ''),
  794.             'extrafn': extrafn if obsshelve else None
  795.         })
  796.     except error.InterventionRequired:
  797.         tr.close()
  798.  
  799.         nodestoprune = [repo.changelog.node(rev)
  800.                         for rev in xrange(oldtiprev, len(repo))]
  801.         shelvedstate.save(repo, basename, pctx, tmpwctx, nodestoprune,
  802.                           branchtorestore, opts.get('keep'), obsshelve,
  803.                           activebookmark)
  804.  
  805.         util.rename(repo.join('rebasestate'),
  806.                     repo.join('unshelverebasestate'))
  807.         raise error.InterventionRequired(
  808.             _("unresolved conflicts (see 'hg resolve', then "
  809.               "'hg unshelve --continue')"))
  810.  
  811.     # refresh ctx after rebase completes
  812.     shelvectx = repo['tip']
  813.  
  814.     if not shelvectx in tmpwctx.children():
  815.         # rebase was a no-op, so it produced no child commit
  816.         shelvectx = tmpwctx
  817.     return shelvectx
  818.  
  819. def _forgetunknownfiles(repo, shelvectx, addedbefore):
  820.     # Forget any files that were unknown before the shelve, unknown before
  821.     # unshelve started, but are now added.
  822.     shelveunknown = shelvectx.extra().get('shelve_unknown')
  823.     if not shelveunknown:
  824.         return
  825.     shelveunknown = frozenset(shelveunknown.split('\0'))
  826.     addedafter = frozenset(repo.status().added)
  827.     toforget = (addedafter & shelveunknown) - addedbefore
  828.     repo[None].forget(toforget)
  829.  
  830. def _finishunshelve(repo, oldtiprev, tr, obsshelve, activebookmark):
  831.     _restoreactivebookmark(repo, activebookmark)
  832.     if obsshelve:
  833.         tr.close()
  834.         return
  835.     # The transaction aborting will strip all the commits for us,
  836.     # but it doesn't update the inmemory structures, so addchangegroup
  837.     # hooks still fire and try to operate on the missing commits.
  838.     # Clean up manually to prevent this.
  839.     repo.unfiltered().changelog.strip(oldtiprev, tr)
  840.     _aborttransaction(repo)
  841.  
  842. def _obsoleteredundantnodes(repo, tr, pctx, shelvectx, tmpwctx):
  843.     # order is important in the list of [shelvectx, tmpwctx] below
  844.     # some nodes may already be obsolete
  845.     unfi = repo.unfiltered()
  846.     nodestoobsolete = filter(lambda x: x != pctx, [shelvectx, tmpwctx])
  847.     seen = set()
  848.     relations = []
  849.     for nto in nodestoobsolete:
  850.         if nto in seen:
  851.             continue
  852.         seen.add(nto)
  853.         relations.append((unfi[nto.rev()], ()))
  854.     obsolete.createmarkers(unfi, relations)
  855.  
  856. @command('unshelve',
  857.          [('a', 'abort', None,
  858.            _('abort an incomplete unshelve operation')),
  859.           ('c', 'continue', None,
  860.            _('continue an incomplete unshelve operation')),
  861.           ('k', 'keep', None,
  862.            _('keep shelve after unshelving')),
  863.           ('t', 'tool', '', _('specify merge tool')),
  864.           ('', 'date', '',
  865.            _('set date for temporary commits (DEPRECATED)'), _('DATE'))],
  866.          _('hg unshelve [SHELVED]'))
  867. def unshelve(ui, repo, *shelved, **opts):
  868.     """restore a shelved change to the working directory
  869.  
  870.    This command accepts an optional name of a shelved change to
  871.    restore. If none is given, the most recent shelved change is used.
  872.  
  873.    If a shelved change is applied successfully, the bundle that
  874.    contains the shelved changes is moved to a backup location
  875.    (.hg/shelve-backup).
  876.  
  877.    Since you can restore a shelved change on top of an arbitrary
  878.    commit, it is possible that unshelving will result in a conflict
  879.    between your changes and the commits you are unshelving onto. If
  880.    this occurs, you must resolve the conflict, then use
  881.    ``--continue`` to complete the unshelve operation. (The bundle
  882.    will not be moved until you successfully complete the unshelve.)
  883.  
  884.    (Alternatively, you can use ``--abort`` to abandon an unshelve
  885.    that causes a conflict. This reverts the unshelved changes, and
  886.    leaves the bundle in place.)
  887.  
  888.    If bare shelved change(when no files are specified, without interactive,
  889.    include and exclude option) was done on newly created branch it would
  890.    restore branch information to the working directory.
  891.  
  892.    After a successful unshelve, the shelved changes are stored in a
  893.    backup directory. Only the N most recent backups are kept. N
  894.    defaults to 10 but can be overridden using the ``shelve.maxbackups``
  895.    configuration option.
  896.  
  897.    .. container:: verbose
  898.  
  899.       Timestamp in seconds is used to decide order of backups. More
  900.       than ``maxbackups`` backups are kept, if same timestamp
  901.       prevents from deciding exact order of them, for safety.
  902.    """
  903.     with repo.wlock():
  904.         return _dounshelve(ui, repo, *shelved, **opts)
  905.  
  906. def _dounshelve(ui, repo, *shelved, **opts):
  907.     abortf = opts.get('abort')
  908.     continuef = opts.get('continue')
  909.     if not abortf and not continuef:
  910.         cmdutil.checkunfinished(repo)
  911.  
  912.     if abortf or continuef:
  913.         if abortf and continuef:
  914.             raise error.Abort(_('cannot use both abort and continue'))
  915.         if shelved:
  916.             raise error.Abort(_('cannot combine abort/continue with '
  917.                                'naming a shelved change'))
  918.         if abortf and opts.get('tool', False):
  919.             ui.warn(_('tool option will be ignored\n'))
  920.  
  921.         try:
  922.             state = shelvedstate.load(ui, repo)
  923.             if opts.get('keep') is None:
  924.                 opts['keep'] = state.keep
  925.         except IOError as err:
  926.             if err.errno != errno.ENOENT:
  927.                 raise
  928.             cmdutil.wrongtooltocontinue(repo, _('unshelve'))
  929.         except error.CorruptedState as err:
  930.             ui.debug(str(err) + '\n')
  931.             if continuef:
  932.                 msg = _('corrupted shelved state file')
  933.                 hint = _('please run hg unshelve --abort to abort unshelve '
  934.                          'operation')
  935.                 raise error.Abort(msg, hint=hint)
  936.             elif abortf:
  937.                 msg = _('could not read shelved state file, your working copy '
  938.                         'may be in an unexpected state\nplease update to some '
  939.                         'commit\n')
  940.                 ui.warn(msg)
  941.                 shelvedstate.clear(repo)
  942.             return
  943.  
  944.         if abortf:
  945.             return unshelveabort(ui, repo, state, opts)
  946.         elif continuef:
  947.             return unshelvecontinue(ui, repo, state, opts)
  948.     elif len(shelved) > 1:
  949.         raise error.Abort(_('can only unshelve one change at a time'))
  950.     elif not shelved:
  951.         shelved = listshelves(repo)
  952.         if not shelved:
  953.             raise error.Abort(_('no shelved changes to apply!'))
  954.         basename = util.split(shelved[0][1])[1]
  955.         ui.status(_("unshelving change '%s'\n") % basename)
  956.     else:
  957.         basename = shelved[0]
  958.  
  959.     if not shelvedfile(repo, basename, patchextension).exists():
  960.         raise error.Abort(_("shelved change '%s' not found") % basename)
  961.  
  962.     lock = tr = None
  963.     obsshelve = isobsshelve(repo, ui)
  964.     obsshelvedfile = shelvedfile(repo, basename, 'oshelve')
  965.     if obsshelve and not obsshelvedfile.exists():
  966.         # although we can unshelve a obs-based shelve technically,
  967.         # this particular shelve was created using a traditional way
  968.         obsshelve = False
  969.         ui.note(_("falling back to traditional unshelve since "
  970.                   "shelve was traditional"))
  971.     try:
  972.         lock = repo.lock()
  973.         tr = repo.transaction('unshelve', report=lambda x: None)
  974.         oldtiprev = len(repo)
  975.  
  976.         pctx = repo['.']
  977.         tmpwctx = pctx
  978.         # The goal is to have a commit structure like so:
  979.         # ...-> pctx -> tmpwctx -> shelvectx
  980.         # where tmpwctx is an optional commit with the user's pending changes
  981.         # and shelvectx is the unshelved changes. Then we merge it all down
  982.         # to the original pctx.
  983.  
  984.         activebookmark = _backupactivebookmark(repo)
  985.         tmpwctx, addedbefore = _commitworkingcopychanges(ui, repo, opts,
  986.                                                          tmpwctx)
  987.  
  988.         repo, shelvectx = _unshelverestorecommit(ui, repo, basename, obsshelve)
  989.  
  990.         branchtorestore = ''
  991.         if shelvectx.branch() != shelvectx.p1().branch():
  992.             branchtorestore = shelvectx.branch()
  993.  
  994.         rebaseconfigoverrides = {('ui', 'forcemerge'): opts.get('tool', ''),
  995.                                  ('experimental', 'rebaseskipobsolete'): 'off'}
  996.         with ui.configoverride(rebaseconfigoverrides, 'unshelve'):
  997.             shelvectx = _rebaserestoredcommit(ui, repo, opts, tr, oldtiprev,
  998.                                               basename, pctx, tmpwctx,
  999.                                               shelvectx, branchtorestore,
  1000.                                               obsshelve, activebookmark)
  1001.             mergefiles(ui, repo, pctx, shelvectx)
  1002.         restorebranch(ui, repo, branchtorestore)
  1003.         _forgetunknownfiles(repo, shelvectx, addedbefore)
  1004.  
  1005.         if obsshelve:
  1006.             _obsoleteredundantnodes(repo, tr, pctx, shelvectx, tmpwctx)
  1007.  
  1008.         shelvedstate.clear(repo)
  1009.         _finishunshelve(repo, oldtiprev, tr, obsshelve, activebookmark)
  1010.         unshelvecleanup(ui, repo, basename, opts)
  1011.     finally:
  1012.         if tr:
  1013.             tr.release()
  1014.         lockmod.release(lock)
  1015.  
  1016. @command('shelve',
  1017.          [('A', 'addremove', None,
  1018.            _('mark new/missing files as added/removed before shelving')),
  1019.           ('u', 'unknown', None,
  1020.            _('store unknown files in the shelve')),
  1021.           ('', 'cleanup', None,
  1022.            _('delete all shelved changes')),
  1023.           ('', 'date', '',
  1024.            _('shelve with the specified commit date'), _('DATE')),
  1025.           ('d', 'delete', None,
  1026.            _('delete the named shelved change(s)')),
  1027.           ('e', 'edit', False,
  1028.            _('invoke editor on commit messages')),
  1029.           ('l', 'list', None,
  1030.            _('list current shelves')),
  1031.           ('m', 'message', '',
  1032.            _('use text as shelve message'), _('TEXT')),
  1033.           ('n', 'name', '',
  1034.            _('use the given name for the shelved commit'), _('NAME')),
  1035.           ('p', 'patch', None,
  1036.            _('show patch')),
  1037.           ('i', 'interactive', None,
  1038.            _('interactive mode, only works while creating a shelve')),
  1039.           ('', 'stat', None,
  1040.            _('output diffstat-style summary of changes'))] + commands.walkopts,
  1041.          _('hg shelve [OPTION]... [FILE]...'))
  1042. def shelvecmd(ui, repo, *pats, **opts):
  1043.     '''save and set aside changes from the working directory
  1044.  
  1045.    Shelving takes files that "hg status" reports as not clean, saves
  1046.    the modifications to a bundle (a shelved change), and reverts the
  1047.    files so that their state in the working directory becomes clean.
  1048.  
  1049.    To restore these changes to the working directory, using "hg
  1050.    unshelve"; this will work even if you switch to a different
  1051.    commit.
  1052.  
  1053.    When no files are specified, "hg shelve" saves all not-clean
  1054.    files. If specific files or directories are named, only changes to
  1055.    those files are shelved.
  1056.  
  1057.    In bare shelve (when no files are specified, without interactive,
  1058.    include and exclude option), shelving remembers information if the
  1059.    working directory was on newly created branch, in other words working
  1060.    directory was on different branch than its first parent. In this
  1061.    situation unshelving restores branch information to the working directory.
  1062.  
  1063.    Each shelved change has a name that makes it easier to find later.
  1064.    The name of a shelved change defaults to being based on the active
  1065.    bookmark, or if there is no active bookmark, the current named
  1066.    branch.  To specify a different name, use ``--name``.
  1067.  
  1068.    To see a list of existing shelved changes, use the ``--list``
  1069.    option. For each shelved change, this will print its name, age,
  1070.    and description; use ``--patch`` or ``--stat`` for more details.
  1071.  
  1072.    To delete specific shelved changes, use ``--delete``. To delete
  1073.    all shelved changes, use ``--cleanup``.
  1074.    '''
  1075.     allowables = [
  1076.         ('addremove', set(['create'])), # 'create' is pseudo action
  1077.         ('unknown', set(['create'])),
  1078.         ('cleanup', set(['cleanup'])),
  1079. #       ('date', set(['create'])), # ignored for passing '--date "0 0"' in tests
  1080.         ('delete', set(['delete'])),
  1081.         ('edit', set(['create'])),
  1082.         ('list', set(['list'])),
  1083.         ('message', set(['create'])),
  1084.         ('name', set(['create'])),
  1085.         ('patch', set(['patch', 'list'])),
  1086.         ('stat', set(['stat', 'list'])),
  1087.     ]
  1088.     def checkopt(opt):
  1089.         if opts.get(opt):
  1090.             for i, allowable in allowables:
  1091.                 if opts[i] and opt not in allowable:
  1092.                     raise error.Abort(_("options '--%s' and '--%s' may not be "
  1093.                                        "used together") % (opt, i))
  1094.             return True
  1095.     if checkopt('cleanup'):
  1096.         if pats:
  1097.             raise error.Abort(_("cannot specify names when using '--cleanup'"))
  1098.         return cleanupcmd(ui, repo)
  1099.     elif checkopt('delete'):
  1100.         return deletecmd(ui, repo, pats)
  1101.     elif checkopt('list'):
  1102.         return listcmd(ui, repo, pats, opts)
  1103.     elif checkopt('patch'):
  1104.         return singlepatchcmds(ui, repo, pats, opts, subcommand='patch')
  1105.     elif checkopt('stat'):
  1106.         return singlepatchcmds(ui, repo, pats, opts, subcommand='stat')
  1107.     else:
  1108.         return createcmd(ui, repo, pats, opts)
  1109.  
  1110. def extsetup(ui):
  1111.     cmdutil.unfinishedstates.append(
  1112.         [shelvedstate._filename, False, False,
  1113.          _('unshelve already in progress'),
  1114.          _("use 'hg unshelve --continue' or 'hg unshelve --abort'")])
  1115.     cmdutil.afterresolvedstates.append(
  1116.         [shelvedstate._filename, _('hg unshelve --continue')])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement