evolve: improves readme wording
(yes I just pushed the other version…)
# Copyright 2011 Peter Arrenbrecht <peter.arrenbrecht@gmail.com># Logilab SA <contact@logilab.fr># Pierre-Yves David <pierre-yves.david@ens-lyon.org># Patrick Mezard <patrick@mezard.eu>## This software may be used and distributed according to the terms of the# GNU General Public License version 2 or any later version.'''extends Mercurial feature related to Changeset EvolutionThis extension provides several commands to mutate history and deal withissues it may raise.It also: - enables the "Changeset Obsolescence" feature of mercurial, - alters core commands and extensions that rewrite history to use this feature, - improves some aspect of the early implementation in 2.3'''testedwith='2.7 2.7.1 2.7.2 2.8 2.8.1 2.8.2 2.9 2.9.1 2.9.2 3.0'buglink='https://bitbucket.org/marmoute/mutable-history/issues'importsysimportrandomimportmercurialfrommercurialimportutiltry:frommercurialimportobsoleteifnotobsolete._enabled:obsolete._enabled=Truefrommercurialimportbookmarksbookmarks.bmstoreexcept(ImportError,AttributeError):raiseutil.Abort('Your Mercurial is too old for this version of Evolve',hint='requires version >> 2.4.x')frommercurialimportbookmarksfrommercurialimportcmdutilfrommercurialimportcommandsfrommercurialimportcontextfrommercurialimportcopiesfrommercurialimporterrorfrommercurialimportextensionsfrommercurialimporthgfrommercurialimportlockaslockmodfrommercurialimportmergefrommercurialimportnodefrommercurialimportphasesfrommercurialimportrevsetfrommercurialimportscmutilfrommercurialimporttemplatekwfrommercurial.i18nimport_frommercurial.commandsimportwalkopts,commitopts,commitopts2frommercurial.nodeimportnullid# This extension contains the following code## - Extension Helper code# - Obsolescence cache# - ...# - Older format compat######################################################################## Extension helper ########################################################################classexthelper(object):"""Helper for modular extension setup A single helper should be instanciated for each extension. Helper methods are then used as decorator for various purpose. All decorators return the original function and may be chained. """def__init__(self):self._uicallables=[]self._extcallables=[]self._repocallables=[]self._revsetsymbols=[]self._templatekws=[]self._commandwrappers=[]self._extcommandwrappers=[]self._functionwrappers=[]self._duckpunchers=[]deffinal_uisetup(self,ui):"""Method to be used as the extension uisetup The following operations belong here: - Changes to ui.__class__ . The ui object that will be used to run the command has not yet been created. Changes made here will affect ui objects created after this, and in particular the ui that will be passed to runcommand - Command wraps (extensions.wrapcommand) - Changes that need to be visible to other extensions: because initialization occurs in phases (all extensions run uisetup, then all run extsetup), a change made here will be visible to other extensions during extsetup - Monkeypatch or wrap function (extensions.wrapfunction) of dispatch module members - Setup of pre-* and post-* hooks - pushkey setup """forcont,funcname,funcinself._duckpunchers:setattr(cont,funcname,func)forcommand,wrapperinself._commandwrappers:extensions.wrapcommand(commands.table,command,wrapper)forcont,funcname,wrapperinself._functionwrappers:extensions.wrapfunction(cont,funcname,wrapper)forcinself._uicallables:c(ui)deffinal_extsetup(self,ui):"""Method to be used as a the extension extsetup The following operations belong here: - Changes depending on the status of other extensions. (if extensions.find('mq')) - Add a global option to all commands - Register revset functions """knownexts={}forname,symbolinself._revsetsymbols:revset.symbols[name]=symbolforname,kwinself._templatekws:templatekw.keywords[name]=kwforext,command,wrapperinself._extcommandwrappers:ifextnotinknownexts:e=extensions.find(ext)ifeisNone:raiseutil.Abort('extension %s not found'%ext)knownexts[ext]=e.cmdtableextensions.wrapcommand(knownexts[ext],commands,wrapper)forcinself._extcallables:c(ui)deffinal_reposetup(self,ui,repo):"""Method to be used as a the extension reposetup The following operations belong here: - All hooks but pre-* and post-* - Modify configuration variables - Changes to repo.__class__, repo.dirstate.__class__ """forcinself._repocallables:c(ui,repo)defuisetup(self,call):"""Decorated function will be executed during uisetup example:: @eh.uisetup def setupbabar(ui): print 'this is uisetup!' """self._uicallables.append(call)returncalldefextsetup(self,call):"""Decorated function will be executed during extsetup example:: @eh.extsetup def setupcelestine(ui): print 'this is extsetup!' """self._extcallables.append(call)returncalldefreposetup(self,call):"""Decorated function will be executed during reposetup example:: @eh.reposetup def setupzephir(ui, repo): print 'this is reposetup!' """self._repocallables.append(call)returncalldefrevset(self,symbolname):"""Decorated function is a revset symbol The name of the symbol must be given as the decorator argument. The symbol is added during `extsetup`. example:: @eh.revset('hidden') def revsetbabar(repo, subset, x): args = revset.getargs(x, 0, 0, 'babar accept no argument') return [r for r in subset if 'babar' in repo[r].description()] """defdec(symbol):self._revsetsymbols.append((symbolname,symbol))returnsymbolreturndecdeftemplatekw(self,keywordname):"""Decorated function is a revset keyword The name of the keyword must be given as the decorator argument. The symbol is added during `extsetup`. example:: @eh.templatekw('babar') def kwbabar(ctx): return 'babar' """defdec(keyword):self._templatekws.append((keywordname,keyword))returnkeywordreturndecdefwrapcommand(self,command,extension=None):"""Decorated function is a command wrapper The name of the command must be given as the decorator argument. The wrapping is installed during `uisetup`. If the second option `extension` argument is provided, the wrapping will be applied in the extension commandtable. This argument must be a string that will be searched using `extension.find` if not found and Abort error is raised. If the wrapping applies to an extension, it is installed during `extsetup` example:: @eh.wrapcommand('summary') def wrapsummary(orig, ui, repo, *args, **kwargs): ui.note('Barry!') return orig(ui, repo, *args, **kwargs) """defdec(wrapper):ifextensionisNone:self._commandwrappers.append((command,wrapper))else:self._extcommandwrappers.append((extension,command,wrapper))returnwrapperreturndecdefwrapfunction(self,container,funcname):"""Decorated function is a function wrapper This function takes two arguments, the container and the name of the function to wrap. The wrapping is performed during `uisetup`. (there is no extension support) example:: @eh.function(discovery, 'checkheads') def wrapfunction(orig, *args, **kwargs): ui.note('His head smashed in and his heart cut out') return orig(*args, **kwargs) """defdec(wrapper):self._functionwrappers.append((container,funcname,wrapper))returnwrapperreturndecdefaddattr(self,container,funcname):"""Decorated function is to be added to the container This function takes two arguments, the container and the name of the function to wrap. The wrapping is performed during `uisetup`. example:: @eh.function(context.changectx, 'babar') def babar(ctx): return 'babar' in ctx.description """defdec(func):self._duckpunchers.append((container,funcname,func))returnfuncreturndeceh=exthelper()uisetup=eh.final_uisetupextsetup=eh.final_extsetupreposetup=eh.final_reposetup######################################################################## Critical fix ########################################################################@eh.wrapfunction(mercurial.obsolete,'_readmarkers')defsafereadmarkers(orig,data):"""safe maker wrapper to remove nullid succesors Nullid successors was created by older version of evolve. """nb=0formarkerinorig(data):ifnullidinmarker[1]:marker=(marker[0],tuple(sforsinmarker[1]ifs!=nullid),marker[2],marker[3])nb+=1yieldmarkerifnb:e=sys.stderrprint>>e,'repo contains %i invalid obsolescence markers'%nbgetrevs=obsolete.getrevs######################################################################## Additional Utilities ######################################################################### This section contains a lot of small utility function and method# - Function to create markers# - useful alias pstatus and pdiff (should probably go in evolve)# - "troubles" method on changectx# - function to travel throught the obsolescence graph# - function to find useful changeset to stabilizecreatemarkers=obsolete.createmarkers### Useful alias@eh.uisetupdef_installalias(ui):ifui.config('alias','pstatus',None)isNone:ui.setconfig('alias','pstatus','status --rev .^')ifui.config('alias','pdiff',None)isNone:ui.setconfig('alias','pdiff','diff --rev .^')ifui.config('alias','olog',None)isNone:ui.setconfig('alias','olog',"log -r 'precursors(.)' --hidden")ifui.config('alias','odiff',None)isNone:ui.setconfig('alias','odiff',"diff --hidden --rev 'limit(precursors(.),1)' --rev .")ifui.config('alias','grab',None)isNone:ui.setconfig('alias','grab',"! $HG rebase --dest . --rev $@ && $HG up tip")### Troubled revset symbol@eh.revset('troubled')defrevsettroubled(repo,subset,x):"""``troubled()`` Changesets with troubles. """_=revset.getargs(x,0,0,'troubled takes no arguments')returnrepo.revs('%ld and (unstable() + bumped() + divergent())',subset)### Obsolescence graph# XXX SOME MAJOR CLEAN UP TO DO HERE XXXdef_precursors(repo,s):"""Precursor of a changeset"""cs=set()nm=repo.changelog.nodemapmarkerbysubj=repo.obsstore.precursorsforrins:forpinmarkerbysubj.get(repo[r].node(),()):pr=nm.get(p[0])ifprisnotNone:cs.add(pr)returncsdef_allprecursors(repo,s):# XXX we need a better naming"""transitive precursors of a subset"""toproceed=[repo[r].node()forrins]seen=set()allsubjects=repo.obsstore.precursorswhiletoproceed:nc=toproceed.pop()formarkinallsubjects.get(nc,()):np=mark[0]ifnpnotinseen:seen.add(np)toproceed.append(np)nm=repo.changelog.nodemapcs=set()forpinseen:pr=nm.get(p)ifprisnotNone:cs.add(pr)returncsdef_successors(repo,s):"""Successors of a changeset"""cs=set()nm=repo.changelog.nodemapmarkerbyobj=repo.obsstore.successorsforrins:forpinmarkerbyobj.get(repo[r].node(),()):forsubinp[1]:sr=nm.get(sub)ifsrisnotNone:cs.add(sr)returncsdef_allsuccessors(repo,s,haltonflags=0):# XXX we need a better naming"""transitive successors of a subset haltonflags allows to provide flags which prevent the evaluation of a marker. """toproceed=[repo[r].node()forrins]seen=set()allobjects=repo.obsstore.successorswhiletoproceed:nc=toproceed.pop()formarkinallobjects.get(nc,()):ifmark[2]&haltonflags:continueforsubinmark[1]:ifsub==nullid:continue# should not be here!ifsubnotinseen:seen.add(sub)toproceed.append(sub)nm=repo.changelog.nodemapcs=set()forsinseen:sr=nm.get(s)ifsrisnotNone:cs.add(sr)returncs######################################################################## Extending revset and template ######################################################################### this section add several useful revset symbol not yet in core.# they are subject to changes### XXX I'm not sure this revset is useful@eh.revset('suspended')defrevsetsuspended(repo,subset,x):"""``suspended()`` Obsolete changesets with non-obsolete descendants. """args=revset.getargs(x,0,0,'suspended takes no arguments')suspended=getrevs(repo,'suspended')return[rforrinsubsetifrinsuspended]@eh.revset('precursors')defrevsetprecursors(repo,subset,x):"""``precursors(set)`` Immediate precursors of changesets in set. """s=revset.getset(repo,range(len(repo)),x)cs=_precursors(repo,s)return[rforrinsubsetifrincs]@eh.revset('allprecursors')defrevsetallprecursors(repo,subset,x):"""``allprecursors(set)`` Transitive precursors of changesets in set. """s=revset.getset(repo,range(len(repo)),x)cs=_allprecursors(repo,s)return[rforrinsubsetifrincs]@eh.revset('successors')defrevsetsuccessors(repo,subset,x):"""``successors(set)`` Immediate successors of changesets in set. """s=revset.getset(repo,range(len(repo)),x)cs=_successors(repo,s)return[rforrinsubsetifrincs]@eh.revset('allsuccessors')defrevsetallsuccessors(repo,subset,x):"""``allsuccessors(set)`` Transitive successors of changesets in set. """s=revset.getset(repo,range(len(repo)),x)cs=_allsuccessors(repo,s)return[rforrinsubsetifrincs]### template keywords# XXX it does not handle troubles well :-/@eh.templatekw('obsolete')defobsoletekw(repo,ctx,templ,**args):""":obsolete: String. The obsolescence level of the node, could be ``stable``, ``unstable``, ``suspended`` or ``extinct``. """rev=ctx.rev()ifctx.obsolete():ifctx.extinct():return'extinct'else:return'suspended'elifctx.unstable():return'unstable'return'stable'######################################################################## Various trouble warning ######################################################################### This section take care of issue warning to the user when troubles appear@eh.wrapcommand("update")@eh.wrapcommand("parents")@eh.wrapcommand("pull")defwrapmayobsoletewc(origfn,ui,repo,*args,**opts):"""Warn that the working directory parent is an obsolete changeset"""res=origfn(ui,repo,*args,**opts)ifrepo['.'].obsolete():ui.warn(_('working directory parent is obsolete!\n'))returnres# XXX this could wrap transaction code# XXX (but this is a bit a layer violation)@eh.wrapcommand("commit")@eh.wrapcommand("import")@eh.wrapcommand("push")@eh.wrapcommand("pull")@eh.wrapcommand("graft")@eh.wrapcommand("phase")@eh.wrapcommand("unbundle")defwarnobserrors(orig,ui,repo,*args,**kwargs):"""display warning is the command resulted in more instable changeset"""# part of the troubled stuff may be filtered (stash ?)# This needs a better implementation but will probably wait for core.filtered=repo.changelog.filteredrevspriorunstables=len(set(getrevs(repo,'unstable'))-filtered)priorbumpeds=len(set(getrevs(repo,'bumped'))-filtered)priordivergents=len(set(getrevs(repo,'divergent'))-filtered)ret=orig(ui,repo,*args,**kwargs)# workaround phase stupidity#phases._filterunknown(ui, repo.changelog, repo._phasecache.phaseroots)filtered=repo.changelog.filteredrevsnewunstables=len(set(getrevs(repo,'unstable'))-filtered)-priorunstablesnewbumpeds=len(set(getrevs(repo,'bumped'))-filtered)-priorbumpedsnewdivergents=len(set(getrevs(repo,'divergent'))-filtered)-priordivergentsifnewunstables>0:ui.warn(_('%i new unstable changesets\n')%newunstables)ifnewbumpeds>0:ui.warn(_('%i new bumped changesets\n')%newbumpeds)ifnewdivergents>0:ui.warn(_('%i new divergent changesets\n')%newdivergents)returnret@eh.reposetupdef_repostabilizesetup(ui,repo):"""Add a hint for "hg evolve" when troubles make push fails """ifnotrepo.local():returnclassevolvingrepo(repo.__class__):defpush(self,remote,*args,**opts):"""wrapper around pull that pull obsolete relation"""try:result=super(evolvingrepo,self).push(remote,*args,**opts)exceptutil.Abort,ex:hint=_("use 'hg evolve' to get a stable history ""or --force to ignore warnings")if(len(ex.args)>=1andex.args[0].startswith('push includes ')andex.hintisNone):ex.hint=hintraisereturnresultrepo.__class__=evolvingrepodefsummaryhook(ui,repo):defwrite(fmt,count):s=fmt%countifcount:ui.write(s)else:ui.note(s)nbunstable=len(getrevs(repo,'unstable'))nbbumped=len(getrevs(repo,'bumped'))nbdivergent=len(getrevs(repo,'divergent'))write('unstable: %i changesets\n',nbunstable)write('bumped: %i changesets\n',nbbumped)write('divergent: %i changesets\n',nbdivergent)@eh.extsetupdefobssummarysetup(ui):cmdutil.summaryhooks.add('evolve',summaryhook)######################################################################## Core Other extension compat ########################################################################@eh.extsetupdef_rebasewrapping(ui):# warning about more obsoletetry:rebase=extensions.find('rebase')ifrebase:extensions.wrapcommand(rebase.cmdtable,'rebase',warnobserrors)exceptKeyError:pass# rebase not foundtry:histedit=extensions.find('histedit')ifhistedit:extensions.wrapcommand(histedit.cmdtable,'histedit',warnobserrors)exceptKeyError:pass# rebase not found######################################################################## Old Evolve extension content ######################################################################### XXX need clean up and proper sorting in other section### util function################################ changeset rewriting logic#############################defrewrite(repo,old,updates,head,newbases,commitopts):"""Return (nodeid, created) where nodeid is the identifier of the changeset generated by the rewrite process, and created is True if nodeid was actually created. If created is False, nodeid references a changeset existing before the rewrite call. """iflen(old.parents())>1:#XXX remove this unecessary limitation.raiseerror.Abort(_('cannot amend merge changesets'))base=old.p1()updatebookmarks=_bookmarksupdater(repo,old.node())wlock=repo.wlock()try:# commit a new version of the old changeset, including the update# collect all files which might be affectedfiles=set(old.files())foruinupdates:files.update(u.files())# Recompute copies (avoid recording a -> b -> a)copied=copies.pathcopies(base,head)# prune files which were reverted by the updatesdefsamefile(f):iffinhead.manifest():a=head.filectx(f)iffinbase.manifest():b=base.filectx(f)return(a.data()==b.data()anda.flags()==b.flags())else:returnFalseelse:returnfnotinbase.manifest()files=[fforfinfilesifnotsamefile(f)]# commit version of these files as defined by headheadmf=head.manifest()deffilectxfn(repo,ctx,path):ifpathinheadmf:fctx=head[path]flags=fctx.flags()mctx=context.memfilectx(fctx.path(),fctx.data(),islink='l'inflags,isexec='x'inflags,copied=copied.get(path))returnmctxraiseIOError()ifcommitopts.get('message')andcommitopts.get('logfile'):raiseutil.Abort(_('options --message and --logfile are mutually'' exclusive'))ifcommitopts.get('logfile'):message=open(commitopts['logfile']).read()elifcommitopts.get('message'):message=commitopts['message']else:message=old.description()user=commitopts.get('user')orold.user()date=commitopts.get('date')orNone# old.date()extra=dict(commitopts.get('extra',{}))extra['branch']=head.branch()new=context.memctx(repo,parents=newbases,text=message,files=files,filectxfn=filectxfn,user=user,date=date,extra=extra)ifcommitopts.get('edit'):new._text=cmdutil.commitforceeditor(repo,new,[])revcount=len(repo)newid=repo.commitctx(new)new=repo[newid]created=len(repo)!=revcountupdatebookmarks(newid)finally:wlock.release()returnnewid,createdclassMergeFailure(util.Abort):passdefrelocate(repo,orig,dest):"""rewrite <rev> on dest"""try:iforig.rev()==dest.rev():raiseutil.Abort(_('tried to relocade a node on top of itself'),hint=_("This shouldn't happen. If you still ""need to move changesets, please do so ""manually with nothing to rebase - working directory parent is also destination"))rebase=extensions.find('rebase')# dummy state to trick rebase nodeifnotorig.p2().rev()==node.nullrev:raiseutil.Abort('no support for evolution merge changesets yet',hint="Redo the merge a use `hg prune` to obsolete the old one")destbookmarks=repo.nodebookmarks(dest.node())nodesrc=orig.node()destphase=repo[nodesrc].phase()try:r=rebase.rebasenode(repo,orig.node(),dest.node(),{node.nullrev:node.nullrev},False)ifr[-1]:#some conflictraiseutil.Abort('unresolved merge conflicts (see hg help resolve)')cmdutil.duplicatecopies(repo,orig.node(),dest.node())nodenew=rebase.concludenode(repo,orig.node(),dest.node(),node.nullid)exceptutil.Abort,exc:classLocalMergeFailure(MergeFailure,exc.__class__):passexc.__class__=LocalMergeFailureraiseoldbookmarks=repo.nodebookmarks(nodesrc)ifnodenewisnotNone:phases.retractboundary(repo,destphase,[nodenew])createmarkers(repo,[(repo[nodesrc],(repo[nodenew],))])forbookinoldbookmarks:repo._bookmarks[book]=nodenewelse:createmarkers(repo,[(repo[nodesrc],())])# Behave like rebase, move bookmarks to destforbookinoldbookmarks:repo._bookmarks[book]=dest.node()forbookindestbookmarks:# restore bookmark that rebase moverepo._bookmarks[book]=dest.node()ifoldbookmarksordestbookmarks:repo._bookmarks.write()returnnodenewexceptutil.Abort:# Invalidate the previous setparentsrepo.dirstate.invalidate()raisedef_bookmarksupdater(repo,oldid):"""Return a callable update(newid) updating the current bookmark and bookmarks bound to oldid to newid. """bm=bookmarks.readcurrent(repo)defupdatebookmarks(newid):dirty=Falseifbm:repo._bookmarks[bm]=newiddirty=Trueoldbookmarks=repo.nodebookmarks(oldid)ifoldbookmarks:forbinoldbookmarks:repo._bookmarks[b]=newiddirty=Trueifdirty:repo._bookmarks.write()returnupdatebookmarks### new command#############################cmdtable={}command=cmdutil.command(cmdtable)metadataopts=[('d','date','',_('record the specified date in metadata'),_('DATE')),('u','user','',_('record the specified user in metadata'),_('USER')),]@command('^evolve|stabilize|solve',[('n','dry-run',False,'do not perform actions, just print what would be done'),('A','any',False,'evolve any troubled changeset'),('a','all',False,'evolve all troubled changesets'),('c','continue',False,'continue an interrupted evolution'),],_('[OPTIONS]...'))defevolve(ui,repo,**opts):"""Solve trouble in your repository - rebase unstable changesets to make them stable again, - create proper diffs from bumped changesets, - merge divergent changesets, - update to a successor if the working directory parent is obsolete By default, takes the first troubled changeset that looks relevant. (The logic is still a bit fuzzy) - For unstable, this means taking the first which could be rebased as a child of the working directory parent revision or one of its descendants and rebasing it. - For divergent, this means taking "." if applicable. With --any, evolve picks any troubled changeset to repair. The working directory is updated to the newly created revision. """contopt=opts['continue']anyopt=opts['any']allopt=opts['all']dryrunopt=opts['dry_run']ifcontopt:ifanyopt:raiseutil.Abort('can not specify both "--any" and "--continue"')ifallopt:raiseutil.Abort('can not specify both "--all" and "--continue"')graftcmd=commands.table['graft'][0]returngraftcmd(ui,repo,old_obsolete=True,**{'continue':True})tr=_picknexttroubled(ui,repo,anyoptorallopt)iftrisNone:ifrepo['.'].obsolete():displayer=cmdutil.show_changeset(ui,repo,{'template':shorttemplate})successors=set()forsuccessorssetinobsolete.successorssets(repo,repo['.'].node()):fornodeidinsuccessorsset:successors.add(repo[nodeid])ifnotsuccessors:ui.warn(_('parent is obsolete without successors; '+'likely killed\n'))return2eliflen(successors)>1:ui.warn(_('parent is obsolete with multiple successors:\n'))forctxinsorted(successors,key=lambdactx:ctx.rev()):displayer.show(ctx)return2else:ctx=successors.pop()ui.status(_('update:'))ifnotui.quiet:displayer.show(ctx)ifdryrunopt:print'hg update %s'%ctx.rev()return0else:returnhg.update(repo,ctx.rev())troubled=repo.revs('troubled()')iftroubled:ui.write_err(_('nothing to evolve here\n'))ui.status(_('(%i troubled changesets, do you want --any ?)\n')%len(troubled))return2else:ui.write_err(_('no troubled changesets\n'))return1defprogresscb():ifallopt:ui.progress('evolve',seen,unit='changesets',total=count)seen=1count=alloptand_counttroubled(ui,repo)or1whiletrisnotNone:progresscb()result=_evolveany(ui,repo,tr,dryrunopt,progresscb=progresscb)progresscb()seen+=1ifnotallopt:returnresultprogresscb()tr=_picknexttroubled(ui,repo,anyoptorallopt)ifallopt:ui.progress('evolve',None)def_evolveany(ui,repo,tr,dryrunopt,progresscb):repo=repo.unfiltered()tr=repo[tr.rev()]cmdutil.bailifchanged(repo)troubles=tr.troubles()if'unstable'introubles:return_solveunstable(ui,repo,tr,dryrunopt,progresscb)elif'bumped'introubles:return_solvebumped(ui,repo,tr,dryrunopt,progresscb)elif'divergent'introubles:repo=repo.unfiltered()tr=repo[tr.rev()]return_solvedivergent(ui,repo,tr,dryrunopt,progresscb)else:assertFalse# WHAT? unknown troublesdef_counttroubled(ui,repo):"""Count the amount of troubled changesets"""troubled=set()troubled.update(getrevs(repo,'unstable'))troubled.update(getrevs(repo,'bumped'))troubled.update(getrevs(repo,'divergent'))returnlen(troubled)def_picknexttroubled(ui,repo,pickany=False,progresscb=None):"""Pick a the next trouble changeset to solve"""ifprogresscb:progresscb()tr=_stabilizableunstable(repo,repo['.'])iftrisNone:wdp=repo['.']if'divergent'inwdp.troubles():tr=wdpiftrisNoneandpickany:troubled=list(repo.set('unstable()'))ifnottroubled:troubled=list(repo.set('bumped()'))ifnottroubled:troubled=list(repo.set('divergent()'))iftroubled:tr=troubled[0]returntrdef_stabilizableunstable(repo,pctx):"""Return a changectx for an unstable changeset which can be stabilized on top of pctx or one of its descendants. None if none can be found. """defselfanddescendants(repo,pctx):yieldpctxforprecinrepo.set('allprecursors(%d)',pctx):yieldprecforctxinpctx.descendants():yieldctxforprecinrepo.set('allprecursors(%d)',ctx):yieldprec# Look for an unstable which can be stabilized as a child of# node. The unstable must be a child of one of node predecessors.forctxinselfanddescendants(repo,pctx):forchildinctx.children():ifchild.unstable():returnchildreturnNonedef_solveunstable(ui,repo,orig,dryrun=False,progresscb=None):"""Stabilize a unstable changeset"""obs=orig.parents()[0]ifnotobs.obsolete():printobs.rev(),orig.parents()printorig.rev()obs=orig.parents()[1]assertobs.obsolete()newer=obsolete.successorssets(repo,obs.node())# search of a parent which is not killedwhilenotnewerornewer==[()]:ui.debug("stabilize target %s is plain dead,"" trying to stabilize on its parent")obs=obs.parents()[0]newer=obsolete.successorssets(repo,obs.node())iflen(newer)>1:raiseutil.Abort(_("conflict rewriting. can't choose destination\n"))targets=newer[0]asserttargetsiflen(targets)>1:raiseutil.Abort(_("does not handle split parents yet\n"))return2target=targets[0]displayer=cmdutil.show_changeset(ui,repo,{'template':shorttemplate})target=repo[target]repo.ui.status(_('move:'))ifnotui.quiet:displayer.show(orig)repo.ui.status(_('atop:'))ifnotui.quiet:displayer.show(target)ifprogresscb:progresscb()todo='hg rebase -r %s -d %s\n'%(orig,target)ifdryrun:repo.ui.write(todo)else:repo.ui.note(todo)ifprogresscb:progresscb()lock=repo.lock()try:relocate(repo,orig,target)exceptMergeFailure:repo.opener.write('graftstate',orig.hex()+'\n')repo.ui.write_err(_('evolve failed!\n'))repo.ui.write_err(_('fix conflict and run "hg evolve --continue"\n'))raisefinally:lock.release()def_solvebumped(ui,repo,bumped,dryrun=False,progresscb=None):"""Stabilize a bumped changeset"""# For now we deny bumped mergeiflen(bumped.parents())>1:raiseutil.Abort('late comer stabilization is confused by bumped'' %s being a merge'%bumped)prec=repo.set('last(allprecursors(%d) and public())',bumped).next()# For now we deny target mergeiflen(prec.parents())>1:raiseutil.Abort('late comer evolution is confused by precursors'' %s being a merge'%prec)displayer=cmdutil.show_changeset(ui,repo,{'template':shorttemplate})repo.ui.status(_('recreate:'))ifnotui.quiet:displayer.show(bumped)repo.ui.status(_('atop:'))ifnotui.quiet:displayer.show(prec)ifdryrun:todo='hg rebase --rev %s --dest %s;\n'%(bumped,prec.p1())repo.ui.write(todo)repo.ui.write('hg update %s;\n'%prec)repo.ui.write('hg revert --all --rev %s;\n'%bumped)repo.ui.write('hg commit --msg "bumped update to %s"')return0ifprogresscb:progresscb()wlock=repo.wlock()try:newid=tmpctx=Nonetmpctx=bumpedlock=repo.lock()try:bmupdate=_bookmarksupdater(repo,bumped.node())# Basic check for common parent. Far too complicated and fragiletr=repo.transaction('bumped-stabilize')try:ifnotlist(repo.set('parents(%d) and parents(%d)',bumped,prec)):# Need to rebase the changeset at the right placerepo.ui.status(_('rebasing to destination parent: %s\n')%prec.p1())try:tmpid=relocate(repo,bumped,prec.p1())iftmpidisnotNone:tmpctx=repo[tmpid]createmarkers(repo,[(bumped,(tmpctx,))])exceptMergeFailure:repo.opener.write('graftstate',bumped.hex()+'\n')repo.ui.write_err(_('evolution failed!\n'))repo.ui.write_err(_('fix conflict and run "hg evolve --continue"\n'))raise# Create the new commit contextrepo.ui.status(_('computing new diff\n'))files=set()copied=copies.pathcopies(prec,bumped)precmanifest=prec.manifest()forkey,valinbumped.manifest().iteritems():ifprecmanifest.pop(key,None)!=val:files.add(key)files.update(precmanifest)# add missing files# commit itiffiles:# something to commit!deffilectxfn(repo,ctx,path):ifpathinbumped:fctx=bumped[path]flags=fctx.flags()mctx=context.memfilectx(fctx.path(),fctx.data(),islink='l'inflags,isexec='x'inflags,copied=copied.get(path))returnmctxraiseIOError()text='bumped update to %s:\n\n'%prectext+=bumped.description()new=context.memctx(repo,parents=[prec.node(),node.nullid],text=text,files=files,filectxfn=filectxfn,user=bumped.user(),date=bumped.date(),extra=bumped.extra())newid=repo.commitctx(new)ifnewidisNone:createmarkers(repo,[(tmpctx,())])newid=prec.node()else:phases.retractboundary(repo,bumped.phase(),[newid])createmarkers(repo,[(tmpctx,(repo[newid],))],flag=obsolete.bumpedfix)bmupdate(newid)tr.close()repo.ui.status(_('commited as %s\n')%node.short(newid))finally:tr.release()finally:lock.release()# reroute the working copy parent to the new changesetrepo.dirstate.setparents(newid,node.nullid)finally:wlock.release()def_solvedivergent(ui,repo,divergent,dryrun=False,progresscb=None):base,others=divergentdata(divergent)iflen(others)>1:othersstr="[%s]"%(','.join([str(i)foriinothers]))hint=("changeset %d is divergent with a changeset that got splitted ""| into multiple ones:\n[%s]\n""| This is not handled by automatic evolution yet\n""| You have to fallback to manual handling with commands as:\n""| - hg touch -D\n""| - hg prune\n""| \n""| You should contact your local evolution Guru for help.\n"%(divergent,othersstr))raiseutil.Abort("We do not handle divergence with split yet",hint='')other=others[0]ifdivergent.phase()<=phases.public:raiseutil.Abort("We can't resolve this conflict from the public side",hint="%s is public, try from %s"%(divergent,other))iflen(other.parents())>1:raiseutil.Abort("divergent changeset can't be a merge (yet)",hint="You have to fallback to solving this by hand...\n""| This probably mean to redo the merge and use ""| `hg prune` to kill older version.")ifother.p1()notindivergent.parents():raiseutil.Abort("parents are not common (not handled yet)",hint="| %(d)s, %(o)s are not based on the same changeset.""| With the current state of its implementation, ""| evolve does not work in that case.\n""| rebase one of them next to the other and run ""| this command again.\n""| - either: hg rebase -dest 'p1(%(d)s)' -r %(o)s""| - or: hg rebase -dest 'p1(%(d)s)' -r %(o)s"%{'d':divergent,'o':other})displayer=cmdutil.show_changeset(ui,repo,{'template':shorttemplate})ui.status(_('merge:'))ifnotui.quiet:displayer.show(divergent)ui.status(_('with: '))ifnotui.quiet:displayer.show(other)ui.status(_('base: '))ifnotui.quiet:displayer.show(base)ifdryrun:ui.write('hg update -c %s &&\n'%divergent)ui.write('hg merge %s &&\n'%other)ui.write('hg commit -m "auto merge resolving conflict between ''%s and %s"&&\n'%(divergent,other))ui.write('hg up -C %s &&\n'%base)ui.write('hg revert --all --rev tip &&\n')ui.write('hg commit -m "`hg log -r %s --template={desc}`";\n'%divergent)returnwlock=lock=Nonetry:wlock=repo.wlock()lock=repo.lock()ifdivergentnotinrepo[None].parents():repo.ui.status(_('updating to "local" conflict\n'))hg.update(repo,divergent.rev())repo.ui.note(_('merging divergent changeset\n'))ifprogresscb:progresscb()stats=merge.update(repo,other.node(),branchmerge=True,force=False,partial=None,ancestor=base.node(),mergeancestor=True)hg._showstats(repo,stats)ifstats[3]:repo.ui.status(_("use 'hg resolve' to retry unresolved file merges ""or 'hg update -C .' to abandon\n"))ifstats[3]>0:raiseutil.Abort('Merge conflict between several amendments, and this is not yet automated',hint="""/!\ You can try:/!\ * manual merge + resolve => new cset X/!\ * hg up to the parent of the amended changeset (which are named W and Z)/!\ * hg revert --all -r X/!\ * hg ci -m "same message as the amended changeset" => new cset Y/!\ * hg kill -n Y W Z""")ifprogresscb:progresscb()tr=repo.transaction('stabilize-divergent')try:repo.dirstate.setparents(divergent.node(),node.nullid)oldlen=len(repo)amend(ui,repo,message='',logfile='')ifoldlen==len(repo):new=divergent# no changeselse:new=repo['.']createmarkers(repo,[(other,(new,))])phases.retractboundary(repo,other.phase(),[new.node()])tr.close()finally:tr.release()finally:lockmod.release(lock,wlock)defdivergentdata(ctx):"""return base, other part of a conflict This only return the first one. XXX this woobly function won't survive XXX """forbaseinctx._repo.set('reverse(precursors(%d))',ctx):newer=obsolete.successorssets(ctx._repo,base.node())# drop filter and solution including the original ctxnewer=[nforninnewerifnandctx.node()notinn]ifnewer:returnbase,tuple(ctx._repo[o]foroinnewer[0])raiseutil.Abort('base of divergent changeset not found',hint='this case is not yet handled')shorttemplate='[{rev}] {desc|firstline}\n'@command('^gdown|previous',[],'')defcmdprevious(ui,repo):"""update to parent and display summary lines"""wkctx=repo[None]wparents=wkctx.parents()iflen(wparents)!=1:raiseutil.Abort('merge in progress')parents=wparents[0].parents()displayer=cmdutil.show_changeset(ui,repo,{'template':shorttemplate})iflen(parents)==1:p=parents[0]bm=bookmarks.readcurrent(repo)shouldmove=bmisnotNoneandbookmarks.iscurrent(repo,bm)ret=hg.update(repo,p.rev())ifnotretandshouldmove:repo._bookmarks[bm]=p.node()repo._bookmarks.write()displayer.show(p)return0else:forpinparents:displayer.show(p)ui.warn(_('multiple parents, explicitly update to one\n'))return1@command('^gup|next',[],'')defcmdnext(ui,repo):"""update to child and display summary lines"""wkctx=repo[None]wparents=wkctx.parents()iflen(wparents)!=1:raiseutil.Abort('merge in progress')children=[ctxforctxinwparents[0].children()ifnotctx.obsolete()]displayer=cmdutil.show_changeset(ui,repo,{'template':shorttemplate})ifnotchildren:ui.warn(_('no non-obsolete children\n'))return1iflen(children)==1:c=children[0]bm=bookmarks.readcurrent(repo)shouldmove=bmisnotNoneandbookmarks.iscurrent(repo,bm)ret=hg.update(repo,c.rev())ifnotretandshouldmove:repo._bookmarks[bm]=c.node()repo._bookmarks.write()displayer.show(c)return0else:forcinchildren:displayer.show(c)ui.warn(_('multiple non-obsolete children, explicitly update to one\n'))return1def_reachablefrombookmark(repo,revs,mark):"""filter revisions and bookmarks reachable from the given bookmark yoinked from mq.py """marks=repo._bookmarksifmarknotinmarks:raiseutil.Abort(_("bookmark '%s' not found")%mark)# If the requested bookmark is not the only one pointing to a# a revision we have to only delete the bookmark and not strip# anything. revsets cannot detect that case.uniquebm=Trueform,ninmarks.iteritems():ifm!=markandn==repo[mark].node():uniquebm=Falsebreakifuniquebm:rsrevs=repo.revs("ancestors(bookmark(%s)) - ""ancestors(head() and not bookmark(%s)) - ""ancestors(bookmark() and not bookmark(%s)) - ""obsolete()",mark,mark,mark)revs.update(set(rsrevs))returnmarks,revsdef_deletebookmark(ui,marks,mark):delmarks[mark]marks.write()ui.write(_("bookmark '%s' deleted\n")%mark)def_getmetadata(**opts):metadata={}date=opts.get('date')user=opts.get('user')ifdate:metadata['date']='%i%i'%util.parsedate(date)ifuser:metadata['user']=userreturnmetadata@command('^prune|obsolete|kill',[('n','new',[],_("successor changeset (DEPRECATED)")),('s','succ',[],_("successor changeset")),('r','rev',[],_("revisions to prune")),('','biject',False,_("do a 1-1 map between rev and successor ranges")),('B','bookmark','',_("remove revs only reachable from given"" bookmark"))]+metadataopts,_('[OPTION] [-r] REV...'))# -U --noupdate option to prevent wc update and or bookmarks update ?defcmdprune(ui,repo,*revs,**opts):"""hide changesets by marking them obsolete Obsolete changesets becomes invisible to all commands. Unpruned descendants of pruned changesets becomes "unstable". Use the :hg:`evolve` to handle such situation. When the working directory parent is pruned, the repository is updated to a non-obsolete parent. You can use the ``--succ`` option to inform mercurial that a newer version of the pruned changeset exists. You can use the ``--biject`` option to specify a 1-1 (bijection) between revisions to prune and successor changesets. This option may be removed in a future release (with the functionality absorbed automatically). """revs=set(scmutil.revrange(repo,list(revs)+opts.get('rev')))succs=opts['new']+opts['succ']bookmark=opts.get('bookmark')metadata=_getmetadata(**opts)biject=opts.get('biject')ifbookmark:marks,revs=_reachablefrombookmark(repo,revs,bookmark)ifnotrevs:# no revisions to prune - delete bookmark immediately_deletebookmark(ui,marks,bookmark)ifnotrevs:raiseutil.Abort(_('nothing to prune'))wlock=lock=Nonewlock=repo.wlock()sortedrevs=lambdaspecs:sorted(set(scmutil.revrange(repo,specs)))try:lock=repo.lock()# defines pruned changesetsprecs=[]forpinsortedrevs(revs):cp=repo[p]ifnotcp.mutable():# note: create marker would had raise something anywayraiseutil.Abort('cannot prune immutable changeset: %s'%cp,hint='see "hg help phases" for details')precs.append(cp)ifnotprecs:raiseutil.Abort('nothing to prune')# defines successors changesetssucs=tuple(repo[n]forninsortedrevs(succs))ifnotbijectandlen(sucs)>1andlen(precs)>1:msg="Can't use multiple successors for multiple precursors"raiseutil.Abort(msg)ifbijectandlen(sucs)!=len(precs):msg="Can't use %d successors for %d precursors"%(len(sucs),len(precs))raiseutil.Abort(msg)relations=[(p,sucs)forpinprecs]ifbiject:relations=[(p,(s,))forp,sinzip(precs,sucs)]# create markerscreatemarkers(repo,relations,metadata=metadata)# informs that changeset have been prunedui.status(_('%i changesets pruned\n')%len(precs))# update to an unkilled parentwdp=repo['.']newnode=wdpwhilenewnode.obsolete():newnode=newnode.parents()[0]ifnewnode.node()!=wdp.node():commands.update(ui,repo,newnode.rev())ui.status(_('working directory now at %s\n')%newnode)# update bookmarksifbookmark:_deletebookmark(ui,marks,bookmark)forctxinrepo.unfiltered().set('bookmark() and %ld',precs):ldest=list(repo.set('max((::%d) - obsolete())',ctx))ifldest:dest=ldest[0]updatebookmarks=_bookmarksupdater(repo,ctx.node())updatebookmarks(dest.node())finally:lockmod.release(lock,wlock)@command('amend|refresh',[('A','addremove',None,_('mark new/missing files as added/removed before committing')),('e','edit',False,_('invoke editor on commit messages')),('','close-branch',None,_('mark a branch as closed, hiding it from the branch list')),('s','secret',None,_('use the secret phase for committing')),]+walkopts+commitopts+commitopts2,_('[OPTION]... [FILE]...'))defamend(ui,repo,*pats,**opts):"""combine a changeset with updates and replace it with a new one Commits a new changeset incorporating both the changes to the given files and all the changes from the current parent changeset into the repository. See :hg:`commit` for details about committing changes. If you don't specify -m, the parent's message will be reused. Behind the scenes, Mercurial first commits the update as a regular child of the current parent. Then it creates a new commit on the parent's parents with the updated contents. Then it changes the working copy parent to this new combined changeset. Finally, the old changeset and its update are hidden from :hg:`log` (unless you use --hidden with log). Returns 0 on success, 1 if nothing changed. """opts=opts.copy()edit=opts.pop('edit',False)opts['amend']=Trueifnot(editoropts['message']):opts['message']=repo['.'].description()_alias,commitcmd=cmdutil.findcmd('commit',commands.table)returncommitcmd[0](ui,repo,*pats,**opts)def_commitfiltered(repo,ctx,match):"""Recommit ctx with changed files not in match. Return the new node identifier, or None if nothing changed. """base=ctx.p1()m,a,r=repo.status(base,ctx)[:3]allfiles=set(m+a+r)files=set(fforfinallfilesifnotmatch(f))iffiles==allfiles:returnNone# Filter copiescopied=copies.pathcopies(base,ctx)copied=dict((src,dst)forsrc,dstincopied.iteritems()ifdstinfiles)deffilectxfn(repo,memctx,path):ifpathnotinctx:raiseIOError()fctx=ctx[path]flags=fctx.flags()mctx=context.memfilectx(fctx.path(),fctx.data(),islink='l'inflags,isexec='x'inflags,copied=copied.get(path))returnmctxnew=context.memctx(repo,parents=[base.node(),node.nullid],text=ctx.description(),files=files,filectxfn=filectxfn,user=ctx.user(),date=ctx.date(),extra=ctx.extra())# commitctx always create a new revision, no need to checknewid=repo.commitctx(new)returnnewiddef_uncommitdirstate(repo,oldctx,match):"""Fix the dirstate after switching the working directory from oldctx to a copy of oldctx not containing changed files matched by match. """ctx=repo['.']ds=repo.dirstatecopies=dict(ds.copies())m,a,r=repo.status(oldctx.p1(),oldctx,match=match)[:3]forfinm:ifds[f]=='r':# modified + removed -> removedcontinueds.normallookup(f)forfina:ifds[f]=='r':# added + removed -> unknownds.drop(f)elifds[f]!='a':ds.add(f)forfinr:ifds[f]=='a':# removed + added -> normalds.normallookup(f)elifds[f]!='r':ds.remove(f)# Merge old parent and old working dir copiesoldcopies={}forfin(m+a):src=oldctx[f].renamed()ifsrc:oldcopies[f]=src[0]oldcopies.update(copies)copies=dict((dst,oldcopies.get(src,src))fordst,srcinoldcopies.iteritems())# Adjust the dirstate copiesfordst,srcincopies.iteritems():if(srcnotinctxordstinctxords[dst]!='a'):src=Noneds.copy(src,dst)@command('^uncommit',[('a','all',None,_('uncommit all changes when no arguments given')),]+commands.walkopts,_('[OPTION]... [NAME]'))defuncommit(ui,repo,*pats,**opts):"""move changes from parent revision to working directory Changes to selected files in the checked out revision appear again as uncommitted changed in the working directory. A new revision without the selected changes is created, becomes the checked out revision, and obsoletes the previous one. The --include option specifies patterns to uncommit. The --exclude option specifies patterns to keep in the commit. Return 0 if changed files are uncommitted. """lock=repo.lock()try:wlock=repo.wlock()try:wctx=repo[None]iflen(wctx.parents())<=0:raiseutil.Abort(_("cannot uncommit null changeset"))iflen(wctx.parents())>1:raiseutil.Abort(_("cannot uncommit while merging"))old=repo['.']ifold.phase()==phases.public:raiseutil.Abort(_("cannot rewrite immutable changeset"))iflen(old.parents())>1:raiseutil.Abort(_("cannot uncommit merge changeset"))oldphase=old.phase()updatebookmarks=_bookmarksupdater(repo,old.node())# Recommit the filtered changesetnewid=Noneif(patsoropts.get('include')oropts.get('exclude')oropts.get('all')):match=scmutil.match(old,pats,opts)newid=_commitfiltered(repo,old,match)ifnewidisNone:raiseutil.Abort(_('nothing to uncommit'))# Move local changes on filtered changesetcreatemarkers(repo,[(old,(repo[newid],))])phases.retractboundary(repo,oldphase,[newid])repo.dirstate.setparents(newid,node.nullid)_uncommitdirstate(repo,old,match)updatebookmarks(newid)ifnotrepo[newid].files():ui.warn(_("new changeset is empty\n"))ui.status(_('(use "hg kill ." to remove it)\n'))finally:wlock.release()finally:lock.release()@eh.wrapcommand('commit')defcommitwrapper(orig,ui,repo,*arg,**kwargs):ifkwargs.get('amend',False):lock=Noneelse:lock=repo.lock()try:obsoleted=kwargs.get('obsolete',[])ifobsoleted:obsoleted=repo.set('%lr',obsoleted)result=orig(ui,repo,*arg,**kwargs)ifnotresult:# commit successednew=repo['-1']oldbookmarks=[]markers=[]foroldinobsoleted:oldbookmarks.extend(repo.nodebookmarks(old.node()))markers.append((old,(new,)))ifmarkers:createmarkers(repo,markers)forbookinoldbookmarks:repo._bookmarks[book]=new.node()ifoldbookmarks:repo._bookmarks.write()returnresultfinally:iflockisnotNone:lock.release()@command('^touch',[('r','rev',[],'revision to update'),('D','duplicate',False,'do not mark the new revision as successor of the old one')],# allow to choose the seed ?_('[-r] revs'))deftouch(ui,repo,*revs,**opts):"""Create successors that are identical to their predecessors except for the changeset ID This is used to "resurrect" changesets """duplicate=opts['duplicate']revs=list(revs)revs.extend(opts['rev'])ifnotrevs:revs=['.']revs=scmutil.revrange(repo,revs)ifnotrevs:ui.write_err('no revision to touch\n')return1ifnotduplicateandrepo.revs('public() and %ld',revs):raiseutil.Abort("can't touch public revision")wlock=lock=Nonetry:wlock=repo.wlock()lock=repo.lock()tr=repo.transaction('touch')revs.sort()# ensure parent are run firstnewmapping={}try:forrinrevs:ctx=repo[r]extra=ctx.extra().copy()extra['__touch-noise__']=random.randint(0,0xffffffff)# search for touched parentp1=ctx.p1().node()p2=ctx.p2().node()p1=newmapping.get(p1,p1)p2=newmapping.get(p2,p2)new,_=rewrite(repo,ctx,[],ctx,[p1,p2],commitopts={'extra':extra})# store touched version to help potential childrennewmapping[ctx.node()]=newifnotduplicate:createmarkers(repo,[(ctx,(repo[new],))])phases.retractboundary(repo,ctx.phase(),[new])ifctxinrepo[None].parents():repo.dirstate.setparents(new,node.nullid)tr.close()finally:tr.release()finally:lockmod.release(lock,wlock)@command('^fold',[('r','rev',[],_("explicitly specify the full set of revision to fold")),],# allow to choose the seed ?_('rev'))deffold(ui,repo,*revs,**opts):"""Fold multiple revisions into a single one The revisions from your current working directory to the given one are folded into a single successor revision. you can alternatively use --rev to explicitly specify revisions to be folded, ignoring the current working directory parent. """revs=list(revs)ifrevs:ifopts.get('rev',()):raiseutil.Abort("cannot specify both --rev and a target revision")targets=scmutil.revrange(repo,revs)revs=repo.revs('(%ld::.) or (.::%ld)',targets,targets)elif'rev'inopts:revs=scmutil.revrange(repo,opts['rev'])else:revs=()ifnotrevs:ui.write_err('no revision to fold\n')return1roots=repo.revs('roots(%ld)',revs)iflen(roots)>1:raiseutil.Abort("set has multiple roots")root=repo[roots[0]]ifroot.phase()<=phases.public:raiseutil.Abort("can't fold public revisions")heads=repo.revs('heads(%ld)',revs)iflen(heads)>1:raiseutil.Abort("set has multiple heads")head=repo[heads[0]]wlock=lock=Nonetry:wlock=repo.wlock()lock=repo.lock()tr=repo.transaction('touch')try:allctx=[repo[r]forrinrevs]targetphase=max(c.phase()forcinallctx)msgs=["HG: This is a fold of %d changesets."%len(allctx)]msgs+=["HG: Commit message of changeset %s.\n\n%s\n"%(c.rev(),c.description())forcinallctx]commitopts={'message':"\n".join(msgs)}commitopts['edit']=Truenewid,_=rewrite(repo,root,allctx,head,[root.p1().node(),root.p2().node()],commitopts=commitopts)phases.retractboundary(repo,targetphase,[newid])createmarkers(repo,[(ctx,(repo[newid],))forctxinallctx])tr.close()finally:tr.release()ui.status('%i changesets folded\n'%len(revs))ifrepo['.'].rev()inrevs:hg.update(repo,newid)finally:lockmod.release(lock,wlock)@eh.wrapcommand('graft')defgraftwrapper(orig,ui,repo,*revs,**kwargs):kwargs=dict(kwargs)revs=list(revs)+kwargs.get('rev',[])kwargs['rev']=[]obsoleted=kwargs.setdefault('obsolete',[])lock=repo.lock()try:ifkwargs.get('old_obsolete'):ifkwargs.get('continue'):obsoleted.extend(repo.opener.read('graftstate').splitlines())else:obsoleted.extend(revs)# convert obsolete target into revs to avoid alias jokeobsoleted[:]=[str(i)foriinrepo.revs('%lr',obsoleted)]ifobsoletedandlen(revs)>1:raiseerror.Abort(_('cannot graft multiple revisions while ''obsoleting (for now).'))returncommitwrapper(orig,ui,repo,*revs,**kwargs)finally:lock.release()@eh.extsetupdefoldevolveextsetup(ui):try:rebase=extensions.find('rebase')exceptKeyError:raiseerror.Abort(_('evolution extension requires rebase extension.'))forcmdin['kill','uncommit','touch','fold']:entry=extensions.wrapcommand(cmdtable,cmd,warnobserrors)entry=cmdutil.findcmd('commit',commands.table)[1]entry[1].append(('o','obsolete',[],_("make commit obsolete this revision")))entry=cmdutil.findcmd('graft',commands.table)[1]entry[1].append(('o','obsolete',[],_("make graft obsoletes this revision")))entry[1].append(('O','old-obsolete',False,_("make graft obsoletes its source")))