Compile the main file as well.
[hgct.git] / main.py
blobf2ec230d7c3c7516fdf0382bc6576465f1003b9d
1 #!/usr/bin/env python
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.
8 #
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):
26 import mysubprocess
27 subprocess = mysubprocess
28 else:
29 import subprocess
31 qconnect = qt.QObject.connect
32 Qt = qt.Qt
33 applicationName = 'Git Commit Tool'
34 shortName = 'gct'
35 version = 'v0.1'
36 DEBUG = 0
38 def debug(str):
39 if DEBUG:
40 print str
42 class CommitError(Exception):
43 def __init__(self, operation, msg):
44 self.operation = operation
45 self.msg = msg
47 class FileState:
48 pass
50 class MyListItem(qt.QListViewItem):
51 def __init__(self, parent, file, inSync, commitMsg = False):
52 if inSync:
53 status = 'In sync '
54 else:
55 status = 'Working directory out of sync '
56 if commitMsg:
57 status = ''
58 qt.QListViewItem.__init__(self, parent, file.text, status)
59 self.inSync = inSync
60 self.file = file
61 self.commitMsg = commitMsg
63 def compare(self, item, col, asc):
64 if self.commitMsg:
65 if asc:
66 return -1
67 else:
68 return 1
69 elif item.commitMsg:
70 if asc:
71 return 1
72 else:
73 return -1
74 else:
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)
82 else:
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)
89 def __iter__(self):
90 return ListViewIterator(self)
92 class ListViewIterator:
93 def __init__(self, listview):
94 self.it = qt.QListViewItemIterator(listview)
96 def next(self):
97 cur = self.it.current()
98 if cur:
99 self.it += 1
100 if cur.commitMsg:
101 return self.next()
102 else:
103 return cur
104 else:
105 raise StopIteration()
107 def __iter__(self):
108 return self
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)
116 fW.setFocus()
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)
138 m = self.menuBar()
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'}
147 self.filesW = fW
148 self.files = []
149 self.splitter = splitter
150 self.text = text
152 f = File()
153 f.text = "Commit message"
154 f.textW = self.newTextEdit()
155 f.textW.setTextFormat(Qt.PlainText)
156 f.textW.setReadOnly(False)
157 self.cmitFile = f
158 self.createCmitItem()
159 self.splitter.setSizes(eval(str(settings.readEntry('splitter', '[400, 200]')[0])))
161 def closeEvent(self, e):
162 p = self.pos()
163 settings.writeEntry('x', p.x()),
164 settings.writeEntry('y', p.y()),
166 s = self.size()
167 settings.writeEntry('width', s.width()),
168 settings.writeEntry('height', s.height())
170 settings.writeEntry('splitter', str(self.splitter.sizes()))
171 e.accept()
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 &copy; 2005 Fredrik Kuivinen &lt;freku045@student.liu.se&gt;</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)
188 self.text.update()
190 def updateCache(self, id):
191 for it in self.selectedItems():
192 doUpdateCache(it.file.dstName)
193 self.refreshFiles()
195 def selectedItems(self):
196 ret = []
197 for item in self.filesW:
198 if item.isSelected():
199 ret.append(item)
200 return ret
202 def commit(self, id):
203 selFileNames = []
204 keepFiles = []
206 for item in self.filesW:
207 debug("file: " + item.file.text)
208 if item.isSelected():
209 selFileNames.append(item.file.text)
210 else:
211 keepFiles.append(item.file)
213 commitMsg = str(self.cmitItem.file.textW.text())
215 if not selFileNames:
216 qt.QMessageBox.information(self, "Commit - " + applicationName,
217 "No files selected for commit.", "&Ok")
218 return
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>',
226 '&Yes', '&No')):
227 return
228 else:
229 try:
230 doCommit(keepFiles, commitMsg)
231 except CommitError, e:
232 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
233 "Commit failed during " + e.operation + ": " + e.msg,
234 '&Ok')
235 except OSError, e:
236 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
237 "Commit failed: " + e.strerror,
238 '&Ok')
239 else:
240 self.cmitItem.file.textW.setText('')
241 self.refreshFiles()
243 def getFileState(self):
244 ret = FileState()
245 cur = self.filesW.currentItem()
246 if cur and cur != self.cmitItem:
247 ret.current = self.filesW.currentItem().file.srcName
248 else:
249 ret.current = None
250 ret.selected = {}
252 for x in self.filesW:
253 if x.isSelected():
254 ret.selected[x.file.srcName] = True
255 return ret
257 def restoreFileState(self, state):
258 for x in self.filesW:
259 if state.selected.has_key(x.file.srcName):
260 x.setSelected(True)
261 if x.file.srcName == state.current:
262 self.filesW.setCurrentItem(x)
264 def newTextEdit(self):
265 ret = qt.QTextEdit()
266 self.text.addWidget(ret)
267 return ret
269 def setFiles(self, files):
270 state = self.getFileState()
271 self.filesW.clear()
272 self.createCmitItem()
273 for f in self.files:
274 self.text.removeWidget(f.textW)
276 self.files = []
277 for f in files:
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))
282 self.files.append(f)
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):
294 updateCache()
295 self.setFiles(getFiles())
297 def updateCache():
298 cacheHeadDiff = parseDiff('git-diff-cache -z --cached HEAD')
300 # The set of files that are different in the cache compared to HEAD
301 cacheHeadChange = {}
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
318 # function.
319 if file.change == 'N':
320 runProgram(['git-update-cache', '--force-remove', file.srcName])
321 else:
322 runProgram(['git-update-cache', '--add', '--replace', '--cacheinfo',
323 file.srcMode, file.srcSHA, file.srcName])
325 tree = runProgram(['git-write-tree'])
326 tree = tree.rstrip()
327 commit = runProgram(['git-commit-tree', tree, '-p', 'HEAD'], msg)
328 commit = commit.rstrip()
330 try:
331 f = open(os.environ['GIT_DIR'] + '/HEAD', 'w+')
332 f.write(commit)
333 f.close()
334 except OSError, e:
335 raise CommitError('write to ' + os.environ['GIT_DIR'] + '/HEAD', e.strerror)
337 try:
338 os.unlink(os.environ['GIT_DIR'] + '/MERGE_HEAD')
339 except OSError:
340 pass
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):
351 msg = msg.lstrip()
352 msg = msg.rstrip()
353 msg = re.sub(commitMsgRE, '\n', msg)
354 msg += '\n'
355 return msg
357 class File:
358 pass
360 parseDiffRE = re.compile(':([0-9]+) ([0-9]+) ([0-9a-f]{40}) ([0-9a-f]{40}) ([MCRNDUT])([0-9]*)')
361 def parseDiff(prog):
362 inp = runProgram(prog)
363 ret = []
364 try:
365 recs = inp.split("\0")
366 recs.pop() # remove last entry (which is '')
367 it = recs.__iter__()
368 while True:
369 rec = it.next()
370 m = parseDiffRE.match(rec)
372 if not m:
373 print "Unknown output from " + str(prog) + "!: " + rec + "\n"
374 continue
376 f = File()
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)
382 f.score = m.group(6)
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)
388 else:
389 f.patch = getPatch(f.srcName)
391 ret.append(f)
392 except StopIteration:
393 pass
394 return ret
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.
399 def getFiles():
400 files = parseDiff('git-diff-cache -z -M --cached HEAD')
401 for f in files:
402 c = f.change
403 if c == 'C':
404 f.text = 'Copy from ' + f.srcName + ' to ' + f.dstName
405 elif c == 'R':
406 f.text = 'Rename from ' + f.srcName + ' to ' + f.dstName
407 elif c == 'N':
408 f.text = 'New file: ' + f.srcName
409 elif c == 'D':
410 f.text = 'Deleted file: ' + f.srcName
411 elif c == 'T':
412 f.text = 'Type change: ' + f.srcName
413 else:
414 f.text = f.srcName
416 if len(parseDiff(['git-diff-files', '-z', f.dstName])) > 0:
417 f.updated = False
418 else:
419 f.updated = True
420 return files
422 def getPatch(file, otherFile = None):
423 if otherFile:
424 f = [file, otherFile]
425 else:
426 f = [file]
427 return runProgram(['git-diff-cache', '-p', '-M', '--cached', 'HEAD'] + f)
429 def formatPatchRichText(patch, colors):
430 ret = '<font color="' + colors['std'] + '">'
431 prev = ' '
432 for l in patch.split('\n'):
433 if len(l) > 0:
434 c = l[0]
435 else:
436 c = ' '
438 if c != prev:
439 if c == '+': style = 'new'
440 elif c == '-': style = 'remove'
441 elif c == '@': style = 'head'
442 else: style = 'std'
443 ret += '</font><font color="' + colors[style] + '">'
444 prev = c
445 ret += str(qt.QStyleSheet.escape(l)) + '<br>\n'
446 return ret
448 class ProgramError(Exception):
449 def __init__(self, program, err):
450 self.program = program
451 self.error = err
453 def runProgram(prog, input=None):
454 debug('runProgram prog: ' + str(prog) + " input: " + str(input))
455 if type(prog) is str:
456 progStr = prog
457 else:
458 progStr = ' '.join(prog)
460 try:
461 pop = subprocess.Popen(prog,
462 shell = type(prog) is str,
463 stderr=subprocess.STDOUT,
464 stdout=subprocess.PIPE,
465 stdin=subprocess.PIPE)
466 except OSError, e:
467 debug("strerror: " + e.strerror)
468 raise ProgramError(progStr, e.strerror)
470 if input != None:
471 pop.stdin.write(input)
472 pop.stdin.close()
474 out = pop.stdout.read()
475 code = pop.wait()
476 if code != 0:
477 debug("error output: " + out)
478 raise ProgramError(progStr, out)
479 debug("output: " + out.replace('\0', '\n'))
480 return out
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."
488 sys.exit(1)
490 try:
491 runProgram('git-cat-file -t HEAD')
492 except OSError, e:
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/')
502 mw = MainWidget()
503 mw.refreshFiles()
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
510 # Metacity) window
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])
516 mw.show()
517 app.setMainWidget(mw)
520 # Handle CTRL-C appropriately
521 signal.signal(signal.SIGINT, lambda s, f: app.quit())
523 ret = app.exec_loop()
524 del settings
525 sys.exit(ret)