discovery: filter null from the discovery revset
If there is nothing in common, common will be "null" and the revset will now
returns "-1" crashing the discovery process. We filter out the null revision to
prevent that.
# 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 Mercurial core'''__version__='5.0.2'testedwith='3.2'buglink='http://bz.selenic.com/'importsys,osimportrandomfromStringIOimportStringIOimportstructimporturllibimportresha1re=re.compile(r'\b[0-9a-f]{6,40}\b')importmercurialfrommercurialimportutiltry:frommercurialimportobsoleteifnotobsolete._enabled:obsolete._enabled=Truefrommercurialimportwireprotogboptslist=getattr(wireproto,'gboptslist',None)gboptsmap=getattr(wireproto,'gboptsmap',None)except(ImportError,AttributeError):gboptslist=gboptsmap=Nonefrommercurialimportbase85frommercurialimportbookmarksfrommercurialimportcmdutilfrommercurialimportcommandsfrommercurialimportcontextfrommercurialimportcopiesfrommercurialimporterrorfrommercurialimportexchangefrommercurialimportextensionsfrommercurialimporthttppeerfrommercurialimporthgfrommercurialimportlockaslockmodfrommercurialimportmergefrommercurialimportnodefrommercurialimportphasesfrommercurialimportpatchfrommercurialimportpushkeyfrommercurialimportrevsetfrommercurialimportscmutilfrommercurialimporttemplatekwfrommercurial.i18nimport_frommercurial.commandsimportwalkopts,commitopts,commitopts2,mergetooloptsfrommercurial.nodeimportnullidfrommercurialimportwireprotofrommercurialimportlocalrepofrommercurial.hgwebimporthgweb_modfrommercurialimportbundle2cmdtable={}command=cmdutil.command(cmdtable)_pack=struct.packifgboptsmapisnotNone:memfilectx=context.memfilectxelifgboptslistisnotNone:oldmemfilectx=context.memfilectxdefmemfilectx(repo,*args,**kwargs):returnoldmemfilectx(*args,**kwargs)else:raiseImportError('evolve needs version %s or above'%min(testedwith.split()))# 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######################################################################## experimental behavior ########################################################################commitopts3=[('D','current-date',None,_('record the current date as commit date')),('U','current-user',None,_('record the current user as committer')),]def_resolveoptions(ui,opts):"""modify commit options dict to handle related options For now, all it does is figure out the commit date: respect -D unless -d was supplied. """# N.B. this is extremely similar to setupheaderopts() in mq.pyifnotopts.get('date')andopts.get('current_date'):opts['date']='%d%d'%util.makedate()ifnotopts.get('user')andopts.get('current_user'):opts['user']=ui.username()getrevs=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 stabilize### 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:ifos.name=='nt':ui.setconfig('alias','grab',"! "+util.hgexecutable()+" rebase --dest . --rev $@ && "+util.hgexecutable()+" up tip")else: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'@eh.templatekw('troubles')defshowtroubles(repo,ctx,**args):""":troubles: List of strings. Evolution troubles affecting the changeset (zero or more of "unstable", "divergent" or "bumped")."""returntemplatekw.showlist('trouble',ctx.troubles(),plural='troubles',**args)######################################################################## 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.wrapfunction(mercurial.exchange,'push')defpush(orig,repo,*args,**opts):"""Add a hint for "hg evolve" when troubles make push fails """try:returnorig(repo,*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=hintraisereturnresultdefsummaryhook(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())# 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=memfilectx(repo,fctx.path(),fctx.data(),islink='l'inflags,isexec='x'inflags,copied=copied.get(path))returnmctxreturnNonemessage=cmdutil.logmessage(repo.ui,commitopts)ifnotmessage: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)returnnewid,createdclassMergeFailure(util.Abort):passdefrelocate(repo,orig,dest,keepbranch=False):"""rewrite <rev> on dest"""iforig.rev()==dest.rev():raiseutil.Abort(_('tried to relocate 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"))ifnotorig.p2().rev()==node.nullrev:raiseutil.Abort('no support for evolving merge changesets yet',hint="Redo the merge and use `hg prune <old> --succ <new>` to obsolete the old one")destbookmarks=repo.nodebookmarks(dest.node())nodesrc=orig.node()destphase=repo[nodesrc].phase()commitmsg=orig.description()cache={}sha1s=re.findall(sha1re,commitmsg)unfi=repo.unfiltered()forsha1insha1s:ctx=Nonetry:ctx=unfi[sha1]excepterror.RepoLookupError:continueifnotctx.obsolete():continuesuccessors=obsolete.successorssets(repo,ctx.node(),cache)# We can't make any assumptions about how to update the hash if the# cset in question was split or diverged.iflen(successors)==1andlen(successors[0])==1:newsha1=node.hex(successors[0][0])commitmsg=commitmsg.replace(sha1,newsha1[:len(sha1)])else:repo.ui.note(_('The stale commit message reference to %s could ''not be updated\n')%sha1)tr=repo.transaction('relocate')try:try:ifrepo['.'].rev()!=dest.rev():merge.update(repo,dest,False,True,False)ifkeepbranch:repo.dirstate.setbranch(orig.branch())r=merge.graft(repo,orig,orig.p1(),['local','graft'])ifr[-1]:#some conflictraiseutil.Abort('unresolved merge conflicts (see hg help resolve)')ifcommitmsgisNone:commitmsg=orig.description()extra={'rebase_source':orig.hex()}backup=repo.ui.backupconfig('phases','new-commit')try:targetphase=max(orig.phase(),phases.draft)repo.ui.setconfig('phases','new-commit',targetphase,'rebase')# Commit might fail if unresolved files existnodenew=repo.commit(text=commitmsg,user=orig.user(),date=orig.date(),extra=extra)finally:repo.ui.restoreconfig(backup)exceptutil.Abort,exc:repo.dirstate.beginparentchange()repo.setparents(repo['.'].node(),nullid)repo.dirstate.write()# fix up dirstate for copies and renamescopies.duplicatecopies(repo,dest.rev(),orig.p1().rev())repo.dirstate.endparentchange()classLocalMergeFailure(MergeFailure,exc.__class__):passexc.__class__=LocalMergeFailureraiseoldbookmarks=repo.nodebookmarks(nodesrc)ifnodenewisnotNone:phases.retractboundary(repo,tr,destphase,[nodenew])obsolete.createmarkers(repo,[(repo[nodesrc],(repo[nodenew],))])forbookinoldbookmarks:repo._bookmarks[book]=nodenewelse:obsolete.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()tr.close()finally:tr.release()returnnodenewdef_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#############################metadataopts=[('d','date','',_('record the specified date in metadata'),_('DATE')),('u','user','',_('record the specified user in metadata'),_('USER')),]@eh.uisetupdef_installimportobsolete(ui):entry=cmdutil.findcmd('import',commands.table)[1]entry[1].append(('','obsolete',False,_('mark the old node as obsoleted by ''the created commit')))@eh.wrapfunction(mercurial.cmdutil,'tryimportone')deftryimportone(orig,ui,repo,hunk,parents,opts,*args,**kwargs):extracted=patch.extract(ui,hunk)expected=extracted[5]ifexpectedisnotNone:expected=node.bin(expected)oldextract=patch.extracttry:patch.extract=lambdaui,hunk:extractedret=orig(ui,repo,hunk,parents,opts,*args,**kwargs)finally:patch.extract=oldextractcreated=ret[1]if(opts['obsolete']andNonenotin(created,expected)andcreated!=expected):tr=repo.transaction('import-obs')try:metadata={'user':ui.username()}repo.obsstore.create(tr,expected,(created,),metadata=metadata)tr.close()finally:tr.release()returnretdef_deprecatealias(oldalias,newalias):'''Deprecates an alias for a command in favour of another Creates a new entry in the command table for the old alias. It creates a wrapper that has its synopsis set to show that is has been deprecated. The documentation will be replace with a pointer to the new alias. If a user invokes the command a deprecation warning will be printed and the command of the *new* alias will be invoked. This function is loosely based on the extensions.wrapcommand function. '''aliases,entry=cmdutil.findcmd(newalias,cmdtable)foralias,eincmdtable.iteritems():ifeisentry:breaksynopsis='(DEPRECATED)'iflen(entry)>2:fn,opts,_syn=entryelse:fn,opts,=entrydeprecationwarning=_('%s have been deprecated in favor of %s\n'%(oldalias,newalias))defnewfn(*args,**kwargs):ui=args[0]ui.warn(deprecationwarning)util.checksignature(fn)(*args,**kwargs)newfn.__doc__=deprecationwarningcmdwrapper=command(oldalias,opts,synopsis)cmdwrapper(newfn)@eh.extsetupdefdeprecatealiases(ui):_deprecatealias('gup','next')_deprecatealias('gdown','previous')@command('debugrecordpruneparents',[],'')defcmddebugrecordpruneparents(ui,repo):"""add parents data to prune markers when possible This commands search the repo for prune markers without parent information. If the pruned node is locally known, a new markers with parent data is created."""pgop='reading markers'# lock from the beginning to prevent racewlock=lock=tr=Nonetry:wlock=repo.wlock()lock=repo.lock()tr=repo.transaction('recordpruneparents')unfi=repo.unfiltered()nm=unfi.changelog.nodemapstore=repo.obsstorepgtotal=len(store._all)foridx,markinenumerate(list(store._all)):ifnotmark[1]:rev=nm.get(mark[0])ifrevisnotNone:ctx=unfi[rev]meta=obsolete.decodemeta(mark[3])fori,pinenumerate(ctx.parents(),1):meta['p%i'%i]=p.hex()before=len(store._all)store.create(tr,mark[0],mark[1],mark[2],metadata=meta)iflen(store._all)-before:ui.write('created new markers for %i\n'%rev)ui.progress(pgop,idx,total=pgtotal)tr.close()ui.progress(pgop,None)finally:lockmod.release(tr,lock,wlock)@command('debugobsstorestat',[],'')defcmddebugobsstorestat(ui,repo):"""print statistic about obsolescence markers in the repo"""store=repo.obsstoreunfi=repo.unfiltered()nm=unfi.changelog.nodemapui.write('markers total: %9i\n'%len(store._all))sucscount=[0,0,0,0]known=0parentsdata=0metakeys={}# node -> cluster mapping# a cluster is a (set(nodes), set(markers)) tupleclustersmap={}# same data using parent informationpclustersmap={}formarkinstore:ifmark[0]innm:known+=1nbsucs=len(mark[1])sucscount[min(nbsucs,3)]+=1meta=mark[3]forkey,valueinmeta:metakeys.setdefault(key,0)metakeys[key]+=1meta=dict(meta)parents=[meta.get('p1'),meta.get('p2')]parents=[node.bin(p)forpinparentsifpisnotNone]ifparents:parentsdata+=1# cluster handlingnodes=set()nodes.add(mark[0])nodes.update(mark[1])c=(set(nodes),set([mark]))toproceed=set(nodes)whiletoproceed:n=toproceed.pop()other=clustersmap.get(n)if(otherisnotNoneandotherisnotc):other[0].update(c[0])other[1].update(c[1])foroninc[0]:ifonintoproceed:continueclustersmap[on]=otherc=otherclustersmap[n]=c# same with parent datanodes.update(parents)c=(set(nodes),set([mark]))toproceed=set(nodes)whiletoproceed:n=toproceed.pop()other=pclustersmap.get(n)if(otherisnotNoneandotherisnotc):other[0].update(c[0])other[1].update(c[1])foroninc[0]:ifonintoproceed:continuepclustersmap[on]=otherc=otherpclustersmap[n]=c# freezing the resultforcinclustersmap.values():fc=(frozenset(c[0]),frozenset(c[1]))forninfc[0]:clustersmap[n]=fc# same with parent dataforcinpclustersmap.values():fc=(frozenset(c[0]),frozenset(c[1]))forninfc[0]:pclustersmap[n]=fcui.write(' for known precursors: %9i\n'%known)ui.write(' with parents data: %9i\n'%parentsdata)# successors dataui.write('markers with no successors: %9i\n'%sucscount[0])ui.write(' 1 successors: %9i\n'%sucscount[1])ui.write(' 2 successors: %9i\n'%sucscount[2])ui.write(' more than 2 successors: %9i\n'%sucscount[3])# meta data infoui.write(' available keys:\n')forkeyinsorted(metakeys):ui.write(' %15s: %9i\n'%(key,metakeys[key]))allclusters=list(set(clustersmap.values()))allclusters.sort(key=lambdax:len(x[1]))ui.write('disconnected clusters: %9i\n'%len(allclusters))ui.write(' any known node: %9i\n'%len([cforcinallclustersif[nforninc[0]ifnm.get(n)isnotNone]]))ifallclusters:nbcluster=len(allclusters)ui.write(' smallest length: %9i\n'%len(allclusters[0][1]))ui.write(' longer length: %9i\n'%len(allclusters[-1][1]))median=len(allclusters[nbcluster//2][1])ui.write(' median length: %9i\n'%median)mean=sum(len(x[1])forxinallclusters)//nbclusterui.write(' mean length: %9i\n'%mean)allpclusters=list(set(pclustersmap.values()))allpclusters.sort(key=lambdax:len(x[1]))ui.write(' using parents data: %9i\n'%len(allpclusters))ui.write(' any known node: %9i\n'%len([cforcinallclustersif[nforninc[0]ifnm.get(n)isnotNone]]))ifallpclusters:nbcluster=len(allpclusters)ui.write(' smallest length: %9i\n'%len(allpclusters[0][1]))ui.write(' longer length: %9i\n'%len(allpclusters[-1][1]))median=len(allpclusters[nbcluster//2][1])ui.write(' median length: %9i\n'%median)mean=sum(len(x[1])forxinallpclusters)//nbclusterui.write(' mean length: %9i\n'%mean)@command('^evolve|stabilize|solve',[('n','dry-run',False,'do not perform actions, just print what would be done'),('','confirm',False,'ask for confirmation before performing the action'),('A','any',False,'also consider troubled changesets unrelated to current working directory'),('a','all',False,'evolve all troubled changesets in the repo ''(implies any)'),('c','continue',False,'continue an interrupted evolution'),]+mergetoolopts,_('[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 a single changeset is evolved for each invocation and only troubled changesets that would evolve as a descendant of the current working directory will be considered. See --all and --any options to change this behavior. - 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']confirmopt=opts['confirm']ui.setconfig('ui','forcemerge',opts.get('tool',''),'evolve')startnode=repo['.']ifcontopt:ifanyopt:raiseutil.Abort('cannot specify both "--any" and "--continue"')ifallopt:raiseutil.Abort('cannot specify both "--all" and "--continue"')graftcmd=commands.table['graft'][0]returngraftcmd(ui,repo,old_obsolete=True,**{'continue':True})tro=_picknexttroubled(ui,repo,anyoptorallopt)iftroisNone: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:return0else:res=hg.update(repo,ctx.rev())ifctx!=startnode:ui.status(_('working directory is now at %s\n')%ctx)returnrestroubled=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)or1whiletroisnotNone:progresscb()wlock=lock=tr=Nonetry:wlock=repo.wlock()lock=repo.lock()tr=repo.transaction("evolve")result=_evolveany(ui,repo,tro,dryrunopt,confirmopt,progresscb=progresscb)tr.close()finally:lockmod.release(tr,lock,wlock)progresscb()seen+=1ifnotallopt:ifrepo['.']!=startnode:ui.status(_('working directory is now at %s\n')%repo['.'])returnresultprogresscb()tro=_picknexttroubled(ui,repo,anyoptorallopt)ifallopt:ui.progress('evolve',None)ifrepo['.']!=startnode:ui.status(_('working directory is now at %s\n')%repo['.'])def_evolveany(ui,repo,tro,dryrunopt,confirmopt,progresscb):repo=repo.unfiltered()tro=repo[tro.rev()]cmdutil.bailifchanged(repo)troubles=tro.troubles()if'unstable'introubles:return_solveunstable(ui,repo,tro,dryrunopt,confirmopt,progresscb)elif'bumped'introubles:return_solvebumped(ui,repo,tro,dryrunopt,confirmopt,progresscb)elif'divergent'introubles:repo=repo.unfiltered()tro=repo[tro.rev()]return_solvedivergent(ui,repo,tro,dryrunopt,confirmopt,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()tro=_stabilizableunstable(repo,repo['.'])iftroisNone:wdp=repo['.']if'divergent'inwdp.troubles():tro=wdpiftroisNoneandpickany:troubled=list(repo.set('unstable()'))ifnottroubled:troubled=list(repo.set('bumped()'))ifnottroubled:troubled=list(repo.set('divergent()'))iftroubled:tro=troubled[0]returntrodef_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.directdesc=set([pctx.rev()])forctxinselfanddescendants(repo,pctx):forchildinctx.children():ifctx.rev()indirectdescandnotchild.obsolete():directdesc.add(child.rev())elifchild.unstable():returnchildreturnNonedef_solveunstable(ui,repo,orig,dryrun=False,confirm=False,progresscb=None):"""Stabilize a unstable changeset"""obs=orig.parents()[0]ifnotobs.obsolete():obs=orig.parents()[1]# second parent is obsolete ?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\n"%obs)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]ifnotui.quietorconfirm:repo.ui.write(_('move:'))displayer.show(orig)repo.ui.write(_('atop:'))displayer.show(target)ifconfirmandui.prompt('perform evolve? [Ny]')!='y':raiseutil.Abort(_('evolve aborted by user'))ifprogresscb:progresscb()todo='hg rebase -r %s -d %s\n'%(orig,target)ifdryrun:repo.ui.write(todo)else:repo.ui.note(todo)ifprogresscb:progresscb()keepbranch=orig.p1().branch()!=orig.branch()try:relocate(repo,orig,target,keepbranch)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'))raisedef_solvebumped(ui,repo,bumped,dryrun=False,confirm=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})ifnotui.quietorconfirm:repo.ui.write(_('recreate:'))displayer.show(bumped)repo.ui.write(_('atop:'))displayer.show(prec)ifconfirmandui.prompt('perform evolve? [Ny]')!='y':raiseutil.Abort(_('evolve aborted by user'))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()newid=tmpctx=Nonetmpctx=bumpedbmupdate=_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]obsolete.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().items():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=memfilectx(repo,fctx.path(),fctx.data(),islink='l'inflags,isexec='x'inflags,copied=copied.get(path))returnmctxreturnNonetext='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:obsolete.createmarkers(repo,[(tmpctx,())])newid=prec.node()else:phases.retractboundary(repo,tr,bumped.phase(),[newid])obsolete.createmarkers(repo,[(tmpctx,(repo[newid],))],flag=obsolete.bumpedfix)bmupdate(newid)tr.close()repo.ui.status(_('committed as %s\n')%node.short(newid))finally:tr.release()# reroute the working copy parent to the new changesetrepo.dirstate.beginparentchange()repo.dirstate.setparents(newid,node.nullid)repo.dirstate.endparentchange()def_solvedivergent(ui,repo,divergent,dryrun=False,confirm=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 ""such 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=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 means redoing the merge and using ""| `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.\n""| With the current state of its implementation, \n""| evolve does not work in that case.\n""| rebase one of them next to the other and run \n""| this command again.\n""| - either: hg rebase --dest 'p1(%(d)s)' -r %(o)s\n""| - or: hg rebase --dest 'p1(%(o)s)' -r %(d)s"%{'d':divergent,'o':other})displayer=cmdutil.show_changeset(ui,repo,{'template':shorttemplate})ifnotui.quietorconfirm:ui.write(_('merge:'))displayer.show(divergent)ui.write(_('with: '))displayer.show(other)ui.write(_('base: '))displayer.show(base)ifconfirmandui.prompt('perform evolve? [Ny]')!='y':raiseutil.Abort(_('evolve aborted by user'))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)returnifdivergentnotinrepo[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 ''(this is not automated yet)',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.beginparentchange()repo.dirstate.setparents(divergent.node(),node.nullid)repo.dirstate.endparentchange()oldlen=len(repo)amend(ui,repo,message='',logfile='')ifoldlen==len(repo):new=divergent# no changeselse:new=repo['.']obsolete.createmarkers(repo,[(other,(new,))])phases.retractboundary(repo,tr,other.phase(),[new.node()])tr.close()finally:tr.release()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 %s not found"%ctx,hint='this case is not yet handled')shorttemplate='[{rev}] {desc|firstline}\n'@command('^previous',[('B','move-bookmark',False,_('Move current active bookmark after update'))],'[-B]')defcmdprevious(ui,repo,**opts):"""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=opts.get('move_bookmark')andbmisnotNoneret=hg.update(repo,p.rev())ifnotret:ifshouldmove:repo._bookmarks[bm]=p.node()repo._bookmarks.write()else:bookmarks.unsetcurrent(repo)displayer.show(p)return0else:forpinparents:displayer.show(p)ui.warn(_('multiple parents, explicitly update to one\n'))return1@command('^next',[('B','move-bookmark',False,_('Move current active bookmark after update'))],'[-B]')defcmdnext(ui,repo,**opts):"""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=opts.get('move_bookmark')andbmisnotNoneret=hg.update(repo,c.rev())ifnotret:ifshouldmove:repo._bookmarks[bm]=c.node()repo._bookmarks.write()else:bookmarks.unsetcurrent(repo)displayer.show(c)return0else:forcinchildren:displayer.show(c)ui.warn(_('multiple non-obsolete children, ''explicitly update to one of them\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=set(revs)revs.update(set(rsrevs))revs=sorted(revs)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=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=Nonetry:wlock=repo.wlock()lock=repo.lock()# defines pruned changesetsprecs=[]revs.sort()forpinrevs:cp=repo[p]ifnotcp.mutable():# note: createmarkers() would have raised 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=scmutil.revrange(repo,succs)sucs.sort()sucs=tuple(repo[n]forninsucs)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 markersobsolete.createmarkers(repo,relations,metadata=metadata)# informs that changeset have been prunedui.status(_('%i changesets pruned\n')%len(precs))wdp=repo['.']iflen(sucs)==1andlen(precs)==1andwdpinprecs:# '.' killed, so update to the successornewnode=sucs[0]else:# update to an unkilled parentnewnode=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):# used to be:## ldest = list(repo.set('max((::%d) - obsolete())', ctx))# if ldest:# c = ldest[0]## but then revset took a lazy arrow in the knee and became much# slower. The new forms makes as much sense and a much faster.fordestinctx.ancestors():ifnotdest.obsolete():updatebookmarks=_bookmarksupdater(repo,ctx.node())updatebookmarks(dest.node())breakfinally: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+commitopts3,_('[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)log=opts.get('logfile')opts['amend']=Trueifnot(editoropts['message']orlog):opts['message']=repo['.'].description()_resolveoptions(ui,opts)_alias,commitcmd=cmdutil.findcmd('commit',commands.table)returncommitcmd[0](ui,repo,*pats,**opts)def_touchedbetween(repo,source,dest,match=None):touched=set()forfilesinrepo.status(source,dest,match=match)[:3]:touched.update(files)returntoucheddef_commitfiltered(repo,ctx,match,target=None):"""Recommit ctx with changed files not in match. Return the new node identifier, or None if nothing changed. """base=ctx.p1()iftargetisNone:target=base# ctxinitialfiles=_touchedbetween(repo,base,ctx)ifbase==target:affected=set(fforfininitialfilesifmatch(f))newcontent=set()else:affected=_touchedbetween(repo,target,ctx,match=match)newcontent=_touchedbetween(repo,target,base,match=match)# The commit touchs all existing files# + all file that needs a new content# - the file affected bny uncommit with the same content than base.files=(initialfiles-affected)|newcontentifnotnewcontentandfiles==initialfiles:returnNone# Filter copiescopied=copies.pathcopies(target,ctx)copied=dict((src,dst)forsrc,dstincopied.iteritems()ifdstinfiles)deffilectxfn(repo,memctx,path,contentctx=ctx,redirect=newcontent):ifpathinredirect:returnfilectxfn(repo,memctx,path,contentctx=target,redirect=())ifpathnotincontentctx:returnNonefctx=contentctx[path]flags=fctx.flags()mctx=memfilectx(repo,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')),('r','rev','',_('revert commit content to REV instead')),]+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. The --rev argument let you change the commit file to a content of another revision. It still does not change the content of your file in the working directory. Return 0 if changed files are uncommitted. """wlock=lock=tr=Nonetry:wlock=repo.wlock()lock=repo.lock()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())rev=Noneifopts.get('rev'):rev=scmutil.revsingle(repo,opts.get('rev'))ctx=repo[None]ifctx.p1()==revorctx.p2()==rev:raiseutil.Abort(_("cannot uncommit to parent changeset"))# Recommit the filtered changesettr=repo.transaction('uncommit')newid=Noneif(patsoropts.get('include')oropts.get('exclude')oropts.get('all')):match=scmutil.match(old,pats,opts)newid=_commitfiltered(repo,old,match,target=rev)ifnewidisNone:raiseutil.Abort(_('nothing to uncommit'),hint=_("use --all to uncommit all files"))# Move local changes on filtered changesetobsolete.createmarkers(repo,[(old,(repo[newid],))])phases.retractboundary(repo,tr,oldphase,[newid])repo.dirstate.beginparentchange()repo.dirstate.setparents(newid,node.nullid)_uncommitdirstate(repo,old,match)repo.dirstate.endparentchange()updatebookmarks(newid)ifnotrepo[newid].files():ui.warn(_("new changeset is empty\n"))ui.status(_('(use "hg prune ." to remove it)\n'))tr.close()finally:lockmod.release(tr,lock,wlock)@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:obsolete.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,unusedvariable=rewrite(repo,ctx,[],ctx,[p1,p2],commitopts={'extra':extra})# store touched version to help potential childrennewmapping[ctx.node()]=newifnotduplicate:obsolete.createmarkers(repo,[(ctx,(repo[new],))])phases.retractboundary(repo,tr,ctx.phase(),[new])ifctxinrepo[None].parents():repo.dirstate.beginparentchange()repo.dirstate.setparents(new,node.nullid)repo.dirstate.endparentchange()tr.close()finally:tr.release()finally:lockmod.release(lock,wlock)@command('^fold|squash',[('r','rev',[],_("revision to fold")),('','exact',None,_("only fold specified revisions"))]+commitopts+commitopts2,_('hg fold [OPTION]... [-r] REV'))deffold(ui,repo,*revs,**opts):"""fold multiple revisions into a single one Folds a set of revisions with the parent of the working directory. All revisions linearly between the given revisions and the parent of the working directory will also be folded. Use --exact for folding only the specified revisions while ignoring the parent of the working directory. In this case, the given revisions must form a linear unbroken chain. .. container:: verbose Some examples: - Fold the current revision with its parent:: hg fold .^ - Fold all draft revisions with working directory parent:: hg fold 'draft()' See :hg:`help phases` for more about draft revisions and :hg:`help revsets` for more about the `draft()` keyword - Fold revisions 3, 4, 5, and 6 with the working directory parent:: hg fold 3:6 - Only fold revisions linearly between foo and @:: hg fold foo::@ --exact """revs=list(revs)revs.extend(opts['rev'])ifnotrevs:raiseutil.Abort(_('no revisions specified'))revs=scmutil.revrange(repo,revs)ifnotopts['exact']:# Try to extend given revision starting from the working directoryextrevs=repo.revs('(%ld::.) or (.::%ld)',revs,revs)discardedrevs=[rforrinrevsifrnotinextrevs]ifdiscardedrevs:raiseutil.Abort(_("cannot fold non-linear revisions"),hint=_("given revisions are unrelated to parent ""of working directory"))revs=extrevsiflen(revs)==1:ui.write_err(_('single revision specified, nothing to fold\n'))return1roots=repo.revs('roots(%ld)',revs)iflen(roots)>1:raiseutil.Abort(_("cannot fold non-linear revisions ""(multiple roots given)"))root=repo[roots.first()]ifroot.phase()<=phases.public:raiseutil.Abort(_("cannot fold public revisions"))heads=repo.revs('heads(%ld)',revs)iflen(heads)>1:raiseutil.Abort(_("cannot fold non-linear revisions ""(multiple heads given)"))head=repo[heads.first()]wlock=lock=Nonetry:wlock=repo.wlock()lock=repo.lock()tr=repo.transaction('touch')try:commitopts=opts.copy()allctx=[repo[r]forrinrevs]targetphase=max(c.phase()forcinallctx)ifcommitopts.get('message')orcommitopts.get('logfile'):commitopts['edit']=Falseelse: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,unusedvariable=rewrite(repo,root,allctx,head,[root.p1().node(),root.p2().node()],commitopts=commitopts)phases.retractboundary(repo,tr,targetphase,[newid])obsolete.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):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 (DEPRECATED)")))entry=cmdutil.findcmd('graft',commands.table)[1]entry[1].append(('o','obsolete',[],_("make graft obsoletes this revision (DEPRECATED)")))entry[1].append(('O','old-obsolete',False,_("make graft obsoletes its source (DEPRECATED)")))######################################################################## Obsolescence marker exchange experimenation ########################################################################defobsexcmsg(ui,message,important=False):verbose=ui.configbool('experimental','verbose-obsolescence-exchange',False)ifverbose:message='OBSEXC: '+messageifimportantorverbose:ui.status(message)defobsexcprg(ui,*args,**kwargs):topic='obsmarkers exchange'ifui.configbool('experimental','verbose-obsolescence-exchange',False):topic='OBSEXC'ui.progress(topic,*args,**kwargs)ifgetattr(exchange,'_pushdiscoveryobsmarkers',None)isnotNone:@eh.wrapfunction(exchange,'_pushdiscoveryobsmarkers')def_pushdiscoveryobsmarkers(orig,pushop):if(obsolete._enabledandpushop.repo.obsstoreand'obsolete'inpushop.remote.listkeys('namespaces')):repo=pushop.repoobsexcmsg(repo.ui,"computing relevant nodes\n")revs=list(repo.revs('::%ln',pushop.futureheads))unfi=repo.unfiltered()cl=unfi.changelogifnotpushop.remote.capable('_evoext_obshash_0'):# do not trust core yet# return orig(pushop)nodes=[cl.node(r)forrinrevs]ifnodes:obsexcmsg(repo.ui,"computing markers relevant to %i nodes\n"%len(nodes))pushop.outobsmarkers=repo.obsstore.relevantmarkers(nodes)else:obsexcmsg(repo.ui,"markers already in sync\n")pushop.outobsmarkers=[]pushop.outobsmarkers=repo.obsstore.relevantmarkers(nodes)returncommon=[]obsexcmsg(repo.ui,"looking for common markers in %i nodes\n"%len(revs))commonrevs=list(unfi.revs('::%ln',pushop.outgoing.commonheads))common=findcommonobsmarkers(pushop.ui,unfi,pushop.remote,commonrevs)revs=list(unfi.revs('%ld - (::%ln)',revs,common))nodes=[cl.node(r)forrinrevs]ifnodes:obsexcmsg(repo.ui,"computing markers relevant to %i nodes\n"%len(nodes))pushop.outobsmarkers=repo.obsstore.relevantmarkers(nodes)else:obsexcmsg(repo.ui,"markers already in sync\n")pushop.outobsmarkers=[]@eh.wrapfunction(wireproto,'capabilities')defdiscocapabilities(orig,repo,proto):"""wrapper to advertise new capability"""caps=orig(repo,proto)ifobsolete._enabled:caps+=' _evoext_obshash_0'returncaps@eh.extsetupdef_installobsmarkersdiscovery(ui):hgweb_mod.perms['evoext_obshash']='pull'# wrap command contentoldcap,args=wireproto.commands['capabilities']defnewcap(repo,proto):returndiscocapabilities(oldcap,repo,proto)wireproto.commands['capabilities']=(newcap,args)wireproto.commands['evoext_obshash']=(srv_obshash,'nodes')ifgetattr(exchange,'_pushdiscoveryobsmarkers',None)isNone:ui.warn('evolve: your mercurial version is too old\n''evolve: (running in degraded mode, push will includes all markers)\n')else:olddisco=exchange.pushdiscoverymapping['obsmarker']defnewdisco(pushop):_pushdiscoveryobsmarkers(olddisco,pushop)exchange.pushdiscoverymapping['obsmarker']=newdisco### Set discovery STARTfrommercurialimportdagutilfrommercurialimportsetdiscoverydef_obshash(repo,nodes):hashs=_obsrelsethashtree(repo)nm=repo.changelog.nodemaprevs=[nm.get(n)forninnodes]return[risNoneandnullidorhashs[r][1]forrinrevs]defsrv_obshash(repo,proto,nodes):returnwireproto.encodelist(_obshash(repo,wireproto.decodelist(nodes)))@eh.addattr(localrepo.localpeer,'evoext_obshash')deflocal_obshash(peer,nodes):return_obshash(peer._repo,nodes)@eh.addattr(wireproto.wirepeer,'evoext_obshash')defpeer_obshash(self,nodes):d=self._call("evoext_obshash",nodes=wireproto.encodelist(nodes))try:returnwireproto.decodelist(d)exceptValueError:self._abort(error.ResponseError(_("unexpected response:"),d))deffindcommonobsmarkers(ui,local,remote,probeset,initialsamplesize=100,fullsamplesize=200):# from discoveryroundtrips=0cl=local.changelogdag=dagutil.revlogdag(cl)localhash=_obsrelsethashtree(local)missing=set()common=set()undecided=set(probeset)_takefullsample=setdiscovery._takefullsamplewhileundecided:ui.note(_("sampling from both directions\n"))iflen(undecided)<fullsamplesize:sample=set(undecided)else:sample=_takefullsample(dag,undecided,size=fullsamplesize)roundtrips+=1ui.debug("query %i; still undecided: %i, sample size is: %i\n"%(roundtrips,len(undecided),len(sample)))# indices between sample and externalized version must matchsample=list(sample)remotehash=remote.evoext_obshash(dag.externalizeall(sample))yesno=[localhash[ix][1]==remotehash[si]forsi,ixinenumerate(sample)]commoninsample=set(nfori,ninenumerate(sample)ifyesno[i])common.update(dag.ancestorset(commoninsample,common))missinginsample=[nfori,ninenumerate(sample)ifnotyesno[i]]missing.update(dag.descendantset(missinginsample,missing))undecided.difference_update(missing)undecided.difference_update(common)result=dag.headsetofconnecteds(common)ui.debug("%d total queries\n"%roundtrips)ifnotresult:returnset([nullid])returndag.externalizeall(result)_pushkeyescape=getattr(obsolete,'_pushkeyescape',None)classpushobsmarkerStringIO(StringIO):"""hacky string io for progress"""@util.propertycachedeflength(self):returnlen(self.getvalue())defread(self,size=None):obsexcprg(self.ui,self.tell(),unit="bytes",total=self.length)returnStringIO.read(self,size)def__iter__(self):d=self.read(4096)whiled:yielddd=self.read(4096)@eh.wrapfunction(exchange,'_pushobsolete')def_pushobsolete(orig,pushop):"""utility function to push obsolete markers to a remote"""stepsdone=getattr(pushop,'stepsdone',None)ifstepsdoneisnotNone:if'obsmarkers'instepsdone:returnstepsdone.add('obsmarkers')ifutil.safehasattr(pushop,'cgresult'):cgresult=pushop.cgresultelse:cgresult=pushop.retifcgresult==0:returnpushop.ui.debug('try to push obsolete markers to remote\n')repo=pushop.reporemote=pushop.remoteunfi=repo.unfiltered()cl=unfi.changelogif(obsolete._enabledandrepo.obsstoreand'obsolete'inremote.listkeys('namespaces')):markers=pushop.outobsmarkersifnotmarkers:obsexcmsg(repo.ui,"no marker to push\n")elifremote.capable('_evoext_pushobsmarkers_0'):obsdata=pushobsmarkerStringIO()forchunkinobsolete.encodemarkers(markers,True):obsdata.write(chunk)obsdata.seek(0)obsdata.ui=repo.uiobsexcmsg(repo.ui,"pushing %i obsolescence markers (%i bytes)\n"%(len(markers),len(obsdata.getvalue())),True)remote.evoext_pushobsmarkers_0(obsdata)obsexcprg(repo.ui,None)else:rslts=[]remotedata=_pushkeyescape(markers).items()totalbytes=sum(len(d)fork,dinremotedata)sentbytes=0obsexcmsg(repo.ui,"pushing %i obsolescence markers in %i pushkey payload (%i bytes)\n"%(len(markers),len(remotedata),totalbytes),True)forkey,datainremotedata:obsexcprg(repo.ui,sentbytes,item=key,unit="bytes",total=totalbytes)rslts.append(remote.pushkey('obsolete',key,'',data))sentbytes+=len(data)obsexcprg(repo.ui,sentbytes,item=key,unit="bytes",total=totalbytes)obsexcprg(repo.ui,None)if[rforrinrsltsifnotr]:msg=_('failed to push some obsolete markers!\n')repo.ui.warn(msg)obsexcmsg(repo.ui,"DONE\n")@eh.addattr(wireproto.wirepeer,'evoext_pushobsmarkers_0')defclient_pushobsmarkers(self,obsfile):"""wireprotocol peer method"""self.requirecap('_evoext_pushobsmarkers_0',_('push obsolete markers faster'))ret,output=self._callpush('evoext_pushobsmarkers_0',obsfile)forlinoutput.splitlines(True):self.ui.status(_('remote: '),l)returnret@eh.addattr(httppeer.httppeer,'evoext_pushobsmarkers_0')defhttpclient_pushobsmarkers(self,obsfile):"""httpprotocol peer method (Cannot simply use _callpush as http is doing some special handling)"""self.requirecap('_evoext_pushobsmarkers_0',_('push obsolete markers faster'))ret,output=self._call('evoext_pushobsmarkers_0',data=obsfile)forlinoutput.splitlines(True):ifl.strip():self.ui.status(_('remote: '),l)returnret@eh.wrapfunction(localrepo.localrepository,'_restrictcapabilities')deflocal_pushobsmarker_capabilities(orig,repo,caps):caps=orig(repo,caps)caps.add('_evoext_pushobsmarkers_0')returncaps@eh.addattr(localrepo.localpeer,'evoext_pushobsmarkers_0')deflocal_pushobsmarkers(peer,obsfile):data=obsfile.read()lock=peer._repo.lock()try:tr=peer._repo.transaction('pushkey: obsolete markers')try:new=peer._repo.obsstore.mergemarkers(tr,data)ifnewisnotNone:obsexcmsg(peer._repo.ui,"%i obsolescence markers added\n"%new,True)tr.close()finally:tr.release()finally:lock.release()peer._repo.hook('evolve_pushobsmarkers')defsrv_pushobsmarkers(repo,proto):"""wireprotocol command"""fp=StringIO()proto.redirect()proto.getfile(fp)data=fp.getvalue()fp.close()lock=repo.lock()try:tr=repo.transaction('pushkey: obsolete markers')try:new=repo.obsstore.mergemarkers(tr,data)ifnewisnotNone:obsexcmsg(repo.ui,"%i obsolescence markers added\n"%new,True)tr.close()finally:tr.release()finally:lock.release()repo.hook('evolve_pushobsmarkers')returnwireproto.pushres(0)def_buildpullobsmarkersboundaries(pullop):"""small funtion returning the argument for pull markers call may to contains 'heads' and 'common'. skip the key for None. Its a separed functio to play around with strategy for that."""repo=pullop.repocl=pullop.repo.changelogremote=pullop.remoteunfi=repo.unfiltered()revs=unfi.revs('::(%ln - null)',pullop.common)common=[nullid]ifremote.capable('_evoext_obshash_0'):obsexcmsg(repo.ui,"looking for common markers in %i nodes\n"%len(revs))common=findcommonobsmarkers(repo.ui,repo,remote,revs)return{'heads':pullop.pulledsubset,'common':common}@eh.uisetupdefaddgetbundleargs(self):gboptsmap['evo_obscommon']='nodes'@eh.wrapfunction(exchange,'_pullbundle2extraprepare')def_addobscommontob2pull(orig,pullop,kwargs):ret=orig(pullop,kwargs)if'obsmarkers'inkwargsandpullop.remote.capable('_evoext_getbundle_obscommon'):boundaries=_buildpullobsmarkersboundaries(pullop)common=boundaries['common']ifcommon!=[nullid]:kwargs['evo_obscommon']=commonreturnretifgetattr(exchange,'_getbundleobsmarkerpart',None)isnotNone:@eh.wrapfunction(exchange,'_getbundleobsmarkerpart')def_getbundleobsmarkerpart(orig,bundler,repo,source,heads=None,common=None,bundlecaps=None,**kwargs):if'evo_obscommon'notinkwargs:returnorig(bundler,repo,source,heads,common,bundlecaps,**kwargs)ifkwargs.get('obsmarkers',False):ifheadsisNone:heads=repo.heads()obscommon=kwargs.get('evo_obscommon',())obsset=repo.set('::%ln - ::%ln',heads,obscommon)subset=[c.node()forcinobsset]markers=repo.obsstore.relevantmarkers(subset)exchange.buildobsmarkerspart(bundler,markers)@eh.wrapfunction(exchange,'_pullobsolete')def_pullobsolete(orig,pullop):ifnotobsolete._enabled:returnNoneif'obsmarkers'notingetattr(pullop,'todosteps',['obsmarkers']):returnNoneif'obsmarkers'ingetattr(pullop,'stepsdone',[]):returnNonewirepull=pullop.remote.capable('_evoext_pullobsmarkers_0')ifnotwirepull:returnorig(pullop)if'obsolete'notinpullop.remote.listkeys('namespaces'):returnNone# remote opted out of obsolescence marker exchangetr=Noneui=pullop.repo.uiboundaries=_buildpullobsmarkersboundaries(pullop)ifnotset(boundaries['heads'])-set(boundaries['common']):obsexcmsg(ui,"nothing to pull\n")returnNoneobsexcmsg(ui,"pull obsolescence markers\n",True)new=0ifwirepull:obsdata=pullop.remote.evoext_pullobsmarkers_0(**boundaries)obsdata=obsdata.read()iflen(obsdata)>5:obsexcmsg(ui,"merging obsolescence markers (%i bytes)\n"%len(obsdata))tr=pullop.gettransaction()old=len(pullop.repo.obsstore._all)pullop.repo.obsstore.mergemarkers(tr,obsdata)new=len(pullop.repo.obsstore._all)-oldobsexcmsg(ui,"%i obsolescence markers added\n"%new,True)else:obsexcmsg(ui,"no unknown remote markers\n")obsexcmsg(ui,"DONE\n")ifnew:pullop.repo.invalidatevolatilesets()returntrdef_getobsmarkersstream(repo,heads=None,common=None):revset=''args=[]repo=repo.unfiltered()ifheadsisNone:revset='all()'elifheads:revset+="(::%ln)"args.append(heads)else:assertFalse,'pulling no heads?'ifcommon:revset+=' - (::%ln)'args.append(common)nodes=[c.node()forcinrepo.set(revset,*args)]markers=repo.obsstore.relevantmarkers(nodes)obsdata=StringIO()forchunkinobsolete.encodemarkers(markers,True):obsdata.write(chunk)obsdata.seek(0)returnobsdata@eh.addattr(wireproto.wirepeer,'evoext_pullobsmarkers_0')defclient_pullobsmarkers(self,heads=None,common=None):self.requirecap('_evoext_pullobsmarkers_0',_('look up remote obsmarkers'))opts={}ifheadsisnotNone:opts['heads']=wireproto.encodelist(heads)ifcommonisnotNone:opts['common']=wireproto.encodelist(common)ifutil.safehasattr(self,'_callcompressable'):f=self._callcompressable("evoext_pullobsmarkers_0",**opts)else:f=self._callstream("evoext_pullobsmarkers_0",**opts)f=self._decompress(f)length=int(f.read(20))chunk=4096current=0data=StringIO()ui=self.uiobsexcprg(ui,current,unit="bytes",total=length)whilecurrent<length:readsize=min(length-current,chunk)data.write(f.read(readsize))current+=readsizeobsexcprg(ui,current,unit="bytes",total=length)obsexcprg(ui,None)data.seek(0)returndata@eh.addattr(localrepo.localpeer,'evoext_pullobsmarkers_0')deflocal_pullobsmarkers(self,heads=None,common=None):return_getobsmarkersstream(self._repo,heads=heads,common=common)defsrv_pullobsmarkers(repo,proto,others):opts=wireproto.options('',['heads','common'],others)fork,vinopts.iteritems():ifkin('heads','common'):opts[k]=wireproto.decodelist(v)obsdata=_getobsmarkersstream(repo,**opts)finaldata=StringIO()obsdata=obsdata.getvalue()finaldata.write('%20i'%len(obsdata))finaldata.write(obsdata)finaldata.seek(0)returnwireproto.streamres(proto.groupchunks(finaldata))def_obsrelsethashtree(repo):cache=[]unfi=repo.unfiltered()foriinunfi:ctx=unfi[i]entry=0sha=util.sha1()# add data from p1forpinctx.parents():p=p.rev()ifp<0:p=nullidelse:p=cache[p][1]ifp!=nullid:entry+=1sha.update(p)tmarkers=repo.obsstore.relevantmarkers([ctx.node()])iftmarkers:bmarkers=[obsolete._fm0encodeonemarker(m)formintmarkers]bmarkers.sort()forminbmarkers:entry+=1sha.update(m)ifentry:cache.append((ctx.node(),sha.digest()))else:cache.append((ctx.node(),nullid))returncache@command('debugobsrelsethashtree',[],_(''))defdebugobsrelsethashtree(ui,repo):"""display Obsolete markers, Relevant Set, Hash Tree changeset-node obsrelsethashtree-node It computed form the "orsht" of its parent and markers relevant to the changeset itself."""forchg,obsin_obsrelsethashtree(repo):ui.status('%s%s\n'%(node.hex(chg),node.hex(obs)))_bestformat=max(obsolete.formats.keys())@command('debugobsconvert',[('','new-format',_bestformat,_('Destination format for markers.'))],'')defdebugobsconvert(ui,repo,new_format):ifnew_format==repo.obsstore._version:msg=_('New format is the same as the old format, not upgrading!')raiseutil.Abort(msg)f=repo.sopener('obsstore','wb',atomictemp=True)origmarkers=repo.obsstore._allknown=set()markers=[]forminorigmarkers:ifminknown:continueknown.add(m)markers.append(m)ui.write(_('Old store is version %d, will rewrite in version %d\n')%(repo.obsstore._version,new_format))map(f.write,obsolete.encodemarkers(markers,True,new_format))f.close()ui.write(_('Done!\n'))@eh.wrapfunction(wireproto,'capabilities')defcapabilities(orig,repo,proto):"""wrapper to advertise new capability"""caps=orig(repo,proto)ifobsolete._enabled:caps+=' _evoext_pushobsmarkers_0'caps+=' _evoext_pullobsmarkers_0'caps+=' _evoext_obshash_0'caps+=' _evoext_getbundle_obscommon'returncaps@eh.extsetupdef_installwireprotocol(ui):localrepo.moderncaps.add('_evoext_pullobsmarkers_0')hgweb_mod.perms['evoext_pushobsmarkers_0']='push'hgweb_mod.perms['evoext_pullobsmarkers_0']='pull'wireproto.commands['evoext_pushobsmarkers_0']=(srv_pushobsmarkers,'')wireproto.commands['evoext_pullobsmarkers_0']=(srv_pullobsmarkers,'*')# wrap command contentoldcap,args=wireproto.commands['capabilities']defnewcap(repo,proto):returncapabilities(oldcap,repo,proto)wireproto.commands['capabilities']=(newcap,args)