Mercurial and Git clients can push and pull from this alias URL to interact with this repository. You can change to which repository an alias points by going to the Aliases link on the project page.
Mercurial expects diffs to have a 'strip' level of 1, so we need to provide a directory level that can be stripped. Without this hack, Mercurial's patch routines will not apply the unified diffs we generate.
# Copyright (c) 2009-2010 LOGILAB S.A. (Paris, FRANCE).# http://www.logilab.fr/ -- mailto:contact@logilab.fr## This program is free software; you can redistribute it and/or modify it under# the terms of the GNU General Public License as published by the Free Software# Foundation; either version 2 of the License, or (at your option) any later# version.## This program is distributed in the hope that it will be useful, but WITHOUT# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.## You should have received a copy of the GNU General Public License along with# this program; if not, write to the Free Software Foundation, Inc.,# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA."""Qt4 high level widgets for hg repo changelogs and filelogs"""importosimportdifflibimportrefrommercurialimporthg,error,match,patch,subrepo,commandsfrommercurialimportuiasuimodfromPyQt4.QtCoreimport*fromPyQt4.QtGuiimport*fromPyQt4importQscifromtortoisehg.utilimporthglib,patchctxfromtortoisehg.hgqt.i18nimport_fromtortoisehg.hgqt.lexersimportget_lexer,get_diff_lexerfromtortoisehg.hgqt.blockmatcherimportBlockListfromtortoisehg.hgqtimportqscilibqsci=Qsci.QsciScintillachunkhdrre=re.compile('^@@ -(\d+).*@@$')classAnnotator(qsci):# we use a QScintilla for the annotater cause it makes# it much easier to keep the text area and the annotater sync# (same font rendering etc). However, it have the drawback of making much# more difficult to implement things like QTextBrowser.anchorClicked, which# would have been nice to directly go to the annotated revision...def__init__(self,textarea,parent=None):qsci.__init__(self,parent)self.setFrameStyle(0)self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)self.setReadOnly(True)self.sizePolicy().setControlType(QSizePolicy.Slider)self.setMinimumWidth(20)self.setMaximumWidth(40)# XXX TODO make this computedself.setFont(textarea.font())self.setMarginWidth(0,'')self.setMarginWidth(1,'')self.SendScintilla(qsci.SCI_SETCURSOR,2)self.SendScintilla(qsci.SCI_SETCARETSTYLE,0)# used to set a background color for every annotating revN=32self.markers=[]foriinrange(N):marker=self.markerDefine(qsci.Background)color=0x7FFF00+(i-N/2)*256/N*256*256-i*256/N*256+i*256/Nself.SendScintilla(qsci.SCI_MARKERSETBACK,marker,color)self.markers.append(marker)textarea.verticalScrollBar().valueChanged.connect(self.verticalScrollBar().setValue)defsetFilectx(self,fctx):self.fctx=fctxiffctx.rev()isNone:# the working context does not support annotate yet. I need to# add that to Mercurial at some point.self.setText('')self.fctxann=[]returnself.fctxann=[fforf,lineinfctx.annotate(follow=True)]revlist=[str(f.rev())forfinself.fctxann]self.setText('\n'.join(revlist))uniqrevs=list(sorted(set(revlist)))fori,revinenumerate(revlist):idx=uniqrevs.index(rev)self.markerAdd(i,self.markers[idx%len(self.markers)])classHgFileView(QFrame):"""file diff and content viewer"""showDescSignal=pyqtSignal(QString)linkActivated=pyqtSignal(QString)fileDisplayed=pyqtSignal(QString,QString)showMessage=pyqtSignal(unicode)revForDiffChanged=pyqtSignal(int)filled=pyqtSignal()def__init__(self,parent=None):QFrame.__init__(self,parent)framelayout=QVBoxLayout(self)framelayout.setContentsMargins(0,0,0,0)framelayout.setSpacing(0)l=QHBoxLayout()l.setContentsMargins(0,0,0,0)l.setSpacing(0)self.topLayout=QVBoxLayout()self.filenamelabel=w=QLabel()w.setWordWrap(True)f=w.textInteractionFlags()w.setTextInteractionFlags(f|Qt.TextSelectableByMouse)w.linkActivated.connect(self.linkActivated)self.topLayout.addWidget(w)self.extralabel=w=QLabel()w.setWordWrap(True)w.linkActivated.connect(self.linkActivated)self.topLayout.addWidget(w)w.hide()framelayout.addLayout(self.topLayout)framelayout.addLayout(l,1)self.sci=qscilib.Scintilla(self)self.sci.setFrameStyle(0)l.addWidget(self.sci,1)#self.sci.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)self.sci.setReadOnly(True)self.sci.setUtf8(True)self.sci.setWrapMode(qsci.WrapCharacter)self.sci.installEventFilter(qscilib.KeyPressInterceptor(self))self.sci.setCaretLineVisible(False)ifhasattr(self.sci,'indicatorDefine'):self.sci.indicatorDefine(qsci.RoundBoxIndicator,8)self.sci.setIndicatorDrawUnder(8)self.sci.setIndicatorForegroundColor(QColor('#BBFFFF'),8)self.sci.indicatorDefine(qsci.RoundBoxIndicator,9)self.sci.setIndicatorDrawUnder(9)self.sci.setIndicatorForegroundColor(QColor('#58A8FF'),9)else:self.sci.SendScintilla(qsci.SCI_INDICSETSTYLE,8,qsci.INDIC_ROUNDBOX)self.sci.SendScintilla(qsci.SCI_INDICSETUNDER,8,True)self.sci.SendScintilla(qsci.SCI_INDICSETFORE,8,0xBBFFFF)self.sci.SendScintilla(qsci.SCI_INDICSETSTYLE,9,qsci.INDIC_ROUNDBOX)self.sci.SendScintilla(qsci.SCI_INDICSETUNDER,9,True)self.sci.SendScintilla(qsci.SCI_INDICSETFORE,9,0x58A8FF)# hide margin 0 (markers)self.sci.SendScintilla(qsci.SCI_SETMARGINTYPEN,0,0)self.sci.SendScintilla(qsci.SCI_SETMARGINWIDTHN,0,0)# define markers for colorize zones of diffself.markerplus=self.sci.markerDefine(qsci.Background)self.sci.SendScintilla(qsci.SCI_MARKERSETBACK,self.markerplus,0xB0FFA0)self.markerminus=self.sci.markerDefine(qsci.Background)self.sci.SendScintilla(qsci.SCI_MARKERSETBACK,self.markerminus,0xA0A0FF)self.markertriangle=self.sci.markerDefine(qsci.Background)self.sci.SendScintilla(qsci.SCI_MARKERSETBACK,self.markertriangle,0xFFA0A0)self.lastrev=Noneself.sci.mouseMoveEvent=self.mouseMoveEventll=QVBoxLayout()ll.setContentsMargins(0,0,0,0)ll.setSpacing(0)l.insertLayout(0,ll)ll2=QHBoxLayout()ll2.setContentsMargins(0,0,0,0)ll2.setSpacing(0)ll.addLayout(ll2)# used to fill height of the horizontal scroll barw=QWidget(self)ll.addWidget(w)self._spacer=wself.blk=BlockList(self)self.blk.linkScrollBar(self.sci.verticalScrollBar())ll2.addWidget(self.blk)self.blk.setVisible(False)self.ann=Annotator(self.sci,self)ll2.addWidget(self.ann)self.ann.setVisible(False)self._ctx=Noneself._filename=Noneself._status=Noneself._annotate=Falseself._find_text=Noneself._mode="diff"# can be 'diff' or 'file'self.timer=QTimer()self.timer.setSingleShot(False)self.timer.timeout.connect(self.idle_fill_files)defresizeEvent(self,event):QFrame.resizeEvent(self,event)h=self.sci.horizontalScrollBar().height()self._spacer.setMinimumHeight(h)self._spacer.setMaximumHeight(h)defsetMode(self,mode):ifisinstance(mode,bool):mode=['file','diff'][mode]assertmodein('diff','file')ifmode!=self._mode:self._mode=modeself.blk.setVisible(self._mode=='file')self.ann.setVisible(self._mode=='file'andself._annotate)self.displayFile()defgetMode(self):returnself._modedefsetAnnotate(self,ann):self._annotate=annself.blk.setVisible(self._mode=='file')self.ann.setVisible(self._mode=='file'andself._annotate)self.displayFile()defgetAnnotate(self):returnself._annotatedefsetContext(self,ctx):self._ctx=ctxself._p_rev=Noneself.sci.setTabWidth(ctx._repo.tabwidth)ifctx._repo.wsvisible=='Visible':self.sci.setWhitespaceVisibility(qsci.WsVisible)elifctx._repo.wsvisible=='VisibleAfterIndent':self.sci.setWhitespaceVisibility(qsci.WsVisibleAfterIndent)else:self.sci.setWhitespaceVisibility(qsci.WsInvisible)defrev(self):returnself._ctx.rev()deffilename(self):returnself._filenamedefdisplayDiff(self,rev):ifrev!=self._p_rev:self.displayFile(rev=rev)defmouseMoveEvent(self,event):ifself._mode=='file'andself._annotateandself.ann.fctxann:# Calculate row index from the scroll offset and mouse positionscroll_offset=self.sci.verticalScrollBar().value()idx=scroll_offset+event.pos().y()/self.sci.textHeight(0)# It's possible to scroll below the bottom lineifidx>=len(self.ann.fctxann):idx=len(self.ann.fctxann)-1ctx=self.ann.fctxann[idx]rev=ctx.rev()desc=hglib.get_revision_desc(ctx,self.filename())ifrev!=self.lastrev:self.showDescSignal.emit(desc)self.lastrev=revqsci.mouseMoveEvent(self.sci,event)defleaveEvent(self,event):ifself._mode=='file'andself._annotate:self.lastrev=Noneself.showDescSignal.emit('')defclearDisplay(self):self.sci.clear()self.ann.clear()self.blk.clear()# Setting the label to ' ' rather than clear() keeps the label# from disappearing during refresh, and tool layouts bouncingself.filenamelabel.setText(' ')self.extralabel.hide()self.sci.setMarginLineNumbers(1,False)self.sci.setMarginWidth(1,'')defdisplayFile(self,filename=None,rev=None,status=None):iffilenameisNone:filename,status=self._filename,self._statuselse:self._filename,self._status=filename,statusifrevisnotNone:self._p_rev=revself.revForDiffChanged.emit(rev)self.clearDisplay()iffilenameisNone:self.sci.setMarginLineNumbers(1,False)self.sci.setMarginWidth(1,'')returnctx=self._ctxrepo=ctx._repoifself._p_revisnotNone:ctx2=repo[self._p_rev]else:ctx2=Nonefd=FileData(ctx,ctx2,filename,status)iffd.elabel:self.extralabel.setText(fd.elabel)self.extralabel.show()else:self.extralabel.hide()self.filenamelabel.setText(fd.flabel)ifnotfd.isValid():self.ann.setVisible(False)self.sci.setText(fd.error)returnifself._mode=='diff'andfd.diff:lexer=get_diff_lexer(self)self.sci.setLexer(lexer)utext=[hglib.tounicode(l)forlinfd.diff[2:]]self.sci.setText(u'\n'.join(utext))eliffd.contentsisNone:returnelse:lexer=get_lexer(filename,fd.contents,self)self.sci.setLexer(lexer)nlines=fd.contents.count('\n')# margin 1 is used for line numbersself.sci.setMarginLineNumbers(1,True)self.sci.setMarginWidth(1,str(nlines)+'0')self.sci.setText(fd.contents)ifself._find_text:self.highlightSearchString(self._find_text)uf=hglib.tounicode(self._filename)self.fileDisplayed.emit(uf,fd.contentsorQString())ifself._mode!='file':returnifself._annotate:self.ann.setVisible(self._annotate)iflexerisnotNone:self.ann.setFont(lexer.font(0))else:self.ann.setFont(self.sci.font())self.ann.setFilectx(self._ctx[filename])# Update diff marginiffd.contentsandfd.olddata:ifself.timer.isActive():self.timer.stop()olddata=fd.olddata.splitlines()newdata=fd.contents.splitlines()self._diff=difflib.SequenceMatcher(None,olddata,newdata)self._diffs=[]self.blk.syncPageStep()self.timer.start()defnextDiff(self):ifself._mode=='file':row,column=self.sci.getCursorPosition()fori,(lo,hi)inenumerate(self._diffs):iflo>row:last=(i==(len(self._diffs)-1))breakelse:returnFalseself.sci.setCursorPosition(lo,0)self.sci.verticalScrollBar().setValue(lo)returnnotlastdefprevDiff(self):ifself._mode=='file':row,column=self.sci.getCursorPosition()fori,(lo,hi)inenumerate(reversed(self._diffs)):ifhi<row:first=(i==(len(self._diffs)-1))breakelse:returnFalseself.sci.setCursorPosition(lo,0)self.sci.verticalScrollBar().setValue(lo)returnnotfirstdefnextLine(self):x,y=self.sci.getCursorPosition()self.sci.setCursorPosition(x+1,y)defprevLine(self):x,y=self.sci.getCursorPosition()self.sci.setCursorPosition(x-1,y)defnextCol(self):x,y=self.sci.getCursorPosition()self.sci.setCursorPosition(x,y+1)defprevCol(self):x,y=self.sci.getCursorPosition()self.sci.setCursorPosition(x,y-1)defnDiffs(self):returnlen(self._diffs)defdiffMode(self):returnself._mode=='diff'deffileMode(self):returnself._mode=='file'defsearchString(self,text):self._find_text=textself.clearHighlights()findpos=self.highlightSearchString(self._find_text)iffindpos:deffinditer(self,findpos):ifself._find_text:forposinfindpos:self.highlightCurrentSearchString(pos,self._find_text)yieldself._ctx.rev(),self._filename,posreturnfinditer(self,findpos)defclearHighlights(self):n=self.sci.length()# highlightself.sci.SendScintilla(qsci.SCI_SETINDICATORCURRENT,8)self.sci.SendScintilla(qsci.SCI_INDICATORCLEARRANGE,0,n)# current found occurrenceself.sci.SendScintilla(qsci.SCI_SETINDICATORCURRENT,9)self.sci.SendScintilla(qsci.SCI_INDICATORCLEARRANGE,0,n)defhighlightSearchString(self,text):data=unicode(self.sci.text())self.sci.SendScintilla(qsci.SCI_SETINDICATORCURRENT,8)pos=[data.find(text)]n=len(text)whilepos[-1]>-1:self.sci.SendScintilla(qsci.SCI_INDICATORFILLRANGE,pos[-1],n)pos.append(data.find(text,pos[-1]+1))pos=[xforxinposifx>-1]self.showMessage.emit(_("Found %d occurrences of '%s' in current file or diff")%(len(pos),text))returnposdefhighlightCurrentSearchString(self,pos,text):line=self.sci.SendScintilla(qsci.SCI_LINEFROMPOSITION,pos)#line, idx = w.lineIndexFromPosition(nextpos)self.sci.ensureLineVisible(line)self.sci.SendScintilla(qsci.SCI_SETINDICATORCURRENT,9)self.sci.SendScintilla(qsci.SCI_INDICATORCLEARRANGE,0,pos)self.sci.SendScintilla(qsci.SCI_INDICATORFILLRANGE,pos,len(text))@pyqtSlot(unicode,bool,bool,bool)deffind(self,exp,icase=True,wrap=False,forward=True):self.sci.find(exp,icase,wrap,forward)@pyqtSlot(unicode,bool)defhighlightText(self,match,icase=False):self.sci.highlightText(match,icase)defverticalScrollBar(self):returnself.sci.verticalScrollBar()defidle_fill_files(self):# we make a burst of diff-lines computed at once, but we# disable GUI updates for efficiency reasons, then only# refresh GUI at the end of the burstself.sci.setUpdatesEnabled(False)self.blk.setUpdatesEnabled(False)forninrange(30):# burst poolifself._diffisNoneornotself._diff.get_opcodes():self._diff=Noneself.timer.stop()self.filled.emit()breaktag,alo,ahi,blo,bhi=self._diff.get_opcodes().pop(0)iftag=='replace':self._diffs.append([blo,bhi])self.blk.addBlock('x',blo,bhi)foriinrange(blo,bhi):self.sci.markerAdd(i,self.markertriangle)eliftag=='delete':# You cannot effectively show deleted lines in a single# pane display. They do not exist.pass# self._diffs.append([blo, bhi])# self.blk.addBlock('-', blo, bhi)# for i in range(alo, ahi):# self.sci.markerAdd(i, self.markerminus)eliftag=='insert':self._diffs.append([blo,bhi])self.blk.addBlock('+',blo,bhi)foriinrange(blo,bhi):self.sci.markerAdd(i,self.markerplus)eliftag=='equal':passelse:raiseValueError,'unknown tag %r'%(tag,)# ok, enable GUI refresh for code viewers and diff-block displayersself.sci.setUpdatesEnabled(True)self.blk.setUpdatesEnabled(True)classFileData(object):def__init__(self,ctx,ctx2,wfile,status=None):self.contents=Noneself.error=Noneself.olddata=Noneself.diff=Noneself.flabel=u''self.elabel=u''self.readStatus(ctx,ctx2,wfile,status)defcheckMaxDiff(self,ctx,wfile):p=_('File or diffs not displayed: ')try:fctx=ctx.filectx(wfile)ifctx.rev()isNone:size=fctx.size()else:# fctx.size() can read all data into memory in rename cases so# we read the size directly from the filelog, this is deeper# under the API than I prefer to go, but seems necessarysize=fctx._filelog.rawsize(fctx.filerev())except(EnvironmentError,error.LookupError),e:self.error=p+hglib.tounicode(str(e))returnNoneifsize>ctx._repo.maxdiff:self.error=p+_('File is larger than the specified max size.\n')returnNonetry:data=fctx.data()if'\0'indata:self.error=p+_('File is binary.\n')returnNoneexceptEnvironmentError,e:self.error=p+hglib.tounicode(str(e))returnNonereturnfctx,datadefisValid(self):returnself.errorisNonedefreadStatus(self,ctx,ctx2,wfile,status):defgetstatus(repo,n1,n2,wfile):m=match.exact(repo.root,repo.getcwd(),[wfile])modified,added,removed=repo.status(n1,n2,match=m)[:3]ifwfileinmodified:return'M'ifwfileinadded:return'A'ifwfileinremoved:return'R'returnNonerepo=ctx._repoself.flabel+=u'<b>%s</b>'%hglib.tounicode(wfile)ifisinstance(ctx,patchctx.patchctx):self.diff=ctx.thgmqpatchdata(wfile)flags=ctx.flags(wfile)ifflagsin('x','-'):lbl=_("exec mode has been <font color='red'>%s</font>")change=(flags=='x')and_('set')or_('unset')self.elabel=lbl%changeelifflags=='l':self.flabel+=_(' <i>(is a symlink)</i>')returnabsfile=repo.wjoin(wfile)if(wfileinctxand'l'inctx.flags(wfile))or \
os.path.islink(absfile):ifwfileinctx:data=ctx[wfile].data()else:data=os.readlink(absfile)self.contents=hglib.tounicode(data)self.flabel+=_(' <i>(is a symlink)</i>')returnifstatusisNone:status=getstatus(repo,ctx.p1().node(),ctx.node(),wfile)ifctx2isNone:ctx2=ctx.p1()ifstatus=='S':try:assert(ctx.rev()isNone)out=[]_ui=uimod.ui()sroot=repo.wjoin(wfile)srepo=hg.repository(_ui,path=sroot)srev=ctx.substate.get(wfile,subrepo.nullstate)[1]sactual=srepo['.'].hex()_ui.pushbuffer()commands.status(_ui,srepo)data=_ui.popbuffer()ifdata:out.append(_('File Status:\n'))out.append(data)out.append('\n')ifsrev=='':out.append(_('New subrepository\n\n'))elifsrev!=sactual:out.append(_('Revision has changed from:\n\n'))opts={'date':None,'user':None,'rev':[srev]}_ui.pushbuffer()commands.log(_ui,srepo,**opts)out.append(hglib.tounicode(_ui.popbuffer()))out.append(_('To:\n'))opts['rev']=[sactual]_ui.pushbuffer()commands.log(_ui,srepo,**opts)out.append(hglib.tounicode(_ui.popbuffer()))self.contents=u''.join(out)self.flabel+=_(' <i>(is a dirty sub-repository)</i>')lbl=u' <a href="subrepo:%s">%s...</a>'self.flabel+=lbl%(hglib.tounicode(sroot),_('open'))except(error.RepoError,util.Abort),e:self.error=_('Not a Mercurial subrepo, not previewable')return# TODO: elif check if a subdirectory (for manifest tool)ifstatusin('R','!'):ifwfileinctx.p1():newdata=ctx.p1()[wfile].data()self.contents=hglib.tounicode(newdata)self.flabel+=_(' <i>(was deleted)</i>')else:self.flabel+=_(' <i>(was added, now missing)</i>')returnifstatusin('I','?'):try:data=open(repo.wjoin(wfile),'r').read()if'\0'indata:self.error='binary file'else:self.contents=hglib.tounicode(data)self.flabel+=_(' <i>(is unversioned)</i>')exceptEnvironmentError,e:self.error=hglib.tounicode(str(e))returnifstatusin('M','A'):res=self.checkMaxDiff(ctx,wfile)ifresisNone:returnfctx,newdata=resself.contents=hglib.tounicode(newdata)change=Noneforpfctxinfctx.parents():if'x'infctx.flags()and'x'notinpfctx.flags():change=_('set')elif'x'notinfctx.flags()and'x'inpfctx.flags():change=_('unset')ifchange:lbl=_("exec mode has been <font color='red'>%s</font>")self.elabel=lbl%changeifstatus=='A':renamed=fctx.renamed()ifnotrenamed:self.flabel+=_(' <i>(was added)</i>')returnoldname,node=renamedfr=hglib.tounicode(oldname)self.flabel+=_(' <i>(renamed from %s)</i>')%frolddata=repo.filectx(oldname,fileid=node).data()elifstatus=='M':ifwfilenotinctx2:# merge situation where file was added in other branchself.flabel+=_(' <i>(was added)</i>')returnoldname=wfileolddata=ctx2[wfile].data()else:return self.olddata = olddata
olddata = olddata.splitlines()
newdata = newdata.splitlines()
- gen = difflib.unified_diff(olddata, newdata, oldname, wfile,
+ gen = difflib.unified_diff(olddata, newdata, 'a/'+oldname, 'b/'+wfile,
lineterm='')
data = []
if repo.ui.config('diff', 'showfunc'):
forchunklineingen:chunkhdr=chunkhdrre.match(chunkline)ifchunkhdr:func=hglib.getchunkfunction(olddata,chunkhdr.group(1))iffunc:chunkline+=funcdata.append(chunkline)else:forchunklineingen:data.append(chunkline)self.diff=data
Attach a Trello Card
Add a tag
Your session has expired
You are no longer logged in. Please log in and try your request again.
Filter RSS Feed
This RSS feed URL allows you to see the contents of your current filter using any feed reader.
This link includes a special authentication token. If you share the URL with anyone else, they can see this RSS feed's activity. You can disable these tokens when needed.
Your current filter is unsaved; changing it won't affect this RSS feed.