3 # Copyright (c) 2005 Fredrik Kuivinen <freku045@student.liu.se>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 import sys
, math
, random
, qt
, os
, re
, signal
20 # PyQt3 and python 2.4 isn't currently available together on
21 # Debian/testing we do therefore use the following quite ugly work
22 # around. The module 'mysubprocess' is just a copy of the 'subprocess'
23 # module from the Python 2.4 distribution.
24 ver
= sys
.version_info
25 if ver
[0] < 2 or (ver
[0] == 2 and ver
[1] <= 3):
27 subprocess
= mysubprocess
31 qconnect
= qt
.QObject
.connect
33 applicationName
= 'Git Commit Tool'
42 class CommitError(Exception):
43 def __init__(self
, operation
, msg
):
44 self
.operation
= operation
50 class MyListItem(qt
.QListViewItem
):
51 def __init__(self
, parent
, file, inSync
, commitMsg
= False):
55 status
= 'Working directory out of sync '
58 qt
.QListViewItem
.__init
__(self
, parent
, file.text
, status
)
61 self
.commitMsg
= commitMsg
63 def compare(self
, item
, col
, asc
):
75 return cmp(self
.key(col
, asc
), item
.key(col
, asc
))
77 def paintCell(self
, p
, cg
, col
, w
, a
):
78 if col
== 1 and not self
.inSync
:
79 cg
.setColor(qt
.QColorGroup
.Text
, Qt
.red
)
80 qt
.QListViewItem
.paintCell(self
, p
, cg
, col
, w
, a
)
81 cg
.setColor(qt
.QColorGroup
.Text
, Qt
.black
)
83 qt
.QListViewItem
.paintCell(self
, p
, cg
, col
, w
, a
)
85 class MyListView(qt
.QListView
):
86 def __init__(self
, parent
=None, name
=None):
87 qt
.QListView
.__init
__(self
, parent
, name
)
90 return ListViewIterator(self
)
92 class ListViewIterator
:
93 def __init__(self
, listview
):
94 self
.it
= qt
.QListViewItemIterator(listview
)
97 cur
= self
.it
.current()
105 raise StopIteration()
110 class MainWidget(qt
.QMainWindow
):
111 def __init__(self
, parent
=None, name
=None):
112 qt
.QMainWindow
.__init
__(self
, parent
, name
)
113 splitter
= qt
.QSplitter(Qt
.Vertical
, self
)
115 fW
= MyListView(splitter
)
117 fW
.setSelectionMode(qt
.QListView
.Multi
)
118 fW
.addColumn('Description')
119 statusTitle
= 'Cache Status'
120 fW
.addColumn(statusTitle
)
121 fW
.setResizeMode(qt
.QListView
.AllColumns
)
122 fW
.header().setStretchEnabled(1, False)
123 fW
.setColumnWidth(1, self
.fontMetrics().width(statusTitle
+ 'xxx'))
125 text
= qt
.QWidgetStack(splitter
)
127 self
.setCentralWidget(splitter
)
128 self
.setCaption(applicationName
)
130 self
.newCurLambda
= lambda i
: self
.currentChange(i
)
131 qconnect(fW
, qt
.SIGNAL("currentChanged(QListViewItem*)"), self
.newCurLambda
)
133 ops
= qt
.QPopupMenu(self
)
134 ops
.insertItem("Commit Selected Files", self
.commit
, Qt
.CTRL
+Qt
.Key_T
)
135 ops
.insertItem("Refresh", self
.refreshFiles
, Qt
.CTRL
+Qt
.Key_R
)
136 ops
.insertItem("Update Cache for Selected Files", self
.updateCache
, Qt
.CTRL
+Qt
.Key_U
)
139 m
.insertItem("&Operations", ops
)
141 h
= qt
.QPopupMenu(self
)
142 h
.insertItem("&About", self
.about
)
143 m
.insertItem("&Help", h
)
145 self
.patchColors
= {'std': 'black', 'new': '#009600', 'remove': '#C80000', 'head': '#C800C8'}
149 self
.splitter
= splitter
153 f
.text
= "Commit message"
154 f
.textW
= self
.newTextEdit()
155 f
.textW
.setTextFormat(Qt
.PlainText
)
156 f
.textW
.setReadOnly(False)
158 self
.createCmitItem()
159 self
.splitter
.setSizes(eval(str(settings
.readEntry('splitter', '[400, 200]')[0])))
161 def closeEvent(self
, e
):
163 settings
.writeEntry('x', p
.x()),
164 settings
.writeEntry('y', p
.y()),
167 settings
.writeEntry('width', s
.width()),
168 settings
.writeEntry('height', s
.height())
170 settings
.writeEntry('splitter', str(self
.splitter
.sizes()))
173 def createCmitItem(self
):
174 self
.cmitItem
= MyListItem(self
.filesW
, self
.cmitFile
, False, True)
175 self
.cmitItem
.setSelectable(False)
176 self
.filesW
.insertItem(self
.cmitItem
)
178 def about(self
, ignore
):
179 qt
.QMessageBox
.about(self
, "About " + applicationName
,
180 "<qt><center><h1>" + applicationName
+ " " + version
+ "</h1></center>\n" +
181 "<center>Copyright © 2005 Fredrik Kuivinen <freku045@student.liu.se></center>\n" +
182 "<p>This program is free software; you can redistribute it and/or modify " +
183 "it under the terms of the GNU General Public License version 2 as " +
184 "published by the Free Software Foundation.</p></qt>")
186 def currentChange(self
, item
):
187 self
.text
.raiseWidget(item
.file.textW
)
190 def updateCache(self
, id):
191 for it
in self
.selectedItems():
192 doUpdateCache(it
.file.dstName
)
195 def selectedItems(self
):
197 for item
in self
.filesW
:
198 if item
.isSelected():
202 def commit(self
, id):
206 for item
in self
.filesW
:
207 debug("file: " + item
.file.text
)
208 if item
.isSelected():
209 selFileNames
.append(item
.file.text
)
211 keepFiles
.append(item
.file)
213 commitMsg
= str(self
.cmitItem
.file.textW
.text())
216 qt
.QMessageBox
.information(self
, "Commit - " + applicationName
,
217 "No files selected for commit.", "&Ok")
220 commitMsg
= fixCommitMsgWhiteSpace(commitMsg
)
221 if(qt
.QMessageBox
.question(self
, "Confirm Commit - " + applicationName
,
222 '<qt><p>Do you want to commit the following file(s):</p>' +
223 '<blockquote>' + '<br>'.join(selFileNames
) + '</blockquote>' +
224 '<p>with the commit message:</p>' +
225 '<blockquote><pre>' + commitMsg
+ '</pre></blockquote></qt>',
230 doCommit(keepFiles
, commitMsg
)
231 except CommitError
, e
:
232 qt
.QMessageBox
.warning(self
, "Commit Failed - " + applicationName
,
233 "Commit failed during " + e
.operation
+ ": " + e
.msg
,
236 qt
.QMessageBox
.warning(self
, "Commit Failed - " + applicationName
,
237 "Commit failed: " + e
.strerror
,
240 self
.cmitItem
.file.textW
.setText('')
243 def getFileState(self
):
245 cur
= self
.filesW
.currentItem()
246 if cur
and cur
!= self
.cmitItem
:
247 ret
.current
= self
.filesW
.currentItem().file.srcName
252 for x
in self
.filesW
:
254 ret
.selected
[x
.file.srcName
] = True
257 def restoreFileState(self
, state
):
258 for x
in self
.filesW
:
259 if state
.selected
.has_key(x
.file.srcName
):
261 if x
.file.srcName
== state
.current
:
262 self
.filesW
.setCurrentItem(x
)
264 def newTextEdit(self
):
266 self
.text
.addWidget(ret
)
269 def setFiles(self
, files
):
270 state
= self
.getFileState()
272 self
.createCmitItem()
274 self
.text
.removeWidget(f
.textW
)
278 f
.textW
= self
.newTextEdit()
279 f
.textW
.setReadOnly(False)
280 f
.textW
.setTextFormat(Qt
.RichText
)
281 f
.textW
.setText(formatPatchRichText(f
.patch
, self
.patchColors
))
283 self
.filesW
.insertItem(MyListItem(self
.filesW
, f
, f
.updated
))
285 self
.filesW
.setCurrentItem(self
.cmitItem
)
287 # For some reason the currentChanged signal isn't emitted
288 # here. We call currentChange ourselves instead.
289 self
.currentChange(self
.cmitItem
)
291 self
.restoreFileState(state
)
293 def refreshFiles(self
, ignored
=None):
295 self
.setFiles(getFiles())
298 cacheHeadDiff
= parseDiff('git-diff-cache -z --cached HEAD')
300 # The set of files that are different in the cache compared to HEAD
302 for f
in cacheHeadDiff
:
303 cacheHeadChange
[f
.srcName
] = True
305 noncacheHeadDiff
= parseDiff('git-diff-cache -z HEAD')
306 for f
in noncacheHeadDiff
:
307 if (f
.srcSHA
== '0'*40 or f
.dstSHA
== '0'*40) and not cacheHeadChange
.has_key(f
.srcName
):
308 runProgram(['git-update-cache', '--remove', f
.srcName
])
310 def doUpdateCache(filename
):
311 runProgram(['git-update-cache', '--remove', '--add', '--replace', filename
])
313 def doCommit(filesToKeep
, msg
):
314 for file in filesToKeep
:
315 # If we have a new file in the cache which we do not want to
316 # commit we have to remove it from the cache. We will add this
317 # cache entry back in to the cache at the end of this
319 if file.change
== 'N':
320 runProgram(['git-update-cache', '--force-remove', file.srcName
])
322 runProgram(['git-update-cache', '--add', '--replace', '--cacheinfo',
323 file.srcMode
, file.srcSHA
, file.srcName
])
325 tree
= runProgram(['git-write-tree'])
327 commit
= runProgram(['git-commit-tree', tree
, '-p', 'HEAD'], msg
)
328 commit
= commit
.rstrip()
331 f
= open(os
.environ
['GIT_DIR'] + '/HEAD', 'w+')
335 raise CommitError('write to ' + os
.environ
['GIT_DIR'] + '/HEAD', e
.strerror
)
338 os
.unlink(os
.environ
['GIT_DIR'] + '/MERGE_HEAD')
342 for file in filesToKeep
:
343 # Don't add files that are going to be deleted back to the cache
344 if file.change
!= 'D':
345 runProgram(['git-update-cache', '--add', '--replace', '--cacheinfo',
346 file.dstMode
, file.dstSHA
, file.dstName
])
349 commitMsgRE
= re
.compile('[ \t\r\f\v]*\n\\s*\n')
350 def fixCommitMsgWhiteSpace(msg
):
353 msg
= re
.sub(commitMsgRE
, '\n', msg
)
360 parseDiffRE
= re
.compile(':([0-9]+) ([0-9]+) ([0-9a-f]{40}) ([0-9a-f]{40}) ([MCRNDUT])([0-9]*)')
362 inp
= runProgram(prog
)
365 recs
= inp
.split("\0")
366 recs
.pop() # remove last entry (which is '')
370 m
= parseDiffRE
.match(rec
)
373 print "Unknown output from " + str(prog
) + "!: " + rec
+ "\n"
377 f
.srcMode
= m
.group(1)
378 f
.dstMode
= m
.group(2)
379 f
.srcSHA
= m
.group(3)
380 f
.dstSHA
= m
.group(4)
381 f
.change
= m
.group(5)
383 f
.srcName
= f
.dstName
= it
.next()
385 if f
.change
== 'C' or f
.change
== 'R':
386 f
.dstName
= it
.next()
387 f
.patch
= getPatch(f
.srcName
, f
.dstName
)
389 f
.patch
= getPatch(f
.srcName
)
392 except StopIteration:
397 # HEAD is src in the returned File objects. That is, srcName is the
398 # name in HEAD and dstName is the name in the cache.
400 files
= parseDiff('git-diff-cache -z -M --cached HEAD')
404 f
.text
= 'Copy from ' + f
.srcName
+ ' to ' + f
.dstName
406 f
.text
= 'Rename from ' + f
.srcName
+ ' to ' + f
.dstName
408 f
.text
= 'New file: ' + f
.srcName
410 f
.text
= 'Deleted file: ' + f
.srcName
412 f
.text
= 'Type change: ' + f
.srcName
416 if len(parseDiff(['git-diff-files', '-z', f
.dstName
])) > 0:
422 def getPatch(file, otherFile
= None):
424 f
= [file, otherFile
]
427 return runProgram(['git-diff-cache', '-p', '-M', '--cached', 'HEAD'] + f
)
429 def formatPatchRichText(patch
, colors
):
430 ret
= '<font color="' + colors
['std'] + '">'
432 for l
in patch
.split('\n'):
439 if c
== '+': style
= 'new'
440 elif c
== '-': style
= 'remove'
441 elif c
== '@': style
= 'head'
443 ret
+= '</font><font color="' + colors
[style
] + '">'
445 ret
+= str(qt
.QStyleSheet
.escape(l
)) + '<br>\n'
448 class ProgramError(Exception):
449 def __init__(self
, program
, err
):
450 self
.program
= program
453 def runProgram(prog
, input=None):
454 debug('runProgram prog: ' + str(prog
) + " input: " + str(input))
455 if type(prog
) is str:
458 progStr
= ' '.join(prog
)
461 pop
= subprocess
.Popen(prog
,
462 shell
= type(prog
) is str,
463 stderr
=subprocess
.STDOUT
,
464 stdout
=subprocess
.PIPE
,
465 stdin
=subprocess
.PIPE
)
467 debug("strerror: " + e
.strerror
)
468 raise ProgramError(progStr
, e
.strerror
)
471 pop
.stdin
.write(input)
474 out
= pop
.stdout
.read()
477 debug("error output: " + out
)
478 raise ProgramError(progStr
, out
)
479 debug("output: " + out
.replace('\0', '\n'))
482 if not os
.environ
.has_key('GIT_DIR'):
483 os
.environ
['GIT_DIR'] = '.git'
485 def basicsFailed(msg
):
486 print "'git-cat-file -t HEAD' failed: " + msg
487 print "Make sure that the current working directory contains a '.git' directory, or\nthat GIT_DIR is set appropriately."
491 runProgram('git-cat-file -t HEAD')
493 basicsFailed(e
.strerror
)
494 except ProgramError
, e
:
495 basicsFailed(e
.error
)
497 app
= qt
.QApplication(sys
.argv
)
498 settings
= qt
.QSettings()
499 settings
.beginGroup('/' + shortName
)
500 settings
.beginGroup('/geometry/')
505 mw
.resize(settings
.readNumEntry('width', 500)[0],
506 settings
.readNumEntry('height', 600)[0])
509 # The following code doesn't work correctly in some (at least
511 # managers. http://doc.trolltech.com/3.3/geometry.html contains some
512 # information about this issue.
513 # mw.move(settings.readNumEntry('x', 100)[0],
514 # settings.readNumEntry('y', 100)[0])
517 app
.setMainWidget(mw
)
520 # Handle CTRL-C appropriately
521 signal
.signal(signal
.SIGINT
, lambda s
, f
: app
.quit())
523 ret
= app
.exec_loop()