Make it possible to commit merges in Git mode.
[hgct.git] / main.py
blobcfd63a7003bf4f32fa73a48883ba8936ff630dbc
1 #!/usr/bin/env python
3 # Copyright (c) 2005 Fredrik Kuivinen <freku045@student.liu.se>
4 # Copyright (c) 2005 Mark Williamson <mark.williamson@cl.cam.ac.uk>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License version 2 as
8 # published by the Free Software Foundation.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 import sys, math, random, qt, os, re, signal, sets, settings
20 from optparse import OptionParser
22 from ctcore import *
24 # Determine semantics according to executable name. Default to git.
25 if os.path.basename(sys.argv[0]) == 'hgct':
26 print "defaulting to import hg because arg = %s" % sys.argv[0]
27 import hg as scm
28 else:
29 import git as scm
31 qconnect = qt.QObject.connect
32 Qt = qt.Qt
33 #DEBUG = 1
35 class CommitError(Exception):
36 def __init__(self, operation, msg):
37 self.operation = operation
38 self.msg = msg
40 class FileState:
41 pass
43 class MyListItem(qt.QCheckListItem):
44 def __init__(self, parent, file, commitMsg = False):
45 qt.QCheckListItem.__init__(self, parent, file.text, qt.QCheckListItem.CheckBox)
46 self.file = file
47 self.commitMsg = commitMsg
49 def compare(self, item, col, asc):
50 if self.commitMsg:
51 if asc:
52 return -1
53 else:
54 return 1
55 elif item.commitMsg:
56 if asc:
57 return 1
58 else:
59 return -1
60 else:
61 return cmp(self.key(col, asc), item.key(col, asc))
63 def paintCell(self, p, cg, col, w, a):
64 if self.commitMsg:
65 qt.QListViewItem.paintCell(self, p, cg, col, w, a)
66 else:
67 qt.QCheckListItem.paintCell(self, p, cg, col, w, a)
69 def isSelected(self):
70 return self.state() == qt.QCheckListItem.On
72 def setSelected(self, s):
73 if s:
74 self.setState(qt.QCheckListItem.On)
75 else:
76 self.setState(qt.QCheckListItem.Off)
78 class MyListView(qt.QListView):
79 def __init__(self, parent=None, name=None):
80 qt.QListView.__init__(self, parent, name)
82 def __iter__(self):
83 return ListViewIterator(self)
85 class ListViewIterator:
86 def __init__(self, listview):
87 self.it = qt.QListViewItemIterator(listview)
89 def next(self):
90 cur = self.it.current()
91 if cur:
92 self.it += 1
93 if cur.commitMsg:
94 return self.next()
95 else:
96 return cur
97 else:
98 raise StopIteration()
100 def __iter__(self):
101 return self
103 class MainWidget(qt.QMainWindow):
104 def __init__(self, parent=None, name=None):
105 qt.QMainWindow.__init__(self, parent, name)
106 splitter = qt.QSplitter(Qt.Vertical, self)
108 fW = MyListView(splitter)
109 fW.setFocus()
110 fW.setSelectionMode(qt.QListView.NoSelection)
111 fW.addColumn('Description')
112 fW.setResizeMode(qt.QListView.AllColumns)
114 text = qt.QWidgetStack(splitter)
116 self.setCentralWidget(splitter)
117 self.setCaption(applicationName)
119 self.newCurLambda = lambda i: self.currentChange(i)
120 qconnect(fW, qt.SIGNAL("currentChanged(QListViewItem*)"), self.newCurLambda)
122 ops = qt.QPopupMenu(self)
123 ops.insertItem("Commit Selected Files", self.commit, Qt.CTRL+Qt.Key_T)
124 ops.insertItem("Refresh", self.refreshFiles, Qt.CTRL+Qt.Key_R)
125 ops.insertItem("Select All", self.selectAll, Qt.CTRL+Qt.Key_A)
126 ops.insertItem("Unselect All", self.unselectAll, Qt.CTRL+Qt.Key_U)
127 ops.insertItem("Preferences...", self.showPrefs, Qt.CTRL+Qt.Key_P)
129 m = self.menuBar()
130 m.insertItem("&Operations", ops)
132 h = qt.QPopupMenu(self)
133 h.insertItem("&About", self.about)
134 m.insertItem("&Help", h)
136 qconnect(fW, qt.SIGNAL("contextMenuRequested(QListViewItem*, const QPoint&, int)"),
137 self.contextMenuRequestedSlot)
138 self.fileOps = qt.QPopupMenu(self)
139 self.fileOps.insertItem("Toggle selection", self.toggleFile)
140 self.fileOps.insertItem("Edit", self.editFile, Qt.CTRL+Qt.Key_E)
141 self.fileOps.insertItem("Discard changes", self.discardFile)
142 self.fileOps.insertItem("Ignore file", self.ignoreFile)
144 # The following attribute is set by contextMenuRequestedSlot
145 # and currentChange and used by the fileOps
146 self.currentContextItem = None
148 self.patchColors = {'std': 'black', 'new': '#009600', 'remove': '#C80000', 'head': '#C800C8'}
150 self.filesW = fW
151 self.files = []
152 self.splitter = splitter
153 self.text = text
155 f = File()
156 f.text = "Commit message"
157 f.textW = self.newTextEdit()
158 f.textW.setTextFormat(Qt.PlainText)
159 f.textW.setReadOnly(False)
160 f.textW.setText(settings.signoff)
162 self.cmitFile = f
163 self.createCmitItem()
164 self.editorProcesses = sets.Set()
165 self.loadSettings()
167 def loadSettings(self):
168 self.splitter.setSizes(settings.splitter)
170 def closeEvent(self, e):
171 s = self.size()
172 settings.width = s.width()
173 settings.height = s.height()
174 settings.splitter = self.splitter.sizes()
175 e.accept()
177 def createCmitItem(self):
178 self.cmitItem = MyListItem(self.filesW, self.cmitFile, True)
179 self.cmitItem.setSelectable(False)
180 self.filesW.insertItem(self.cmitItem)
182 def about(self, ignore):
183 qt.QMessageBox.about(self, "About " + applicationName,
184 "<qt><center><h1>" + applicationName + " " + version + """</h1></center>\n
185 <center>Copyright &copy; 2005 Fredrik Kuivinen &lt;freku045@student.liu.se&gt;
186 </center>\n<p>This program is free software; you can redistribute it and/or
187 modify it under the terms of the GNU General Public License version 2 as
188 published by the Free Software Foundation.</p></qt>""")
190 def contextMenuRequestedSlot(self, item, pos, col):
191 if item and not item.commitMsg:
192 self.currentContextItem = item
193 self.fileOps.exec_loop(qt.QCursor.pos())
194 else:
195 self.currentContextItem = None
197 def toggleFile(self, ignored):
198 it = self.currentContextItem
199 if not it:
200 return
202 if it.isSelected():
203 it.setSelected(False)
204 else:
205 it.setSelected(True)
207 def editFile(self, ignored):
208 it = self.currentContextItem
209 if not it:
210 return
212 ed = getEditor()
213 if not ed:
214 qt.QMessageBox.warning(self, 'No editor found',
215 '''No editor found. Gct looks for an editor to execute in the environment
216 variable GCT_EDITOR, if that variable is not set it will use the variable
217 EDITOR.''')
218 return
220 # This piece of code is not entirely satisfactory. If the user
221 # has EDITOR set to 'vi', or some other non-X application, the
222 # editor will be started in the terminal which (h)gct was
223 # started in. A better approach would be to close stdin and
224 # stdout after the fork but before the exec, but this doesn't
225 # seem to be possible with QProcess.
226 p = qt.QProcess(ed)
227 p.addArgument(it.file.dstName)
228 p.setCommunication(0)
229 qconnect(p, qt.SIGNAL('processExited()'), self.editorExited)
230 if not p.launch(qt.QByteArray()):
231 qt.QMessageBox.warning(self, 'Failed to launch editor',
232 shortName + ' failed to launch the ' + \
233 'editor. The command used was: ' + \
234 ed + ' ' + it.file.dstName)
235 else:
236 self.editorProcesses.add(p)
238 def editorExited(self):
239 p = self.sender()
240 status = p.exitStatus()
241 file = str(p.arguments()[1])
242 editor = str(p.arguments()[0]) + ' ' + file
243 if not p.normalExit():
244 qt.QMessageBox.warning(self, 'Editor failure',
245 'The editor, ' + editor + ', exited abnormally.')
246 elif status != 0:
247 qt.QMessageBox.warning(self, 'Editor failure',
248 'The editor, ' + editor + ', exited with exit code ' + str(status))
250 self.editorProcesses.remove(p)
251 scm.doUpdateCache(file)
252 self.refreshFiles()
254 def discardFile(self, ignored):
255 it = self.currentContextItem
256 if not it:
257 return
259 scm.discardFile(it.file)
260 self.refreshFiles()
262 def ignoreFile(self, ignored):
263 it = self.currentContextItem
264 if not it:
265 return
267 scm.ignoreFile(it.file)
268 self.refreshFiles()
270 def currentChange(self, item):
271 self.text.raiseWidget(item.file.textW)
272 self.text.update()
273 self.currentContextItem = item
275 def selectedItems(self):
276 ret = []
277 for item in self.filesW:
278 if item.isSelected():
279 ret.append(item)
280 return ret
282 def commit(self, id):
283 selFileNames = []
284 keepFiles = []
285 commitFiles = []
287 for item in self.filesW:
288 debug("file: " + item.file.text)
289 if item.isSelected():
290 selFileNames.append(item.file.text)
291 commitFiles.append(item.file.dstName)
292 else:
293 keepFiles.append(item.file)
295 commitMsg = str(self.cmitItem.file.textW.text())
297 if not selFileNames:
298 qt.QMessageBox.information(self, "Commit - " + applicationName,
299 "No files selected for commit.", "&Ok")
300 return
302 commitMsg = fixCommitMsgWhiteSpace(commitMsg)
303 if scm.commitIsMerge():
304 mergeMsg = scm.mergeMessage()
305 else:
306 mergeMsg = ''
308 if(qt.QMessageBox.question(self, "Confirm Commit - " + applicationName,
309 '<qt><p>' + mergeMsg + '</p><p>Do you want to commit the following file(s):</p><blockquote>' +
310 '<br>'.join(selFileNames) +
311 '''</blockquote><p>with the commit message:</p><blockquote><pre>''' +
312 str(qt.QStyleSheet.escape(commitMsg)) + '</pre></blockquote></qt>',
313 '&Yes', '&No')):
314 return
315 else:
316 try:
317 scm.doCommit(keepFiles, commitFiles, commitMsg)
318 except CommitError, e:
319 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
320 "Commit failed during " + e.operation + ": " + e.msg,
321 '&Ok')
322 except OSError, e:
323 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
324 "Commit failed: " + e.strerror,
325 '&Ok')
326 else:
327 self.cmitItem.file.textW.setText(settings.signoff)
328 self.refreshFiles()
330 def getFileState(self):
331 ret = FileState()
332 cur = self.filesW.currentItem()
333 if cur and cur != self.cmitItem:
334 ret.current = self.filesW.currentItem().file.srcName
335 else:
336 ret.current = None
337 ret.selected = {}
339 for x in self.filesW:
340 if x.isSelected():
341 ret.selected[x.file.srcName] = True
342 return ret
344 def restoreFileState(self, state):
345 for x in self.filesW:
346 if state.selected.has_key(x.file.srcName):
347 x.setSelected(True)
348 if x.file.srcName == state.current:
349 self.filesW.setCurrentItem(x)
351 def newTextEdit(self):
352 ret = qt.QTextEdit()
353 self.text.addWidget(ret)
354 return ret
356 def setFiles(self, files):
357 state = self.getFileState()
358 self.filesW.clear()
359 self.createCmitItem()
360 for f in self.files:
361 self.text.removeWidget(f.textW)
363 self.files = []
364 for f in files:
365 f.textW = self.newTextEdit()
366 f.textW.setReadOnly(True)
367 f.textW.setTextFormat(Qt.RichText)
368 f.textW.setText(formatPatchRichText(f.patch, self.patchColors))
369 self.files.append(f)
370 self.filesW.insertItem(MyListItem(self.filesW, f))
372 self.filesW.setCurrentItem(self.cmitItem)
374 # For some reason the currentChanged signal isn't emitted
375 # here. We call currentChange ourselves instead.
376 self.currentChange(self.cmitItem)
378 self.restoreFileState(state)
380 def refreshFiles(self, ignored=None):
381 files = scm.getFiles()
382 if settings.quitOnNoChanges and len(files) == 0:
383 self.close()
384 else:
385 self.setFiles(files)
387 return len(files) > 0
389 def selectAll(self):
390 for x in self.filesW:
391 x.setSelected(True)
393 def unselectAll(self):
394 for x in self.filesW:
395 x.setSelected(False)
397 def showPrefs(self):
398 settings.showSettings()
400 commitMsgRE = re.compile('[ \t\r\f\v]*\n\\s*\n')
401 def fixCommitMsgWhiteSpace(msg):
402 msg = msg.lstrip()
403 msg = msg.rstrip()
404 msg = re.sub(commitMsgRE, '\n\n', msg)
405 msg += '\n'
406 return msg
408 def formatPatchRichText(patch, colors):
409 ret = ['<qt><pre><font color="', colors['std'], '">']
410 prev = ' '
411 for l in patch.split('\n'):
412 if len(l) > 0:
413 c = l[0]
414 else:
415 c = ' '
417 if c != prev:
418 if c == '+': style = 'new'
419 elif c == '-': style = 'remove'
420 elif c == '@': style = 'head'
421 else: style = 'std'
422 ret.extend(['</font><font color="', colors[style], '">'])
423 prev = c
424 line = qt.QStyleSheet.escape(l).ascii()
425 if not line:
426 line = ''
427 else:
428 line = str(line)
429 ret.extend([line, '\n'])
430 ret.append('</pre></qt>')
431 return ''.join(ret)
433 def getEditor():
434 if os.environ.has_key('GCT_EDITOR'):
435 return os.environ['GCT_EDITOR']
436 elif os.environ.has_key('EDITOR'):
437 return os.environ['EDITOR']
438 else:
439 return None
441 scm.repoValid()
443 app = qt.QApplication(sys.argv)
445 optParser = OptionParser(usage="%prog [--gui]", version=applicationName + ' ' + version)
446 optParser.add_option('-g', '--gui', action='store_true', dest='gui',
447 help='Unconditionally start the GUI')
448 (options, args) = optParser.parse_args(app.argv()[1:])
450 settings = settings.Settings()
451 mw = MainWidget()
453 if not mw.refreshFiles() and settings.quitOnNoChanges and not options.gui:
454 print 'No outstanding changes'
455 sys.exit(0)
457 mw.resize(settings.width, settings.height)
459 # The following code doesn't work correctly in some (at least
460 # Metacity) window
461 # managers. http://doc.trolltech.com/3.3/geometry.html contains some
462 # information about this issue.
463 # mw.move(settings.readNumEntry('x', 100)[0],
464 # settings.readNumEntry('y', 100)[0])
466 mw.show()
467 app.setMainWidget(mw)
470 # Handle CTRL-C appropriately
471 signal.signal(signal.SIGINT, lambda s, f: app.quit())
473 ret = app.exec_loop()
474 settings.writeSettings()
475 sys.exit(ret)