Eliminate potential reference cycles from kwrepo
- delete kwrepo.commitctx after using the tweaked version
- prefer self.hook over repo.hook to avoid nesting
Also pass arguments to commit as arbitrary list.
Thanks to Simon Heimberg and Matt Mackall for guidance.
# keyword.py - $Keyword$ expansion for Mercurial## Copyright 2007, 2008 Christian Ebert <blacktrash@gmx.net>## This software may be used and distributed according to the terms of the# GNU General Public License version 2, incorporated herein by reference.## $Id$## Keyword expansion hack against the grain of a DSCM## There are many good reasons why this is not needed in a distributed# SCM, still it may be useful in very small projects based on single# files (like LaTeX packages), that are mostly addressed to an# audience not running a version control system.## For in-depth discussion refer to# <http://www.selenic.com/mercurial/wiki/index.cgi/KeywordPlan>.## Keyword expansion is based on Mercurial's changeset template mappings.## Binary files are not touched.## Files to act upon/ignore are specified in the [keyword] section.# Customized keyword template mappings in the [keywordmaps] section.## Run "hg help keyword" and "hg kwdemo" to get info on configuration.'''expand keywords in tracked filesThis extension expands RCS/CVS-like or self-customized $Keywords$ in trackedtext files selected by your configuration.Keywords are only expanded in local repositories and not stored in the changehistory. The mechanism can be regarded as a convenience for the current useror for archive distribution.Configuration is done in the [keyword] and [keywordmaps] sections of hgrcfiles.Example: [keyword] # expand keywords in every python file except those matching "x*" **.py = x* = ignoreNote: the more specific you are in your filename patterns the less you lose speed in huge repositories.For [keywordmaps] template mapping and expansion demonstration and control run"hg kwdemo".An additional date template filter {date|utcdate} is provided.The default template mappings (view with "hg kwdemo -d") can be replaced withcustomized keywords and templates. Again, run "hg kwdemo" to control theresults of your config changes.Before changing/disabling active keywords, run "hg kwshrink" to avoid the riskof inadvertently storing expanded keywords in the change history.To force expansion after enabling it, or a configuration change, run "hgkwexpand".Also, when committing with the record extension or using mq's qrecord, beaware that keywords cannot be updated. Again, run "hg kwexpand" on the filesin question to update keyword expansions after all changes have been checkedin.Expansions spanning more than one line and incremental expansions, like CVS'$Log$, are not supported. A keyword template map "Log = {desc}" expands to thefirst line of the changeset description.'''frommercurialimportcommands,cmdutil,dispatch,filelog,revlog,extensionsfrommercurialimportpatch,localrepo,templater,templatefilters,util,matchfrommercurial.hgwebimportwebcommandsfrommercurial.lockimportreleasefrommercurial.nodeimportnullidfrommercurial.i18nimport_importre,shutil,tempfile,timecommands.optionalrepo+=' kwdemo'# hg commands that do not act on keywordsnokwcommands=('add addremove annotate bundle copy export grep incoming init'' log outgoing push rename rollback tip verify'' convert email glog')# hg commands that trigger expansion only when writing to working dir,# not when reading filelog, and unexpand when reading from working dirrestricted='merge record resolve qfold qimport qnew qpush qrefresh qrecord'defutcdate(date):'''Returns hgdate in cvs-like UTC format.'''returntime.strftime('%Y/%m/%d %H:%M:%S',time.gmtime(date[0]))# make keyword tools accessiblekwtools={'templater':None,'hgcmd':'','inc':[],'exc':['.hg*']}classkwtemplater(object):''' Sets up keyword templates, corresponding keyword regex, and provides keyword substitution functions. '''templates={'Revision':'{node|short}','Author':'{author|user}','Date':'{date|utcdate}','RCSFile':'{file|basename},v','Source':'{root}/{file},v','Id':'{file|basename},v {node|short} {date|utcdate} {author|user}','Header':'{root}/{file},v {node|short} {date|utcdate} {author|user}',}def__init__(self,ui,repo):self.ui=uiself.repo=repoself.match=match.match(repo.root,'',[],kwtools['inc'],kwtools['exc'])self.restrict=kwtools['hgcmd']inrestricted.split()kwmaps=self.ui.configitems('keywordmaps')ifkwmaps:# override default templatesself.templates=dict((k,templater.parsestring(v,False))fork,vinkwmaps)escaped=map(re.escape,self.templates.keys())kwpat=r'\$(%s)(: [^$\n\r]*? )??\$'%'|'.join(escaped)self.re_kw=re.compile(kwpat)templatefilters.filters['utcdate']=utcdateself.ct=cmdutil.changeset_templater(self.ui,self.repo,False,None,'',False)defsubstitute(self,data,path,ctx,subfunc):'''Replaces keywords in data with expanded template.'''defkwsub(mobj):kw=mobj.group(1)self.ct.use_template(self.templates[kw])self.ui.pushbuffer()self.ct.show(ctx,root=self.repo.root,file=path)ekw=templatefilters.firstline(self.ui.popbuffer())return'$%s: %s $'%(kw,ekw)returnsubfunc(kwsub,data)defexpand(self,path,node,data):'''Returns data with keywords expanded.'''ifnotself.restrictandself.match(path)andnotutil.binary(data):ctx=self.repo.filectx(path,fileid=node).changectx()returnself.substitute(data,path,ctx,self.re_kw.sub)returndatadefiskwfile(self,path,flagfunc):'''Returns true if path matches [keyword] pattern and is not a symbolic link. Caveat: localrepository._link fails on Windows.'''returnself.match(path)andnot'l'inflagfunc(path)defoverwrite(self,node,expand,files):'''Overwrites selected files expanding/shrinking keywords.'''ctx=self.repo[node]mf=ctx.manifest()ifnodeisnotNone:# commitfiles=[fforfinctx.files()iffinmf]notify=self.ui.debugelse:# kwexpand/kwshrinknotify=self.ui.notecandidates=[fforfinfilesifself.iskwfile(f,ctx.flags)]ifcandidates:self.restrict=True# do not expand when readingmsg=(expandand_('overwriting %s expanding keywords\n')or_('overwriting %s shrinking keywords\n'))forfincandidates:fp=self.repo.file(f)data=fp.read(mf[f])ifutil.binary(data):continueifexpand:ifnodeisNone:ctx=self.repo.filectx(f,fileid=mf[f]).changectx()data,found=self.substitute(data,f,ctx,self.re_kw.subn)else:found=self.re_kw.search(data)iffound:notify(msg%f)self.repo.wwrite(f,data,mf.flags(f))ifnodeisNone:self.repo.dirstate.normal(f)self.restrict=Falsedefshrinktext(self,text):'''Unconditionally removes all keyword substitutions from text.'''returnself.re_kw.sub(r'$\1$',text)defshrink(self,fname,text):'''Returns text with all keyword substitutions removed.'''ifself.match(fname)andnotutil.binary(text):returnself.shrinktext(text)returntextdefshrinklines(self,fname,lines):'''Returns lines with keyword substitutions removed.'''ifself.match(fname):text=''.join(lines)ifnotutil.binary(text):returnself.shrinktext(text).splitlines(True)returnlinesdefwread(self,fname,data):'''If in restricted mode returns data read from wdir with keyword substitutions removed.'''returnself.restrictandself.shrink(fname,data)ordataclasskwfilelog(filelog.filelog):''' Subclass of filelog to hook into its read, add, cmp methods. Keywords are "stored" unexpanded, and processed on reading. '''def__init__(self,opener,kwt,path):super(kwfilelog,self).__init__(opener,path)self.kwt=kwtself.path=pathdefread(self,node):'''Expands keywords when reading filelog.'''data=super(kwfilelog,self).read(node)returnself.kwt.expand(self.path,node,data)defadd(self,text,meta,tr,link,p1=None,p2=None):'''Removes keyword substitutions when adding to filelog.'''text=self.kwt.shrink(self.path,text)returnsuper(kwfilelog,self).add(text,meta,tr,link,p1,p2)defcmp(self,node,text):'''Removes keyword substitutions for comparison.'''text=self.kwt.shrink(self.path,text)ifself.renamed(node):t2=super(kwfilelog,self).read(node)returnt2!=textreturnrevlog.revlog.cmp(self,node,text)def_status(ui,repo,kwt,unknown,*pats,**opts):'''Bails out if [keyword] configuration is not active. Returns status of working directory.'''ifkwt:match=cmdutil.match(repo,pats,opts)returnrepo.status(match=match,unknown=unknown,clean=True)ifui.configitems('keyword'):raiseutil.Abort(_('[keyword] patterns cannot match'))raiseutil.Abort(_('no [keyword] patterns configured'))def_kwfwrite(ui,repo,expand,*pats,**opts):'''Selects files and passes them to kwtemplater.overwrite.'''ifrepo.dirstate.parents()[1]!=nullid:raiseutil.Abort(_('outstanding uncommitted merge'))kwt=kwtools['templater']status=_status(ui,repo,kwt,False,*pats,**opts)modified,added,removed,deleted=status[:4]ifmodifiedoraddedorremovedordeleted:raiseutil.Abort(_('outstanding uncommitted changes'))wlock=lock=Nonetry:wlock=repo.wlock()lock=repo.lock()kwt.overwrite(None,expand,status[6])finally:release(lock,wlock)defdemo(ui,repo,*args,**opts):'''print [keywordmaps] configuration and an expansion example Show current, custom, or default keyword template maps and their expansions. Extend current configuration by specifying maps as arguments and optionally by reading from an additional hgrc file. Override current keyword template maps with "default" option. '''defdemoitems(section,items):ui.write('[%s]\n'%section)fork,vinitems:ui.write('%s = %s\n'%(k,v))msg='hg keyword config and expansion example'kwstatus='current'fn='demo.txt'branchname='demobranch'tmpdir=tempfile.mkdtemp('','kwdemo.')ui.note(_('creating temporary repository at %s\n')%tmpdir)repo=localrepo.localrepository(ui,tmpdir,True)ui.setconfig('keyword',fn,'')ifargsoropts.get('rcfile'):kwstatus='custom'ifopts.get('rcfile'):ui.readconfig(opts.get('rcfile'))ifopts.get('default'):kwstatus='default'kwmaps=kwtemplater.templatesifui.configitems('keywordmaps'):# override maps from optional rcfilefork,vinkwmaps.iteritems():ui.setconfig('keywordmaps',k,v)elifargs:# simulate hgrc parsingrcmaps=['[keywordmaps]\n']+[a+'\n'forainargs]fp=repo.opener('hgrc','w')fp.writelines(rcmaps)fp.close()ui.readconfig(repo.join('hgrc'))ifnotopts.get('default'):kwmaps=dict(ui.configitems('keywordmaps'))orkwtemplater.templatesuisetup(ui)reposetup(ui,repo)fork,vinui.configitems('extensions'):ifk.endswith('keyword'):extension='%s = %s'%(k,v)breakui.status(_('\n\tconfig using %s keyword template maps\n')%kwstatus)ui.write('[extensions]\n%s\n'%extension)demoitems('keyword',ui.configitems('keyword'))demoitems('keywordmaps',kwmaps.iteritems())keywords='$'+'$\n$'.join(kwmaps.keys())+'$\n'repo.wopener(fn,'w').write(keywords)repo.add([fn])path=repo.wjoin(fn)ui.note(_('\n%s keywords written to %s:\n')%(kwstatus,path))ui.note(keywords)ui.note('\nhg -R "%s" branch "%s"\n'%(tmpdir,branchname))# silence branch command if not verbosequiet=ui.quietui.quiet=notui.verbosecommands.branch(ui,repo,branchname)ui.quiet=quietforname,cmdinui.configitems('hooks'):ifname.split('.',1)[0].find('commit')>-1:repo.ui.setconfig('hooks',name,'')ui.note(_('unhooked all commit hooks\n'))ui.note('hg -R "%s" ci -m "%s"\n'%(tmpdir,msg))repo.commit(text=msg)fmt=ui.verboseand' in %s'%pathor''ui.status(_('\n\t%s keywords expanded%s\n')%(kwstatus,fmt))ui.write(repo.wread(fn))ui.debug(_('\nremoving temporary repository %s\n')%tmpdir)shutil.rmtree(tmpdir,ignore_errors=True)defexpand(ui,repo,*pats,**opts):'''expand keywords in the working directory Run after (re)enabling keyword expansion. kwexpand refuses to run if given files contain local changes. '''# 3rd argument sets expansion to True_kwfwrite(ui,repo,True,*pats,**opts)deffiles(ui,repo,*pats,**opts):'''show files configured for keyword expansion List which files in the working directory are matched by the [keyword] configuration patterns. Useful to prevent inadvertent keyword expansion and to speed up execution by including only files that are actual candidates for expansion. See "hg help keyword" on how to construct patterns both for inclusion and exclusion of files. Use -u/--untracked to list untracked files as well. With -a/--all and -v/--verbose the codes used to show the status of files are: K = keyword expansion candidate k = keyword expansion candidate (untracked) I = ignored i = ignored (untracked) '''kwt=kwtools['templater']status=_status(ui,repo,kwt,opts.get('untracked'),*pats,**opts)modified,added,removed,deleted,unknown,ignored,clean=statusfiles=sorted(modified+added+clean)wctx=repo[None]kwfiles=[fforfinfilesifkwt.iskwfile(f,wctx.flags)]kwuntracked=[fforfinunknownifkwt.iskwfile(f,wctx.flags)]cwd=patsandrepo.getcwd()or''kwfstats=(notopts.get('ignore')and(('K',kwfiles),('k',kwuntracked),)or())ifopts.get('all')oropts.get('ignore'):kwfstats+=(('I',[fforfinfilesiffnotinkwfiles]),('i',[fforfinunknowniffnotinkwuntracked]),)forchar,filenamesinkwfstats:fmt=(opts.get('all')orui.verbose)and'%s%%s\n'%charor'%s\n'forfinfilenames:ui.write(fmt%repo.pathto(f,cwd))defshrink(ui,repo,*pats,**opts):'''revert expanded keywords in the working directory Run before changing/disabling active keywords or if you experience problems with "hg import" or "hg merge". kwshrink refuses to run if given files contain local changes. '''# 3rd argument sets expansion to False_kwfwrite(ui,repo,False,*pats,**opts)defuisetup(ui):'''Collects [keyword] config in kwtools. Monkeypatches dispatch._parse if needed.'''forpat,optinui.configitems('keyword'):ifopt!='ignore':kwtools['inc'].append(pat)else:kwtools['exc'].append(pat)ifkwtools['inc']:defkwdispatch_parse(orig,ui,args):'''Monkeypatch dispatch._parse to obtain running hg command.'''cmd,func,args,options,cmdoptions=orig(ui,args)kwtools['hgcmd']=cmdreturncmd,func,args,options,cmdoptionsextensions.wrapfunction(dispatch,'_parse',kwdispatch_parse)defreposetup(ui,repo):'''Sets up repo as kwrepo for keyword substitution. Overrides file method to return kwfilelog instead of filelog if file matches user configuration. Wraps commit to overwrite configured files with updated keyword substitutions. Monkeypatches patch and webcommands.'''try:if(notrepo.local()ornotkwtools['inc']orkwtools['hgcmd']innokwcommands.split()or'.hg'inutil.splitpath(repo.root)orrepo._url.startswith('bundle:')):returnexceptAttributeError:passkwtools['templater']=kwt=kwtemplater(ui,repo)classkwrepo(repo.__class__):deffile(self,f):iff[0]=='/':f=f[1:]returnkwfilelog(self.sopener,kwt,f)defwread(self,filename):data=super(kwrepo,self).wread(filename)returnkwt.wread(filename,data)defcommit(self,*args,**opts):# use custom commitctx for user commands# other extensions can still wrap repo.commitctx directlyself.commitctx=self.kwcommitctxtry:returnsuper(kwrepo,self).commit(*args,**opts)finally:delself.commitctxdefkwcommitctx(self,ctx,error=False):wlock=lock=Nonetry:wlock=self.wlock()lock=self.lock()# store and postpone commit hookscommithooks={}forname,cmdinui.configitems('hooks'):ifname.split('.',1)[0]=='commit':commithooks[name]=cmdui.setconfig('hooks',name,None)ifcommithooks:# store parents for commit hooksp1,p2=ctx.p1(),ctx.p2()xp1,xp2=p1.hex(),p2andp2.hex()or''n=super(kwrepo,self).commitctx(ctx,error)kwt.overwrite(n,True,None)ifcommithooks:forname,cmdincommithooks.iteritems():ui.setconfig('hooks',name,cmd)self.hook('commit',node=n,parent1=xp1,parent2=xp2)returnnfinally:release(lock,wlock)# monkeypatchesdefkwpatchfile_init(orig,self,ui,fname,opener,missing=False,eol=None):'''Monkeypatch/wrap patch.patchfile.__init__ to avoid rejects or conflicts due to expanded keywords in working dir.'''orig(self,ui,fname,opener,missing,eol)# shrink keywords read from working dirself.lines=kwt.shrinklines(self.fname,self.lines)defkw_diff(orig,repo,node1=None,node2=None,match=None,changes=None,opts=None):'''Monkeypatch patch.diff to avoid expansion except when comparing against working dir.'''ifnode2isnotNone:kwt.match=util.neverelifnode1isnotNoneandnode1!=repo['.'].node():kwt.restrict=Truereturnorig(repo,node1,node2,match,changes,opts)defkwweb_skip(orig,web,req,tmpl):'''Wraps webcommands.x turning off keyword expansion.'''kwt.match=util.neverreturnorig(web,req,tmpl)repo.__class__=kwrepoextensions.wrapfunction(patch.patchfile,'__init__',kwpatchfile_init)extensions.wrapfunction(patch,'diff',kw_diff)forcin'annotate changeset rev filediff diff'.split():extensions.wrapfunction(webcommands,c,kwweb_skip)cmdtable={'kwdemo':(demo,[('d','default',None,_('show default keyword template maps')),('f','rcfile',[],_('read maps from rcfile'))],_('hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...')),'kwexpand':(expand,commands.walkopts,_('hg kwexpand [OPTION]... [FILE]...')),'kwfiles':(files,[('a','all',None,_('show keyword status flags of all files')),('i','ignore',None,_('show files excluded from expansion')),('u','untracked',None,_('additionally show untracked files')),]+commands.walkopts,_('hg kwfiles [OPTION]... [FILE]...')),'kwshrink':(shrink,commands.walkopts,_('hg kwshrink [OPTION]... [FILE]...')),}