/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 __init__.py

  • Committer: Jelmer Vernooij
  • Date: 2007-02-01 15:50:40 UTC
  • Revision ID: jelmer@samba.org-20070201155040-3hq4mfbxs99kzazy
add framework for tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
# along with this program; if not, write to the Free Software
13
13
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14
14
 
15
 
"""Graphical support for Bazaar using GTK.
16
 
 
17
 
This plugin includes:
18
 
gannotate         GTK+ annotate.
19
 
gbranch           GTK+ branching.
20
 
gcheckout         GTK+ checkout.
21
 
gcommit           GTK+ commit dialog.
22
 
gconflicts        GTK+ conflicts.
23
 
gdiff             Show differences in working tree in a GTK+ Window.
24
 
ginit             Initialise a new branch.
25
 
gloom             GTK+ loom browse dialog
26
 
gmerge            GTK+ merge dialog
27
 
gmissing          GTK+ missing revisions dialog.
28
 
gpreferences      GTK+ preferences dialog.
29
 
gpush             GTK+ push.
30
 
gsend             GTK+ send merge directive.
31
 
gstatus           GTK+ status dialog.
32
 
gtags             Manage branch tags.
33
 
visualise         Graphically visualise this branch.
34
 
"""
35
 
 
36
 
from __future__ import absolute_import
37
 
 
38
 
import os
39
 
import sys
40
 
 
41
 
if getattr(sys, "frozen", None) is not None: # we run bzr.exe
42
 
 
43
 
    # FIXME: Unless a better packaging solution is found, the following
44
 
    # provides a workaround for https://bugs.launchpad.net/bzr/+bug/388790 Also
45
 
    # see https://code.edge.launchpad.net/~vila/bzr-gtk/388790-windows-setup
46
 
    # for more details about while it's needed.
47
 
 
48
 
    # NOTE: _lib must be ahead of bzrlib or sax.saxutils (in olive) fails
49
 
    here = os.path.dirname(__file__)
50
 
    sys.path.insert(0, os.path.join(here, '_lib'))
51
 
    sys.path.append(os.path.join(here, '_lib/gtk-2.0'))
52
 
 
 
15
"""GTK+ frontends to Bazaar commands """
53
16
 
54
17
import bzrlib
55
 
import bzrlib.api
56
 
from bzrlib import (
57
 
    config,
58
 
    )
59
 
from bzrlib.commands import plugin_cmds
60
 
 
61
 
from bzrlib.plugins.gtk.info import (
62
 
    bzr_plugin_version as version_info,
63
 
    bzr_compatible_versions,
64
 
    )
65
 
 
66
 
if version_info[3] == 'final':
67
 
    version_string = '%d.%d.%d' % version_info[:3]
68
 
else:
69
 
    version_string = '%d.%d.%d%s%d' % version_info
70
 
__version__ = version_string
71
 
 
72
 
bzrlib.api.require_any_api(bzrlib, bzr_compatible_versions)
73
 
 
74
 
if __name__ != 'bzrlib.plugins.gtk':
75
 
    from bzrlib.trace import warning
76
 
    warning("Not running as bzrlib.plugins.gtk, things may break.")
 
18
 
 
19
__version__ = '0.15.0'
 
20
version_info = tuple(int(n) for n in __version__.split('.'))
 
21
 
 
22
 
 
23
def check_bzrlib_version(desired):
 
24
    """Check that bzrlib is compatible.
 
25
 
 
26
    If version is < bzr-gtk version, assume incompatible.
 
27
    If version == bzr-gtk version, assume completely compatible
 
28
    If version == bzr-gtk version + 1, assume compatible, with deprecations
 
29
    Otherwise, assume incompatible.
 
30
    """
 
31
    desired_plus = (desired[0], desired[1]+1)
 
32
    bzrlib_version = bzrlib.version_info[:2]
 
33
    if bzrlib_version == desired:
 
34
        return
 
35
    try:
 
36
        from bzrlib.trace import warning
 
37
    except ImportError:
 
38
        # get the message out any way we can
 
39
        from warnings import warn as warning
 
40
    if bzrlib_version < desired:
 
41
        warning('Installed bzr version %s is too old to be used with bzr-gtk'
 
42
                ' %s.' % (bzrlib.__version__, __version__))
 
43
        # Not using BzrNewError, because it may not exist.
 
44
        raise Exception, ('Version mismatch', version_info)
 
45
    else:
 
46
        warning('bzr-gtk is not up to date with installed bzr version %s.'
 
47
                ' \nThere should be a newer version available, e.g. %i.%i.' 
 
48
                % (bzrlib.__version__, bzrlib_version[0], bzrlib_version[1]))
 
49
        if bzrlib_version != desired_plus:
 
50
            raise Exception, 'Version mismatch'
 
51
 
 
52
 
 
53
check_bzrlib_version(version_info[:2])
 
54
 
 
55
from bzrlib import errors
 
56
from bzrlib.commands import Command, register_command, display_command
 
57
from bzrlib.errors import NotVersionedError, BzrCommandError, NoSuchFile
 
58
from bzrlib.commands import Command, register_command
 
59
from bzrlib.option import Option
 
60
from bzrlib.branch import Branch
 
61
from bzrlib.workingtree import WorkingTree
 
62
from bzrlib.bzrdir import BzrDir
 
63
 
 
64
import os.path
 
65
 
 
66
def import_pygtk():
 
67
    try:
 
68
        import pygtk
 
69
    except ImportError:
 
70
        raise errors.BzrCommandError("PyGTK not installed.")
 
71
    pygtk.require('2.0')
 
72
    return pygtk
77
73
 
78
74
 
79
75
def set_ui_factory():
80
 
    from bzrlib.plugins.gtk.ui import GtkUIFactory
 
76
    pygtk = import_pygtk()
 
77
    from olive.ui import GtkUIFactory
81
78
    import bzrlib.ui
82
79
    bzrlib.ui.ui_factory = GtkUIFactory()
83
80
 
84
81
 
85
 
def data_basedirs():
86
 
    return [os.path.dirname(__file__),
87
 
             "/usr/share/bzr-gtk", 
88
 
             "/usr/local/share/bzr-gtk"]
89
 
 
90
 
 
91
 
def data_path(*args):
92
 
    for basedir in data_basedirs():
93
 
        path = os.path.join(basedir, *args)
94
 
        if os.path.exists(path):
95
 
            return path
96
 
    return None
97
 
 
98
 
 
99
 
def icon_path(*args):
100
 
    return data_path(os.path.join('icons', *args))
101
 
 
102
 
 
103
 
commands = {
104
 
    "gannotate": ["gblame", "gpraise"],
105
 
    "gbranch": [],
106
 
    "gcheckout": [],
107
 
    "gcommit": ["gci"],
108
 
    "gconflicts": [],
109
 
    "gdiff": [],
110
 
    "ginit": [],
111
 
    "gmerge": [],
112
 
    "gmissing": [],
113
 
    "gpreferences": [],
114
 
    "gpush": [],
115
 
    "gsend": [],
116
 
    "gstatus": ["gst"],
117
 
    "gtags": [],
118
 
    "visualise": ["visualize", "vis", "viz", 'glog'],
119
 
    }
120
 
 
121
 
try:
122
 
    from bzrlib.plugins import loom
123
 
except ImportError:
124
 
    pass # Loom plugin doesn't appear to be present
125
 
else:
126
 
    commands["gloom"] = []
127
 
 
128
 
for cmd, aliases in commands.iteritems():
129
 
    plugin_cmds.register_lazy("cmd_%s" % cmd, aliases,
130
 
                              "bzrlib.plugins.gtk.commands")
131
 
 
132
 
def save_commit_messages(*args):
133
 
    from bzrlib.plugins.gtk import commitmsgs
134
 
    commitmsgs.save_commit_messages(*args)
135
 
 
136
 
try:
137
 
    from bzrlib.hooks import install_lazy_named_hook
138
 
except ImportError:
139
 
    from bzrlib.branch import Branch
140
 
    Branch.hooks.install_named_hook('post_uncommit',
141
 
                                    save_commit_messages,
142
 
                                    "Saving commit messages for gcommit")
143
 
else:
144
 
    install_lazy_named_hook("bzrlib.branch", "Branch.hooks",
145
 
        'post_uncommit', save_commit_messages, "Saving commit messages for gcommit")
146
 
 
147
 
 
148
 
option_registry = getattr(config, "option_registry", None)
149
 
if option_registry is not None:
150
 
    config.option_registry.register_lazy('nautilus_integration',
151
 
            'bzrlib.plugins.gtk.config', 'opt_nautilus_integration')
152
 
 
153
 
def load_tests(basic_tests, module, loader):
154
 
    testmod_names = [
155
 
        'tests',
156
 
        ]
157
 
    import sys
158
 
    default_encoding = sys.getdefaultencoding()
159
 
    try:
160
 
        result = basic_tests
161
 
        try:
162
 
            import gi.repository.Gtk
163
 
        except ImportError:
164
 
            return basic_tests
165
 
        basic_tests.addTest(loader.loadTestsFromModuleNames(
166
 
                ["%s.%s" % (__name__, tmn) for tmn in testmod_names]))
167
 
    finally:
168
 
        if sys.getdefaultencoding() != default_encoding:
169
 
            reload(sys)
170
 
            sys.setdefaultencoding(default_encoding)
171
 
    return basic_tests
 
82
class cmd_gbranch(Command):
 
83
    """GTK+ branching.
 
84
    
 
85
    """
 
86
 
 
87
    def run(self):
 
88
        pygtk = import_pygtk()
 
89
        try:
 
90
            import gtk
 
91
        except RuntimeError, e:
 
92
            if str(e) == "could not open display":
 
93
                raise NoDisplayError
 
94
 
 
95
        from bzrlib.plugins.gtk.olive.branch import BranchDialog
 
96
 
 
97
        set_ui_factory()
 
98
        dialog = BranchDialog(os.path.abspath('.'))
 
99
        dialog.window.connect("destroy", lambda w: gtk.main_quit())
 
100
        dialog.display()
 
101
        
 
102
        gtk.main()
 
103
 
 
104
register_command(cmd_gbranch)
 
105
 
 
106
class cmd_gdiff(Command):
 
107
    """Show differences in working tree in a GTK+ Window.
 
108
    
 
109
    Otherwise, all changes for the tree are listed.
 
110
    """
 
111
    takes_args = ['filename?']
 
112
    takes_options = ['revision']
 
113
 
 
114
    @display_command
 
115
    def run(self, revision=None, filename=None):
 
116
        set_ui_factory()
 
117
        wt = WorkingTree.open_containing(".")[0]
 
118
        branch = wt.branch
 
119
        if revision is not None:
 
120
            if len(revision) == 1:
 
121
                tree1 = wt
 
122
                revision_id = revision[0].in_history(branch).rev_id
 
123
                tree2 = branch.repository.revision_tree(revision_id)
 
124
            elif len(revision) == 2:
 
125
                revision_id_0 = revision[0].in_history(branch).rev_id
 
126
                tree2 = branch.repository.revision_tree(revision_id_0)
 
127
                revision_id_1 = revision[1].in_history(branch).rev_id
 
128
                tree1 = branch.repository.revision_tree(revision_id_1)
 
129
        else:
 
130
            tree1 = wt
 
131
            tree2 = tree1.basis_tree()
 
132
 
 
133
        from viz.diffwin import DiffWindow
 
134
        import gtk
 
135
        window = DiffWindow()
 
136
        window.connect("destroy", lambda w: gtk.main_quit())
 
137
        window.set_diff("Working Tree", tree1, tree2)
 
138
        if filename is not None:
 
139
            tree_filename = wt.relpath(filename)
 
140
            try:
 
141
                window.set_file(tree_filename)
 
142
            except NoSuchFile:
 
143
                if (tree1.inventory.path2id(tree_filename) is None and 
 
144
                    tree2.inventory.path2id(tree_filename) is None):
 
145
                    raise NotVersionedError(filename)
 
146
                raise BzrCommandError('No changes found for file "%s"' % 
 
147
                                      filename)
 
148
        window.show()
 
149
 
 
150
        gtk.main()
 
151
 
 
152
register_command(cmd_gdiff)
 
153
 
 
154
class cmd_visualise(Command):
 
155
    """Graphically visualise this branch.
 
156
 
 
157
    Opens a graphical window to allow you to see the history of the branch
 
158
    and relationships between revisions in a visual manner,
 
159
 
 
160
    The default starting point is latest revision on the branch, you can
 
161
    specify a starting point with -r revision.
 
162
    """
 
163
    takes_options = [
 
164
        "revision",
 
165
        Option('limit', "maximum number of revisions to display",
 
166
               int, 'count')]
 
167
    takes_args = [ "location?" ]
 
168
    aliases = [ "visualize", "vis", "viz" ]
 
169
 
 
170
    def run(self, location=".", revision=None, limit=None):
 
171
        set_ui_factory()
 
172
        (branch, path) = Branch.open_containing(location)
 
173
        branch.lock_read()
 
174
        branch.repository.lock_read()
 
175
        try:
 
176
            if revision is None:
 
177
                revid = branch.last_revision()
 
178
                if revid is None:
 
179
                    return
 
180
            else:
 
181
                (revno, revid) = revision[0].in_history(branch)
 
182
 
 
183
            from viz.bzrkapp import BzrkApp
 
184
                
 
185
            app = BzrkApp()
 
186
            app.show(branch, revid, limit)
 
187
        finally:
 
188
            branch.repository.unlock()
 
189
            branch.unlock()
 
190
        app.main()
 
191
 
 
192
 
 
193
register_command(cmd_visualise)
 
194
 
 
195
class cmd_gannotate(Command):
 
196
    """GTK+ annotate.
 
197
    
 
198
    Browse changes to FILENAME line by line in a GTK+ window.
 
199
    """
 
200
 
 
201
    takes_args = ["filename", "line?"]
 
202
    takes_options = [
 
203
        Option("all", help="show annotations on all lines"),
 
204
        Option("plain", help="don't highlight annotation lines"),
 
205
        Option("line", type=int, argname="lineno",
 
206
               help="jump to specified line number"),
 
207
        "revision",
 
208
    ]
 
209
    aliases = ["gblame", "gpraise"]
 
210
    
 
211
    def run(self, filename, all=False, plain=False, line='1', revision=None):
 
212
        pygtk = import_pygtk()
 
213
 
 
214
        try:
 
215
            import gtk
 
216
        except RuntimeError, e:
 
217
            if str(e) == "could not open display":
 
218
                raise NoDisplayError
 
219
        set_ui_factory()
 
220
 
 
221
        try:
 
222
            line = int(line)
 
223
        except ValueError:
 
224
            raise BzrCommandError('Line argument ("%s") is not a number.' % 
 
225
                                  line)
 
226
 
 
227
        from annotate.gannotate import GAnnotateWindow
 
228
        from annotate.config import GAnnotateConfig
 
229
 
 
230
        try:
 
231
            (tree, path) = WorkingTree.open_containing(filename)
 
232
            branch = tree.branch
 
233
        except errors.NoWorkingTree:
 
234
            (branch, path) = Branch.open_containing(filename)
 
235
            tree = branch.basis_tree()
 
236
 
 
237
        file_id = tree.path2id(path)
 
238
 
 
239
        if file_id is None:
 
240
            raise NotVersionedError(filename)
 
241
        if revision is not None:
 
242
            if len(revision) != 1:
 
243
                raise BzrCommandError("Only 1 revion may be specified.")
 
244
            revision_id = revision[0].in_history(branch).rev_id
 
245
            tree = branch.repository.revision_tree(revision_id)
 
246
        else:
 
247
            revision_id = getattr(tree, 'get_revision_id', lambda: None)()
 
248
 
 
249
        window = GAnnotateWindow(all, plain)
 
250
        window.connect("destroy", lambda w: gtk.main_quit())
 
251
        window.set_title(path + " - gannotate")
 
252
        config = GAnnotateConfig(window)
 
253
        window.show()
 
254
        branch.lock_read()
 
255
        try:
 
256
            window.annotate(tree, branch, file_id)
 
257
        finally:
 
258
            branch.unlock()
 
259
        window.jump_to_line(line)
 
260
        
 
261
        gtk.main()
 
262
 
 
263
register_command(cmd_gannotate)
 
264
 
 
265
class cmd_gcommit(Command):
 
266
    """GTK+ commit dialog
 
267
 
 
268
    Graphical user interface for committing revisions"""
 
269
    
 
270
    takes_args = []
 
271
    takes_options = []
 
272
 
 
273
    def run(self, filename=None):
 
274
        import os
 
275
        pygtk = import_pygtk()
 
276
 
 
277
        try:
 
278
            import gtk
 
279
        except RuntimeError, e:
 
280
            if str(e) == "could not open display":
 
281
                raise NoDisplayError
 
282
 
 
283
        set_ui_factory()
 
284
        from olive.commit import CommitDialog
 
285
        from bzrlib.commit import Commit
 
286
        from bzrlib.errors import (BzrCommandError,
 
287
                                   NotBranchError,
 
288
                                   NoWorkingTree,
 
289
                                   PointlessCommit,
 
290
                                   ConflictsInTree,
 
291
                                   StrictCommitFailed)
 
292
 
 
293
        wt = None
 
294
        branch = None
 
295
        try:
 
296
            (wt, path) = WorkingTree.open_containing(filename)
 
297
            branch = wt.branch
 
298
        except NotBranchError, e:
 
299
            path = e.path
 
300
        except NoWorkingTree, e:
 
301
            path = e.base
 
302
            try:
 
303
                (branch, path) = Branch.open_containing(path)
 
304
            except NotBranchError, e:
 
305
                path = e.path
 
306
 
 
307
 
 
308
        commit = CommitDialog(wt, path, not branch)
 
309
        commit.run()
 
310
 
 
311
register_command(cmd_gcommit)
 
312
 
 
313
class NoDisplayError(BzrCommandError):
 
314
    """gtk could not find a proper display"""
 
315
 
 
316
    def __str__(self):
 
317
        return "No DISPLAY. Unable to run GTK+ application."
 
318
 
 
319
def test_suite():
 
320
    from unittest import TestSuite
 
321
    import tests
 
322
    result = TestSuite()
 
323
    result.addTest(tests.test_suite())
 
324
    return result
172
325