/b-gtk/fix-viz

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/b-gtk/fix-viz

« back to all changes in this revision

Viewing changes to commit.py

  • Committer: Jelmer Vernooij
  • Date: 2012-07-09 15:23:26 UTC
  • mto: This revision was merged to the branch mainline in revision 794.
  • Revision ID: jelmer@samba.org-20120709152326-dzxb8zoz0btull7n
Remove bzr-notify.

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
from gi.repository import Pango
23
23
 
24
24
from bzrlib import (
 
25
    bencode,
25
26
    errors,
26
27
    osutils,
 
28
    revision as _mod_revision,
27
29
    trace,
 
30
    tsort,
28
31
    )
29
 
try:
30
 
    from bzrlib import bencode
31
 
except ImportError:
32
 
    from bzrlib.util import bencode
33
 
 
34
32
from bzrlib.plugins.gtk.dialog import question_dialog
 
33
from bzrlib.plugins.gtk.diff import DiffView
35
34
from bzrlib.plugins.gtk.errors import show_bzr_error
36
35
from bzrlib.plugins.gtk.i18n import _i18n
 
36
from bzrlib.plugins.gtk.commitmsgs import SavedCommitMessagesManager
37
37
 
38
38
try:
39
39
    import dbus
43
43
    have_dbus = False
44
44
 
45
45
 
 
46
def _get_sorted_revisions(tip_revision, revision_ids, parent_map):
 
47
    """Get an iterator which will return the revisions in merge sorted order.
 
48
 
 
49
    This will build up a list of all nodes, such that only nodes in the list
 
50
    are referenced. It then uses MergeSorter to return them in 'merge-sorted'
 
51
    order.
 
52
 
 
53
    :param revision_ids: A set of revision_ids
 
54
    :param parent_map: The parent information for each node. Revisions which
 
55
        are considered ghosts should not be present in the map.
 
56
    :return: iterator from MergeSorter.iter_topo_order()
 
57
    """
 
58
    # MergeSorter requires that all nodes be present in the graph, so get rid
 
59
    # of any references pointing outside of this graph.
 
60
    parent_graph = {}
 
61
    for revision_id in revision_ids:
 
62
        if revision_id not in parent_map: # ghost
 
63
            parent_graph[revision_id] = []
 
64
        else:
 
65
            # Only include parents which are in this sub-graph
 
66
            parent_graph[revision_id] = [p for p in parent_map[revision_id]
 
67
                                            if p in revision_ids]
 
68
    sorter = tsort.MergeSorter(parent_graph, tip_revision)
 
69
    return sorter.iter_topo_order()
 
70
 
 
71
 
46
72
def pending_revisions(wt):
47
73
    """Return a list of pending merges or None if there are none of them.
48
74
 
53
79
    """
54
80
    parents = wt.get_parent_ids()
55
81
    if len(parents) < 2:
56
 
        return None
 
82
        return
57
83
 
58
84
    # The basic pending merge algorithm uses the same algorithm as
59
85
    # bzrlib.status.show_pending_merges
61
87
    branch = wt.branch
62
88
    last_revision = parents[0]
63
89
 
64
 
    if last_revision is not None:
65
 
        try:
66
 
            ignore = set(branch.repository.get_ancestry(last_revision,
67
 
                                                        topo_sorted=False))
68
 
        except errors.NoSuchRevision:
69
 
            # the last revision is a ghost : assume everything is new
70
 
            # except for it
71
 
            ignore = set([None, last_revision])
72
 
    else:
73
 
        ignore = set([None])
 
90
    graph = branch.repository.get_graph()
 
91
    other_revisions = [last_revision]
74
92
 
75
93
    pm = []
76
94
    for merge in pending:
77
 
        ignore.add(merge)
78
 
        try:
79
 
            rev = branch.repository.get_revision(merge)
80
 
            children = []
81
 
            pm.append((rev, children))
82
 
 
83
 
            # This does need to be topo sorted, so we search backwards
84
 
            inner_merges = branch.repository.get_ancestry(merge)
85
 
            assert inner_merges[0] is None
86
 
            inner_merges.pop(0)
87
 
            for mmerge in reversed(inner_merges):
88
 
                if mmerge in ignore:
89
 
                    continue
90
 
                rev = branch.repository.get_revision(mmerge)
91
 
                children.append(rev)
92
 
 
93
 
                ignore.add(mmerge)
94
 
        except errors.NoSuchRevision:
95
 
            print "DEBUG: NoSuchRevision:", merge
96
 
 
97
 
    return pm
 
95
        try:
 
96
            merge_rev = branch.repository.get_revision(merge)
 
97
        except errors.NoSuchRevision:
 
98
            # If we are missing a revision, just print out the revision id
 
99
            trace.mutter("ghost: %r", merge)
 
100
            other_revisions.append(merge)
 
101
            continue
 
102
 
 
103
        # Find all of the revisions in the merge source, which are not in the
 
104
        # last committed revision.
 
105
        merge_extra = graph.find_unique_ancestors(merge, other_revisions)
 
106
        other_revisions.append(merge)
 
107
        merge_extra.discard(_mod_revision.NULL_REVISION)
 
108
 
 
109
        # Get a handle to all of the revisions we will need
 
110
        try:
 
111
            revisions = dict((rev.revision_id, rev) for rev in
 
112
                             branch.repository.get_revisions(merge_extra))
 
113
        except errors.NoSuchRevision:
 
114
            # One of the sub nodes is a ghost, check each one
 
115
            revisions = {}
 
116
            for revision_id in merge_extra:
 
117
                try:
 
118
                    rev = branch.repository.get_revisions([revision_id])[0]
 
119
                except errors.NoSuchRevision:
 
120
                    revisions[revision_id] = None
 
121
                else:
 
122
                    revisions[revision_id] = rev
 
123
 
 
124
         # Display the revisions brought in by this merge.
 
125
        rev_id_iterator = _get_sorted_revisions(merge, merge_extra,
 
126
                            branch.repository.get_parent_map(merge_extra))
 
127
        # Skip the first node
 
128
        num, first, depth, eom = rev_id_iterator.next()
 
129
        if first != merge:
 
130
            raise AssertionError('Somehow we misunderstood how'
 
131
                ' iter_topo_order works %s != %s' % (first, merge))
 
132
        children = []
 
133
        for num, sub_merge, depth, eom in rev_id_iterator:
 
134
            rev = revisions[sub_merge]
 
135
            if rev is None:
 
136
                trace.warning("ghost: %r", sub_merge)
 
137
                continue
 
138
            children.append(rev)
 
139
        yield (merge_rev, children)
98
140
 
99
141
 
100
142
_newline_variants_re = re.compile(r'\r\n?')
101
143
def _sanitize_and_decode_message(utf8_message):
102
144
    """Turn a utf-8 message into a sanitized Unicode message."""
103
145
    fixed_newline = _newline_variants_re.sub('\n', utf8_message)
104
 
    return fixed_newline.decode('utf-8')
 
146
    return osutils.safe_unicode(fixed_newline)
105
147
 
106
148
 
107
149
class CommitDialog(Gtk.Dialog):
108
150
    """Implementation of Commit."""
109
151
 
110
152
    def __init__(self, wt, selected=None, parent=None):
111
 
        Gtk.Dialog.__init__(self, title="Commit to %s" % wt.basedir,
112
 
                            parent=parent, flags=0,)
 
153
        super(CommitDialog, self).__init__(
 
154
            title="Commit to %s" % wt.basedir, parent=parent, flags=0)
113
155
        self.connect('delete-event', self._on_delete_window)
114
156
        self._question_dialog = question_dialog
115
157
 
122
164
        self._enable_per_file_commits = True
123
165
        self._commit_all_changes = True
124
166
        self.committed_revision_id = None # Nothing has been committed yet
 
167
        self._last_selected_file = None
125
168
        self._saved_commit_messages_manager = SavedCommitMessagesManager(
126
169
            self._wt, self._wt.branch)
127
170
 
133
176
        """Setup the member variables for state."""
134
177
        self._basis_tree = self._wt.basis_tree()
135
178
        self._delta = None
136
 
        self._pending = pending_revisions(self._wt)
 
179
        self._wt.lock_read()
 
180
        try:
 
181
            self._pending = list(pending_revisions(self._wt))
 
182
        finally:
 
183
            self._wt.unlock()
137
184
 
138
185
        self._is_checkout = (self._wt.branch.get_bound_location() is not None)
139
186
 
191
238
 
192
239
        all_enabled = (self._selected is None)
193
240
        # The first entry is always the 'whole tree'
194
 
        all_iter = store.append([None, None, all_enabled, 'All Files', '', ''])
 
241
        all_iter = store.append(["", "", all_enabled, 'All Files', '', ''])
195
242
        initial_cursor = store.get_path(all_iter)
196
243
        # should we pass specific_files?
197
244
        self._wt.lock_read()
228
275
        # This sets the cursor, which causes the expander to close, which
229
276
        # causes the _file_message_text_view to never get realized. So we have
230
277
        # to give it a little kick, or it warns when we try to grab the focus
231
 
        self._treeview_files.set_cursor(initial_cursor, None, None)
 
278
        self._treeview_files.set_cursor(initial_cursor, None, False)
232
279
 
233
280
        def _realize_file_message_tree_view(*args):
234
281
            self._file_message_text_view.realize()
242
289
            self._check_local.hide()
243
290
            return
244
291
        if have_dbus:
245
 
            bus = dbus.SystemBus()
 
292
            try:
 
293
                bus = dbus.SystemBus()
 
294
            except dbus.DBusException:
 
295
                trace.mutter("DBus system bus not available")
 
296
                self._check_local.show()
 
297
                return
246
298
            try:
247
299
                proxy_obj = bus.get_object('org.freedesktop.NetworkManager',
248
300
                                           '/org/freedesktop/NetworkManager')
250
302
                trace.mutter("networkmanager not available.")
251
303
                self._check_local.show()
252
304
                return
253
 
            
 
305
 
254
306
            dbus_iface = dbus.Interface(proxy_obj,
255
307
                                        'org.freedesktop.NetworkManager')
256
308
            try:
282
334
        """Build up the dialog widgets."""
283
335
        # The primary pane which splits it into left and right (adjustable)
284
336
        # sections.
285
 
        self._hpane = Gtk.HPaned()
 
337
        self._hpane = Gtk.Paned.new(Gtk.Orientation.HORIZONTAL)
286
338
 
287
339
        self._construct_left_pane()
288
340
        self._construct_right_pane()
389
441
        # file_label.show()
390
442
        self._files_box.pack_start(file_label, False, True, 0)
391
443
 
392
 
        self._commit_all_files_radio = Gtk.RadioButton(
 
444
        self._commit_all_files_radio = Gtk.RadioButton.new_with_label(
393
445
            None, _i18n("Commit all changes"))
394
446
        self._files_box.pack_start(self._commit_all_files_radio, False, True, 0)
395
447
        self._commit_all_files_radio.show()
396
448
        self._commit_all_files_radio.connect('toggled',
397
449
            self._toggle_commit_selection)
398
 
        self._commit_selected_radio = Gtk.RadioButton(
 
450
        self._commit_selected_radio = Gtk.RadioButton.new_with_label_from_widget(
399
451
            self._commit_all_files_radio, _i18n("Only commit selected changes"))
400
452
        self._files_box.pack_start(self._commit_selected_radio, False, True, 0)
401
453
        self._commit_selected_radio.show()
448
500
                                     self._on_treeview_files_cursor_changed)
449
501
 
450
502
    def _toggle_commit(self, cell, path, model):
451
 
        if model[path][0] is None: # No file_id means 'All Files'
 
503
        if model[path][0] == "": # No file_id means 'All Files'
452
504
            new_val = not model[path][2]
453
505
            for node in model:
454
506
                node[2] = new_val
464
516
                checked_col.set_visible(False)
465
517
            else:
466
518
                checked_col.set_visible(True)
467
 
            renderer = checked_col.get_cell_renderers()[0]
 
519
            renderer = checked_col.get_cells()[0]
468
520
            renderer.set_property('activatable', not all_files)
469
521
 
470
522
    def _construct_pending_list(self):
508
560
                                             Gtk.CellRendererText(), text=3))
509
561
 
510
562
    def _construct_diff_view(self):
511
 
        from bzrlib.plugins.gtk.diff import DiffView
512
 
 
513
563
        # TODO: jam 2007-10-30 The diff label is currently disabled. If we
514
564
        #       decide that we really don't ever want to display it, we should
515
565
        #       actually remove it, and other references to it, along with the
524
574
        self._add_to_right_table(self._diff_view, 4, True)
525
575
        self._diff_view.show()
526
576
 
 
577
    @staticmethod
 
578
    def get_line_height(widget):
 
579
        pango_layout = widget.create_pango_layout("X");
 
580
        ink_rectangle, logical_rectangle = pango_layout.get_pixel_extents()
 
581
        return logical_rectangle.height
 
582
 
527
583
    def _construct_file_message(self):
528
584
        scroller = Gtk.ScrolledWindow()
529
585
        scroller.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
536
592
        self._file_message_text_view.modify_font(Pango.FontDescription("Monospace"))
537
593
        self._file_message_text_view.set_wrap_mode(Gtk.WrapMode.WORD)
538
594
        self._file_message_text_view.set_accepts_tab(False)
 
595
        line_height = self.get_line_height(self._file_message_text_view)
 
596
        self._file_message_text_view.set_size_request(-1, line_height * 2)
539
597
        self._file_message_text_view.show()
540
598
 
541
599
        self._file_message_expander = Gtk.Expander(
571
629
 
572
630
    def _on_treeview_files_cursor_changed(self, treeview):
573
631
        treeselection = treeview.get_selection()
 
632
        if treeselection is None:
 
633
            # The treeview was probably destroyed as the dialog closes.
 
634
            return
574
635
        (model, selection) = treeselection.get_selected()
575
636
 
576
637
        if selection is not None:
577
638
            path, display_path = model.get(selection, 1, 3)
578
639
            self._diff_label.set_text(_i18n('Diff for ') + display_path)
579
 
            if path is None:
 
640
            if path == "":
580
641
                self._diff_view.show_diff(None)
581
642
            else:
582
 
                self._diff_view.show_diff([path.decode('UTF-8')])
 
643
                self._diff_view.show_diff([osutils.safe_unicode(path)])
583
644
            self._update_per_file_info(selection)
584
645
 
585
646
    def _on_accel_next(self, accel_group, window, keyval, modifier):
596
657
            # We have either made it to the end of the list, or nothing was
597
658
            # selected. Either way, select All Files, and jump to the global
598
659
            # commit message.
599
 
            self._treeview_files.set_cursor((0,))
 
660
            self._treeview_files.set_cursor(
 
661
                Gtk.TreePath(path=0), "", False)
600
662
            self._global_message_text_view.grab_focus()
601
663
        else:
602
664
            # Set the cursor to this entry, and jump to the per-file commit
603
665
            # message
604
 
            self._treeview_files.set_cursor(model.get_path(next))
 
666
            self._treeview_files.set_cursor(model.get_path(next), None, False)
605
667
            self._file_message_text_view.grab_focus()
606
668
 
607
669
    def _save_current_file_message(self):
621
683
        self._save_current_file_message()
622
684
        text_buffer = self._file_message_text_view.get_buffer()
623
685
        file_id, display_path, message = self._files_store.get(selection, 0, 3, 5)
624
 
        if file_id is None: # Whole tree
 
686
        if file_id == "": # Whole tree
625
687
            self._file_message_expander.set_label(_i18n('File commit message'))
626
688
            self._file_message_expander.set_expanded(False)
627
689
            self._file_message_expander.set_sensitive(False)
644
706
        files = []
645
707
        records = iter(self._files_store)
646
708
        rec = records.next() # Skip the All Files record
647
 
        assert rec[0] is None, "Are we skipping the wrong record?"
 
709
        assert rec[0] == "", "Are we skipping the wrong record?"
648
710
 
649
711
        file_info = []
650
712
        for record in records:
651
713
            if self._commit_all_changes or record[2]:# [2] checkbox
652
 
                file_id = record[0] # [0] file_id
653
 
                path = record[1]    # [1] real path
 
714
                file_id = osutils.safe_utf8(record[0]) # [0] file_id
 
715
                path = osutils.safe_utf8(record[1])    # [1] real path
654
716
                # [5] commit message
655
717
                file_message = _sanitize_and_decode_message(record[5])
656
718
                files.append(path.decode('UTF-8'))
792
854
        rev_dict['revision_id'] = rev.revision_id
793
855
        return rev_dict
794
856
 
795
 
 
796
 
class SavedCommitMessagesManager:
797
 
    """Save glogal and per-file commit messages.
798
 
 
799
 
    Saves global commit message and utf-8 file_id->message dictionary
800
 
    of per-file commit messages on disk. Re-reads them later for re-using.
801
 
    """
802
 
 
803
 
    def __init__(self, tree=None, branch=None):
804
 
        """If branch is None, builds empty messages, otherwise reads them
805
 
        from branch's disk storage. 'tree' argument is for the future."""
806
 
        if branch is None:
807
 
            self.global_message = u''
808
 
            self.file_messages = {}
809
 
        else:
810
 
            config = branch.get_config()
811
 
            self.global_message = config.get_user_option(
812
 
                'gtk_global_commit_message')
813
 
            if self.global_message is None:
814
 
                self.global_message = u''
815
 
            file_messages = config.get_user_option('gtk_file_commit_messages')
816
 
            if file_messages: # unicode and B-encoded:
817
 
                self.file_messages = bencode.bdecode(
818
 
                    file_messages.encode('UTF-8'))
819
 
            else:
820
 
                self.file_messages = {}
821
 
 
822
 
    def get(self):
823
 
        return self.global_message, self.file_messages
824
 
 
825
 
    def is_not_empty(self):
826
 
        return bool(self.global_message or self.file_messages)
827
 
 
828
 
    def insert(self, global_message, file_info):
829
 
        """Formats per-file commit messages (list of dictionaries, one per file)
830
 
        into one utf-8 file_id->message dictionary and merges this with
831
 
        previously existing dictionary. Merges global commit message too."""
832
 
        file_messages = {}
833
 
        for fi in file_info:
834
 
            file_message = fi['message']
835
 
            if file_message:
836
 
                file_messages[fi['file_id']] = file_message # utf-8 strings
837
 
        for k,v in file_messages.iteritems():
838
 
            try:
839
 
                self.file_messages[k] = v + '\n******\n' + self.file_messages[k]
840
 
            except KeyError:
841
 
                self.file_messages[k] = v
842
 
        if self.global_message:
843
 
            self.global_message = global_message + '\n******\n' \
844
 
                + self.global_message
845
 
        else:
846
 
            self.global_message = global_message
847
 
 
848
 
    def save(self, tree, branch):
849
 
        # We store in branch's config, which can be a problem if two gcommit
850
 
        # are done in two checkouts of one single branch (comments overwrite
851
 
        # each other). Ideally should be in working tree. But uncommit does
852
 
        # not always have a working tree, though it always has a branch.
853
 
        # 'tree' argument is for the future
854
 
        config = branch.get_config()
855
 
        # should it be named "gtk_" or some more neutral name ("gui_" ?) to
856
 
        # be compatible with qbzr in the future?
857
 
        config.set_user_option('gtk_global_commit_message', self.global_message)
858
 
        # bencode() does not know unicode objects but set_user_option()
859
 
        # requires one:
860
 
        config.set_user_option(
861
 
            'gtk_file_commit_messages',
862
 
            bencode.bencode(self.file_messages).decode('UTF-8'))
863
 
 
864
 
 
865
 
def save_commit_messages(local, master, old_revno, old_revid,
866
 
                         new_revno, new_revid):
867
 
    b = local
868
 
    if b is None:
869
 
        b = master
870
 
    mgr = SavedCommitMessagesManager(None, b)
871
 
    revid_iterator = b.repository.iter_reverse_revision_history(old_revid)
872
 
    cur_revno = old_revno
873
 
    new_revision_id = old_revid
874
 
    graph = b.repository.get_graph()
875
 
    for rev_id in revid_iterator:
876
 
        if cur_revno == new_revno:
877
 
            break
878
 
        cur_revno -= 1
879
 
        rev = b.repository.get_revision(rev_id)
880
 
        file_info = rev.properties.get('file-info', None)
881
 
        if file_info is None:
882
 
            file_info = {}
883
 
        else:
884
 
            file_info = bencode.bdecode(file_info.encode('UTF-8'))
885
 
        global_message = osutils.safe_unicode(rev.message)
886
 
        # Concatenate comment of the uncommitted revision
887
 
        mgr.insert(global_message, file_info)
888
 
 
889
 
        parents = graph.get_parent_map([rev_id]).get(rev_id, None)
890
 
        if not parents:
891
 
            continue
892
 
    mgr.save(None, b)