Debian Codegraph @

lib/commit.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2006-2007 Lukáš Lalinský <[email protected]om>
5 # Copyright (C) 2006 Trolltech ASA
6 # Copyright (C) 2006 Jelmer Vernooij <[email protected]>
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
22 import os.path
23 from PyQt5 import QtCore, QtGui, QtWidgets
24
25 from breezy.plugins.qbrz.lib.subprocess import SubProcessDialog
26 from breezy.plugins.qbrz.lib.util import (
27 BTN_REFRESH,
28 file_extension,
29 get_global_config,
30 get_qbrz_config,
31 url_for_display,
32 ThrobberWidget,
33 runs_in_loading_queue,
34 StandardButton,
35 InfoWidget,
36 )
37
38 from breezy.plugins.qbrz.lib.logwidget import LogList
39 from breezy.plugins.qbrz.lib.uifactory import ui_current_widget
40 from breezy.plugins.qbrz.lib.trace import reports_exception
41
42 from breezy import errors
43 from breezy.plugins.qbrz.lib.spellcheck import SpellCheckHighlighter, SpellChecker
44 from breezy.plugins.qbrz.lib.autocomplete import get_wordlist_builder
45 from breezy.plugins.qbrz.lib.commit_data import QBzrCommitData
46 from breezy.plugins.qbrz.lib.diff import (DiffButtons, show_diff, InternalWTDiffArgProvider)
47 from breezy.plugins.qbrz.lib.i18n import gettext
48 from breezy.plugins.qbrz.lib import logmodel
49 from breezy.plugins.qbrz.lib.loggraphviz import BranchInfo
50 from breezy.plugins.qbrz.lib.treewidget import (TreeWidget, SelectAllCheckBox, ChangeDescription, FilterModelKeys)
51 from breezy.plugins.qbrz.lib.revisionview import RevisionView
52 from breezy.plugins.qbrz.lib.update import QBzrUpdateWindow
53
54
55 MAX_AUTOCOMPLETE_FILES = 20
56
57
58 class TextEdit(QtWidgets.QTextEdit):
59 messageEntered = QtCore.pyqtSignal()
60
61 def __init__(self, spell_checker, parent=None, main_window=None):
62 QtWidgets.QTextEdit.__init__(self, parent)
63 # RJL The completer, I think, is to provide suggestions for anything typed
64 self.context_tc = None
65 self.completer = None
66 self.spell_checker = spell_checker
67 # RJL eow = 'end of word'?
68 self.eow = "~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="
69 self.main_window = main_window
70
71 def inputMethodEvent(self, e):
72 self.completer.popup().hide()
73 QtWidgets.QTextEdit.inputMethodEvent(self, e)
74
75 def keyPressEvent(self, e):
76 c = self.completer
77 e_key = e.key()
78 if (e_key in (QtCore.Qt.Key_Tab, QtCore.Qt.Key_Backtab)
79 or (c.popup().isVisible() and e_key in (QtCore.Qt.Key_Enter,
80 QtCore.Qt.Key_Return,
81 QtCore.Qt.Key_Escape))):
82 e.ignore()
83 return
84 if (self.main_window and e_key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return)
85 and (int(e.modifiers()) & QtCore.Qt.ControlModifier)):
86 e.ignore()
87 self.messageEntered.emit()
88 return
89
90 isShortcut = e.modifiers() & QtCore.Qt.ControlModifier and e.key() == QtCore.Qt.Key_E
91 if not isShortcut:
92 QtWidgets.QTextEdit.keyPressEvent(self, e)
93
94 ctrlOrShift = e.modifiers() & (QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier)
95 if ctrlOrShift and not e.text():
96 return
97
98 hasModifier = (e.modifiers() != QtCore.Qt.NoModifier) and not ctrlOrShift
99 completionPrefix = self.textUnderCursor()
100
101 # RJL I *think* this is trying to find out whether to hide or display a list
102 # of possible completions. right() is a QString method that:
103 #
104 # Returns a substring that contains the n rightmost characters of the string.
105 # The entire string is returned if n is greater than size() or less than zero.
106 # QString x = "Pineapple";
107 # QString y = x.right(5); // y == "apple"
108 #
109 # or simply x[-5:] in the land of Python, .right(1) is the last letter
110 # which is e.text()[-1:]
111
112 if not isShortcut and (hasModifier or not e.text() or len(completionPrefix) < 2 or e.text()[-1:] in self.eow):
113 c.popup().hide()
114 return
115
116 if completionPrefix != c.completionPrefix():
117 c.setCompletionPrefix(completionPrefix)
118 c.popup().setCurrentIndex(c.completionModel().index(0, 0))
119
120 cr = self.cursorRect()
121 cr.setWidth(c.popup().sizeHintForColumn(0) + c.popup().verticalScrollBar().sizeHint().width())
122 c.complete(cr)
123
124 def textUnderCursor(self):
125 tc = self.textCursor()
126 tc.select(QtGui.QTextCursor.WordUnderCursor)
127 return tc.selectedText()
128
129 def insertCompletion(self, completion):
130 tc = self.textCursor()
131 extra = len(completion) - len(self.completer.completionPrefix())
132 tc.movePosition(QtGui.QTextCursor.Left)
133 tc.movePosition(QtGui.QTextCursor.EndOfWord)
134 # We want the right-most 'extra' letters
135 # tc.insertText(completion.right(extra))
136 tc.insertText(completion[-extra:])
137 self.setTextCursor(tc)
138
139 def setCompleter(self, completer):
140 self.completer = completer
141 completer.setWidget(self)
142 completer.setCaseSensitivity(QtCore.Qt.CaseSensitive)
143 completer.activated['QString'].connect(self.insertCompletion)
144
145 def contextMenuEvent(self, event):
146 menu = self.createStandardContextMenu(event.globalPos())
147
148 self.context_tc = self.cursorForPosition(event.pos())
149 self.context_tc.movePosition(QtGui.QTextCursor.StartOfWord)
150 self.context_tc.movePosition(QtGui.QTextCursor.EndOfWord, QtGui.QTextCursor.KeepAnchor)
151 text = str(self.context_tc.selectedText())
152 if list(self.spell_checker.check(text)):
153 suggestions = self.spell_checker.suggest(text)
154 first_action = menu.actions()[0]
155 for suggestion in suggestions:
156 action = QtWidgets.QAction(suggestion, self)
157 action.triggered[bool].connect(self.suggestion_selected(suggestion))
158 menu.insertAction(first_action, action)
159 if suggestions:
160 menu.insertSeparator(first_action)
161
162 menu.exec_(event.globalPos())
163 event.accept()
164
165 def suggestion_selected(self, text):
166 def _suggestion_selected(b):
167 self.context_tc.insertText(text)
168 return _suggestion_selected
169
170
171 class PendingMergesList(LogList):
172 def __init__(self, *args, **kargs):
173 super().__init__(*args, **kargs)
174 # The rev numbers are currently bogus. Hide that column.
175 # We could work out the revision numbers by loading whole graph, but
176 # that is going to make this much slower.
177 self.header().hideSection(0)
178 self.log_model.last_rev_is_placeholder = True
179
180 def load_tree(self, tree):
181 bi = BranchInfo('', tree, tree.branch)
182 self.log_model.load((bi,), bi, None, False, logmodel.PendingMergesGraphVizLoader)
183
184 def create_context_menu(self, file_ids):
185 super().create_context_menu(file_ids)
186 showinfo = QtWidgets.QAction("Show &information...", self)
187 self.context_menu.insertAction(self.context_menu.actions()[0], showinfo)
188 self.context_menu.setDefaultAction(showinfo)
189 showinfo.triggered[bool].connect(self.show_info_menu)
190
191 def show_info_menu(self, b=False):
192 self.default_action()
193
194 def default_action(self, index=None):
195 """Show information of a single revision from a index."""
196
197 if index is None:
198 index = self.currentIndex()
199
200 # XXX We should make this show all selected revisions...
201
202 revid = index.data(logmodel.RevIdRole)
203 branch = self.log_model.graph_viz.get_revid_branch(revid)
204 parent_window = self.window()
205 window = RevisionView(revid, branch, parent=parent_window)
206 window.show()
207 parent_window.windows.append(window)
208
209
210 def ignore_pattern_handler(change_description: ChangeDescription):
211 return not change_description.ignored_pattern()
212
213
214 class CommitWindow(SubProcessDialog):
215
216 RevisionIdRole = QtCore.Qt.UserRole + 1
217 ParentIdRole = QtCore.Qt.UserRole + 2
218
219 def __init__(self, tree, selected_list, dialog=True, parent=None, local=None, message=None, ui_mode=True):
220 super().__init__(gettext("Commit"), name="commit", default_size=(540, 540),
221 ui_mode=ui_mode, dialog=dialog, parent=parent)
222 self.is_loading = False
223 self.tree = tree
224 self.ci_data = QBzrCommitData(tree=tree)
225 self.ci_data.load()
226
227 self.is_bound = bool(tree.branch.get_bound_location())
228 self.has_pending_merges = len(tree.get_parent_ids()) > 1
229
230 if self.has_pending_merges and selected_list:
231 raise errors.CannotCommitSelectedFileMerge(selected_list)
232
233 self.windows = []
234 self.initial_selected_list = selected_list
235
236 self.process_widget.failed['QString'].connect(self.on_failed)
237
238 self.throbber = ThrobberWidget(self)
239
240 # commit to branch location
241 branch_groupbox = QtWidgets.QGroupBox(gettext("Branch"), self)
242 branch_layout = QtWidgets.QGridLayout(branch_groupbox)
243 self.branch_location = QtWidgets.QLineEdit()
244 self.branch_location.setReadOnly(True)
245 #
246 branch_base = url_for_display(tree.branch.base)
247 master_branch = url_for_display(tree.branch.get_bound_location())
248 if not master_branch:
249 self.branch_location.setText(branch_base)
250 branch_layout.addWidget(self.branch_location, 0, 0, 1, 2)
251 else:
252 self.local_checkbox = QtWidgets.QCheckBox(gettext("&Local commit"))
253 self.local_checkbox.setToolTip(gettext("Local commits are not pushed to the master branch until a normal commit is performed"))
254 branch_layout.addWidget(self.local_checkbox, 0, 0, 1, 2)
255 branch_layout.addWidget(self.branch_location, 1, 0, 1, 2)
256 branch_layout.addWidget(QtWidgets.QLabel(gettext('Description:')), 2, 0, QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
257 self.commit_type_description = QtWidgets.QLabel()
258 self.commit_type_description.setWordWrap(True)
259 branch_layout.addWidget(self.commit_type_description, 2, 1)
260 branch_layout.setColumnStretch(1,10)
261 self.local_checkbox.stateChanged[int].connect(self.update_branch_groupbox)
262 if local:
263 self.local_checkbox.setChecked(True)
264 self.update_branch_groupbox()
265
266 self.not_uptodate_errors = {
267 'BoundBranchOutOfDate': gettext(
268 'Local branch is out of date with master branch.\n'
269 'To commit to master branch, update the local branch.\n'
270 'You can also pass select local to commit to continue working disconnected.'),
271 'OutOfDateTree': gettext('Working tree is out of date. To commit, update the working tree.')
272 }
273 self.not_uptodate_info = InfoWidget(branch_groupbox)
274 not_uptodate_layout = QtWidgets.QHBoxLayout(self.not_uptodate_info)
275
276 # XXX this is to big. Resize
277 not_uptodate_icon = QtWidgets.QLabel()
278 not_uptodate_icon.setPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_MessageBoxWarning))
279 not_uptodate_layout.addWidget(not_uptodate_icon)
280
281 self.not_uptodate_label = QtWidgets.QLabel('error message goes here')
282 not_uptodate_layout.addWidget(self.not_uptodate_label, 2)
283
284 update_button = QtWidgets.QPushButton(gettext('Update'))
285 update_button.clicked[bool].connect(self.open_update_win)
286
287 not_uptodate_layout.addWidget(update_button)
288
289 self.not_uptodate_info.hide()
290 branch_layout.addWidget(self.not_uptodate_info, 3, 0, 1, 2)
291
292 splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical, self)
293
294 message_groupbox = QtWidgets.QGroupBox(gettext("Message"), splitter)
295 splitter.addWidget(message_groupbox)
296 self.tabWidget = QtWidgets.QTabWidget()
297 splitter.addWidget(self.tabWidget)
298 splitter.setStretchFactor(0, 1)
299 splitter.setStretchFactor(1, 8)
300
301 grid = QtWidgets.QGridLayout(message_groupbox)
302
303 self.show_nonversioned_checkbox = QtWidgets.QCheckBox(gettext("Show non-versioned files"))
304 show_nonversioned = get_qbrz_config().get_option_as_bool(self._window_name + "_show_nonversioned")
305 if show_nonversioned:
306 self.show_nonversioned_checkbox.setChecked(True)
307 else:
308 self.show_nonversioned_checkbox.setChecked(False)
309
310 self.filelist_widget = TreeWidget(self)
311 self.filelist_widget.throbber = self.throbber
312 if show_nonversioned:
313 self.filelist_widget.tree_model.set_select_all_kind('all')
314 else:
315 self.filelist_widget.tree_model.set_select_all_kind('versioned')
316
317 self.file_words = {}
318 self.filelist_widget.tree_model.dataChanged[QtCore.QModelIndex, QtCore.QModelIndex].connect(self.on_filelist_data_changed)
319
320 self.selectall_checkbox = SelectAllCheckBox(self.filelist_widget, self)
321 self.selectall_checkbox.setCheckState(QtCore.Qt.Checked)
322
323 language = get_global_config().get_user_option('spellcheck_language') or 'en'
324 spell_checker = SpellChecker(language)
325
326 # Equivalent for 'bzr commit --message'
327 self.message = TextEdit(spell_checker, message_groupbox, main_window=self)
328 self.message.setToolTip(gettext("Enter the commit message"))
329 self.message.messageEntered.connect(self.do_accept)
330 self.completer = QtWidgets.QCompleter()
331 self.completer_model = QtCore.QStringListModel(self.completer)
332 self.completer.setModel(self.completer_model)
333 self.message.setCompleter(self.completer)
334 self.message.setAcceptRichText(False)
335
336 SpellCheckHighlighter(self.message.document(), spell_checker)
337
338 grid.addWidget(self.message, 0, 0, 1, 2)
339
340 # Equivalent for 'bzr commit --fixes'
341 self.bugsCheckBox = QtWidgets.QCheckBox(gettext("&Fixed bugs:"))
342 self.bugsCheckBox.setToolTip(gettext("Set the IDs of bugs fixed by this commit"))
343 self.bugs = QtWidgets.QLineEdit()
344 self.bugs.setToolTip(gettext("Enter the list of bug IDs in format "
345 "<i>tag:id</i> separated by a space, "
346 "e.g. <i>project:123 project:765</i>"))
347 self.bugs.setEnabled(False)
348 self.bugsCheckBox.stateChanged[int].connect(self.enableBugs)
349 grid.addWidget(self.bugsCheckBox, 1, 0)
350 grid.addWidget(self.bugs, 1, 1)
351
352 # Equivalent for 'bzr commit --author'
353 self.authorCheckBox = QtWidgets.QCheckBox(gettext("&Author:"))
354 self.authorCheckBox.setToolTip(gettext("Set the author of this change,"
355 " if it's different from the committer"))
356 self.author = QtWidgets.QLineEdit()
357 self.author.setToolTip(gettext("Enter the author's name, "
358 "e.g. <i>John Doe &lt;[email protected]&gt;</i>"))
359 self.author.setEnabled(False)
360 self.authorCheckBox.stateChanged[int].connect(self.enableAuthor)
361 grid.addWidget(self.authorCheckBox, 2, 0)
362 grid.addWidget(self.author, 2, 1)
363 # default author from config
364 config = self.tree.branch.get_config()
365 self.default_author = config.username()
366 self.custom_author = ''
367 self.author.setText(self.default_author)
368
369 # Display the list of changed files
370 files_tab = QtWidgets.QWidget()
371 self.tabWidget.addTab(files_tab, gettext("Changes"))
372
373 vbox = QtWidgets.QVBoxLayout(files_tab)
374 vbox.addWidget(self.filelist_widget)
375 self.show_nonversioned_checkbox.toggled[bool].connect(self.show_nonversioned)
376 vbox.addWidget(self.show_nonversioned_checkbox)
377 vbox.addWidget(self.selectall_checkbox)
378
379 # Display a list of pending merges
380 if self.has_pending_merges:
381 self.selectall_checkbox.setCheckState(QtCore.Qt.Checked)
382 self.selectall_checkbox.setEnabled(False)
383 self.pending_merges_list = PendingMergesList(self.processEvents, self.throbber, self)
384 self.tabWidget.addTab(self.pending_merges_list,gettext("Pending Merges"))
385 self.tabWidget.setCurrentWidget(self.pending_merges_list)
386 # Pending-merge widget gets disabled as we are executing.
387 self.disableUi[bool].connect(self.pending_merges_list.setDisabled)
388 else:
389 self.pending_merges_list = None
390
391 self.process_panel = self.make_process_panel()
392 self.tabWidget.addTab(self.process_panel, gettext("Status"))
393
394 splitter.setStretchFactor(0, 3)
395
396 vbox = QtWidgets.QVBoxLayout(self)
397 vbox.addWidget(self.throbber)
398 vbox.addWidget(branch_groupbox)
399 vbox.addWidget(splitter)
400
401 # Diff button to view changes in files selected to commit
402 self.diffbuttons = DiffButtons(self)
403 self.diffbuttons.setToolTip(gettext("View changes in files selected to commit"))
404 self.diffbuttons._triggered['QString'].connect(self.show_diff_for_checked)
405
406 self.refresh_button = StandardButton(BTN_REFRESH)
407 self.refresh_button.clicked.connect(self.refresh)
408
409 hbox = QtWidgets.QHBoxLayout()
410 hbox.addWidget(self.diffbuttons)
411 hbox.addWidget(self.refresh_button)
412 hbox.addWidget(self.buttonbox)
413 vbox.addLayout(hbox)
414
415 # groupbox and tabbox signals handling.
416 for w in (message_groupbox, files_tab):
417 # when operation started we need to disable widgets
418 self.disableUi[bool].connect(w.setDisabled)
419
420 self.restore_commit_data()
421 if message:
422 self.message.setText(message)
423
424 # Try to be smart: if there is no saved message
425 # then set focus on Edit Area; otherwise on OK button.
426 if str(self.message.toPlainText()).strip():
427 self.buttonbox.setFocus()
428 else:
429 self.message.setFocus()
430
431 def show(self):
432 # we show the bare form as soon as possible.
433 SubProcessDialog.show(self)
434 # QtCore.QTimer.singleShot(1, self.load)
435 self.load()
436
437 def exec_(self):
438 # QtCore.QTimer.singleShot(1, self.load)
439 self.load()
440 return SubProcessDialog.exec_(self)
441
442 @runs_in_loading_queue
443 @ui_current_widget
444 @reports_exception()
445 def load(self, refresh=False):
446 if refresh:
447 self.throbber.show()
448 self.refresh_button.setDisabled(True)
449 try:
450 with self.tree.lock_read():
451 if self.pending_merges_list:
452 self.pending_merges_list.load_tree(self.tree)
453 # Force the loading of the revisions, before we start
454 # loading the file list.
455 self.pending_merges_list._load_visible_revisions()
456 self.processEvents()
457
458 # filelist_widget is actually a TreeWidget and its model will be a TreeModel
459 self.filelist_widget.tree_model.checkable = not self.pending_merges_list
460 self.is_loading = True
461 # XXX Would be nice if we could only load the files when the
462 # user clicks on the changes tab, but that would mean that
463 # we can't load the words list.
464 if not refresh:
465 want_unversioned = self.show_nonversioned_checkbox.isChecked()
466 self.filelist_widget.tree_filter_model.setFilter(FilterModelKeys.UNVERSIONED, want_unversioned)
467
468 if not want_unversioned and self.initial_selected_list:
469 # if there are any paths from the command line that are not versioned, we want_unversioned.
470 for path in self.initial_selected_list:
471 if not self.tree.is_versioned(path):
472 want_unversioned = True
473 break
474
475 # Now we call our old pal, TreeWidget::set_tree which goes away and calls TreeModel::set_tree
476 self.filelist_widget.set_tree(self.tree, branch=self.tree.branch, changes_mode=True,
477 want_unversioned=want_unversioned,
478 initial_checked_paths=self.initial_selected_list,
479 change_load_filter=ignore_pattern_handler)
480 else:
481 self.filelist_widget.refresh()
482 self.is_loading = False
483 self.processEvents()
484 self.update_compleater_words()
485 finally:
486 self.throbber.hide()
487 self.refresh_button.setDisabled(False)
488
489 def refresh(self):
490 self.load(True)
491
492 def on_filelist_data_changed(self, start_index, end_index):
493 self.update_compleater_words()
494
495 def update_compleater_words(self):
496 if self.is_loading:
497 return
498
499 num_files_loaded = 0
500
501 words = set()
502 for ref in self.filelist_widget.tree_model.iter_checked():
503 path = ref.path
504 if path not in self.file_words:
505 file_words = set()
506 if num_files_loaded < MAX_AUTOCOMPLETE_FILES:
507 file_words.add(path)
508 file_words.add(os.path.split(path)[-1])
509 change = self.filelist_widget.tree_model.inventory_data_by_path[ref.path].change
510 if change and change.is_renamed():
511 file_words.add(change.oldpath())
512 file_words.add(os.path.split(change.oldpath())[-1])
513 # if num_versioned_files < MAX_AUTOCOMPLETE_FILES:
514 ext = file_extension(path)
515 builder = get_wordlist_builder(ext)
516 if builder is not None:
517 try:
518 abspath = os.path.join(self.tree.basedir, path)
519 file = open(abspath, 'rt')
520 file_words.update(builder.iter_words(file))
521 self.processEvents()
522 except EnvironmentError:
523 pass
524 self.file_words[path] = file_words
525 num_files_loaded += 1
526 else:
527 file_words = self.file_words[path]
528 words.update(file_words)
529 words = list(words)
530 words.sort(key=lambda x: x.lower())
531 self.completer_model.setStringList(words)
532
533 def enableBugs(self, state):
534 if state == QtCore.Qt.Checked:
535 self.bugs.setEnabled(True)
536 self.bugs.setFocus(QtCore.Qt.OtherFocusReason)
537 else:
538 self.bugs.setEnabled(False)
539
540 def enableAuthor(self, state):
541 if state == QtCore.Qt.Checked:
542 self.author.setEnabled(True)
543 self.author.setText(self.custom_author)
544 self.author.setFocus(QtCore.Qt.OtherFocusReason)
545 else:
546 self.author.setEnabled(False)
547 self.custom_author = self.author.text()
548 self.author.setText(self.default_author)
549
550 def restore_commit_data(self):
551 message = self.ci_data['message']
552 if message:
553 self.message.setText(message)
554 bug = self.ci_data['bugs']
555 if bug:
556 self.bugs.setText(bug)
557 self.bugs.setEnabled(True)
558 self.bugsCheckBox.setChecked(True)
559
560 def save_commit_data(self):
561 if self.tree.branch.get_physical_lock_status() or self.tree.branch.is_locked():
562 # XXX maybe show this in a GUI MessageBox (information box)???
563 from breezy.trace import warning
564 warning("Cannot save commit data because the branch is locked.")
565 return
566 # collect data
567 ci_data = QBzrCommitData(tree=self.tree)
568 message = str(self.message.toPlainText()).strip()
569 if message:
570 ci_data['message'] = message
571 bug_str = ''
572 if self.bugsCheckBox.isChecked():
573 bug_str = str(self.bugs.text()).strip()
574 if bug_str:
575 ci_data['bugs'] = bug_str
576 # save only if data different
577 if not ci_data.compare_data(self.ci_data, all_keys=False):
578 ci_data.save()
579
580 def wipe_commit_data(self):
581 if self.tree.branch.get_physical_lock_status() or self.tree.branch.is_locked():
582 # XXX maybe show this in a GUI MessageBox (information box)???
583 from breezy.trace import warning
584 warning("Cannot wipe commit data because the branch is locked.")
585 return
586 self.ci_data.wipe()
587
588 def _get_message(self):
589 return str(self.message.toPlainText()).strip()
590
591 def _get_selected_files(self):
592 """Return (has_files_to_commit[bool], files_to_commit[list], files_to_add[list])"""
593 if self.has_pending_merges:
594 return True, [], []
595
596 files_to_commit = []
597 files_to_add = []
598 for ref in self.filelist_widget.tree_model.iter_checked():
599 if ref.file_id is None:
600 files_to_add.append(ref.path)
601 files_to_commit.append(ref.path)
602
603 if not files_to_commit:
604 return False, [], []
605 else:
606 return True, files_to_commit, files_to_add
607
608 def validate(self):
609 if not self._get_message():
610 self.operation_blocked(gettext("You should provide a commit message."))
611 self.message.setFocus()
612 return False
613 if not self._get_selected_files()[0]:
614 if not self.ask_confirmation(gettext("No changes selected to commit.\nDo you want to commit anyway?")):
615 return False
616 return True
617
618 def do_start(self):
619 args = ["commit"]
620 message = self._get_message()
621 # AND we need to quote it...
622 args.extend(['-m', message]) # keep them separated to avoid bug #297606
623
624 has_files_to_commit, files_to_commit, files_to_add = self._get_selected_files()
625 if not has_files_to_commit:
626 # Possible [rare] problems:
627 # 1. unicode tree root in non-user encoding
628 # may provoke UnicodeEncodeError in subprocess (@win32)
629 # 2. if branch has no commits yet then operation may fail
630 # because of bug #299879
631 args.extend(['--exclude', self.tree.basedir])
632 args.append('--unchanged')
633 else:
634 args.extend(files_to_commit)
635
636 if self.bugsCheckBox.isChecked():
637 for s in str(self.bugs.text()).split():
638 args.append(("--fixes=%s" % s))
639
640 if self.authorCheckBox.isChecked():
641 args.append(("--author=%s" % str(self.author.text())))
642
643 if self.is_bound and self.local_checkbox.isChecked():
644 args.append("--local")
645
646 base_directory = self.tree.basedir
647 commands = []
648 if files_to_add:
649 commands.append((base_directory, ["add", "--no-recurse"] + files_to_add))
650 commands.append((base_directory, args))
651
652 self.tabWidget.setCurrentWidget(self.process_panel)
653 self.process_widget.start_multi(commands)
654
655 def show_nonversioned(self, state):
656 """Show/hide non-versioned files."""
657 if state and not self.filelist_widget.want_unversioned:
658 state = self.filelist_widget.get_state()
659 # RJLRJL: might need to set initial_checked_paths here
660 self.filelist_widget.set_tree(self.tree, changes_mode=True, want_unversioned=True, change_load_filter=ignore_pattern_handler)
661 self.filelist_widget.restore_state(state)
662 if state:
663 self.filelist_widget.tree_model.set_select_all_kind('all')
664 else:
665 self.filelist_widget.tree_model.set_select_all_kind('versioned')
666 self.filelist_widget.tree_filter_model.setFilter(FilterModelKeys.UNVERSIONED, state)
667
668 def _save_or_wipe_commit_data(self):
669 if not self.process_widget.is_running():
670 if self.process_widget.is_finished:
671 self.wipe_commit_data()
672 else:
673 self.save_commit_data()
674
675 def closeEvent(self, event):
676 self._save_or_wipe_commit_data()
677 qbrz_config = get_qbrz_config()
678 qbrz_config.set_option(self._window_name + "_show_nonversioned", self.show_nonversioned_checkbox.isChecked())
679 qbrz_config.save() # do I need this or is .saveSize() enough?
680 return SubProcessDialog.closeEvent(self, event)
681
682 def reject(self):
683 self._save_or_wipe_commit_data()
684 return SubProcessDialog.reject(self)
685
686 def update_branch_groupbox(self):
687 if not self.local_checkbox.isChecked():
688 # commit to master branch selected
689 loc = url_for_display(self.tree.branch.get_bound_location())
690 desc = gettext("A commit will be made directly to the master branch, keeping the local and master branches in sync.")
691 else:
692 # local commit selected
693 loc = url_for_display(self.tree.branch.base)
694 desc = gettext("A local commit to the branch will be performed. The master branch will not be updated until "
695 "a non-local commit is made.")
696 # update GUI
697 self.branch_location.setText(loc)
698 self.commit_type_description.setText(desc)
699
700 def show_diff_for_checked(self, ext_diff=None, dialog_action='commit'):
701 """Diff button clicked: show the diff for checked entries.
702
703 @param ext_diff: selected external diff tool (if any)
704 @param dialog_action: purpose of parent window (main action)
705 """
706 # XXX make this function universal for both qcommit and qrevert (?)
707 if self.filelist_widget.tree_model.checkable:
708 checked = [] # checked versioned
709 unversioned = [] # checked unversioned (supposed to be added)
710 for ref in self.filelist_widget.tree_model.iter_checked():
711 if ref.file_id:
712 checked.append(ref.path)
713 else:
714 unversioned.append(ref.path)
715
716 if checked:
717 arg_provider = InternalWTDiffArgProvider(
718 self.tree.basis_tree().get_revision_id(), self.tree,
719 self.tree.branch, self.tree.branch,
720 specific_files=checked)
721
722 show_diff(arg_provider, ext_diff=ext_diff, parent_window=self, context=self.filelist_widget.diff_context)
723 else:
724 msg = "No changes selected to " + dialog_action
725 QtWidgets.QMessageBox.warning(self, "QBrz - " + gettext("Diff"), gettext(msg), QtWidgets.QMessageBox.Ok)
726
727 if unversioned:
728 # XXX show infobox with message that not all files shown in diff
729 pass
730 else:
731 arg_provider = InternalWTDiffArgProvider(self.tree.basis_tree().get_revision_id(), self.tree, self.tree.branch, self.tree.branch)
732 show_diff(arg_provider, ext_diff=ext_diff, parent_window=self, context=self.filelist_widget.diff_context)
733
734 def on_failed(self, error):
735 SubProcessDialog.on_failed(self, error)
736 error = str(error)
737 if error in self.not_uptodate_errors:
738 self.not_uptodate_label.setText(self.not_uptodate_errors[error])
739 self.not_uptodate_info.show()
740
741 def open_update_win(self, b):
742 update_window = QBzrUpdateWindow(self.tree)
743 self.windows.append(update_window)
744 update_window.show()
745 update_window.subprocessFinished[bool].connect(self.not_uptodate_info.setHidden)