/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: 2008-08-04 18:51:44 UTC
  • Revision ID: jelmer@samba.org-20080804185144-c1v0efzz63zhf790
Remove check for glade.

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
"""Graphical support for Bazaar using GTK.
16
16
 
17
17
This plugin includes:
18
 
gannotate         GTK+ annotate.
19
 
gbranch           GTK+ branching.
20
 
gcheckout         GTK+ checkout.
 
18
gannotate         GTK+ annotate. 
 
19
gbranch           GTK+ branching. 
 
20
gcheckout         GTK+ checkout. 
21
21
gcommit           GTK+ commit dialog.
22
 
gconflicts        GTK+ conflicts.
23
 
gdiff             Show differences in working tree in a GTK+ Window.
 
22
gconflicts        GTK+ conflicts. 
 
23
gdiff             Show differences in working tree in a GTK+ Window. 
24
24
ginit             Initialise a new branch.
25
25
gloom             GTK+ loom browse dialog
26
26
gmerge            GTK+ merge dialog
27
 
gmissing          GTK+ missing revisions dialog.
28
 
gpreferences      GTK+ preferences dialog.
 
27
gmissing          GTK+ missing revisions dialog. 
 
28
gpreferences      GTK+ preferences dialog. 
29
29
gpush             GTK+ push.
30
30
gsend             GTK+ send merge directive.
31
31
gstatus           GTK+ status dialog.
32
32
gtags             Manage branch tags.
33
 
visualise         Graphically visualise this branch.
 
33
visualise         Graphically visualise this branch. 
34
34
"""
35
35
 
36
 
from __future__ import absolute_import
37
 
 
38
 
import os
39
36
import sys
40
37
 
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
 
 
53
 
 
54
38
import bzrlib
55
 
import bzrlib.api
56
 
from bzrlib.commands import plugin_cmds
57
39
 
58
 
from bzrlib.plugins.gtk.info import (
59
 
    bzr_plugin_version as version_info,
60
 
    bzr_compatible_versions,
61
 
    )
 
40
version_info = (0, 96, 0, 'dev', 1)
62
41
 
63
42
if version_info[3] == 'final':
64
43
    version_string = '%d.%d.%d' % version_info[:3]
66
45
    version_string = '%d.%d.%d%s%d' % version_info
67
46
__version__ = version_string
68
47
 
69
 
bzrlib.api.require_any_api(bzrlib, bzr_compatible_versions)
70
 
 
 
48
required_bzrlib = (1, 6)
 
49
 
 
50
def check_bzrlib_version(desired):
 
51
    """Check that bzrlib is compatible.
 
52
 
 
53
    If version is < bzr-gtk version, assume incompatible.
 
54
    """
 
55
    bzrlib_version = bzrlib.version_info[:2]
 
56
    try:
 
57
        from bzrlib.trace import warning
 
58
    except ImportError:
 
59
        # get the message out any way we can
 
60
        from warnings import warn as warning
 
61
    if bzrlib_version < desired:
 
62
        from bzrlib.errors import BzrError
 
63
        warning('Installed Bazaar version %s is too old to be used with bzr-gtk'
 
64
                ' %s.' % (bzrlib.__version__, __version__))
 
65
        raise BzrError('Version mismatch: %r, %r' % (version_info, bzrlib.version_info) )
 
66
 
 
67
 
 
68
if version_info[2] == "final":
 
69
    check_bzrlib_version(required_bzrlib)
 
70
 
 
71
from bzrlib.trace import warning
71
72
if __name__ != 'bzrlib.plugins.gtk':
72
 
    from bzrlib.trace import warning
73
73
    warning("Not running as bzrlib.plugins.gtk, things may break.")
74
74
 
 
75
from bzrlib.lazy_import import lazy_import
 
76
lazy_import(globals(), """
 
77
from bzrlib import (
 
78
    branch,
 
79
    builtins,
 
80
    errors,
 
81
    merge_directive,
 
82
    workingtree,
 
83
    )
 
84
""")
 
85
 
 
86
from bzrlib.commands import Command, register_command, display_command
 
87
from bzrlib.errors import NotVersionedError, BzrCommandError, NoSuchFile
 
88
from bzrlib.option import Option
 
89
 
 
90
import os.path
 
91
 
 
92
def import_pygtk():
 
93
    try:
 
94
        import pygtk
 
95
    except ImportError:
 
96
        raise errors.BzrCommandError("PyGTK not installed.")
 
97
    pygtk.require('2.0')
 
98
    return pygtk
 
99
 
75
100
 
76
101
def set_ui_factory():
77
 
    from bzrlib.plugins.gtk.ui import GtkUIFactory
 
102
    import_pygtk()
 
103
    from ui import GtkUIFactory
78
104
    import bzrlib.ui
79
105
    bzrlib.ui.ui_factory = GtkUIFactory()
80
106
 
97
123
    return data_path(os.path.join('icons', *args))
98
124
 
99
125
 
100
 
commands = {
101
 
    "gannotate": ["gblame", "gpraise"],
102
 
    "gbranch": [],
103
 
    "gcheckout": [],
104
 
    "gcommit": ["gci"],
105
 
    "gconflicts": [],
106
 
    "gdiff": [],
107
 
    "ginit": [],
108
 
    "gmerge": [],
109
 
    "gmissing": [],
110
 
    "gpreferences": [],
111
 
    "gpush": [],
112
 
    "gsend": [],
113
 
    "gstatus": ["gst"],
114
 
    "gtags": [],
115
 
    "visualise": ["visualize", "vis", "viz", 'glog'],
116
 
    }
 
126
def open_display():
 
127
    pygtk = import_pygtk()
 
128
    try:
 
129
        import gtk
 
130
    except RuntimeError, e:
 
131
        if str(e) == "could not open display":
 
132
            raise NoDisplayError
 
133
    set_ui_factory()
 
134
    return gtk
 
135
 
 
136
 
 
137
class GTKCommand(Command):
 
138
    """Abstract class providing GTK specific run commands."""
 
139
 
 
140
    def run(self):
 
141
        open_display()
 
142
        dialog = self.get_gtk_dialog(os.path.abspath('.'))
 
143
        dialog.run()
 
144
 
 
145
 
 
146
class cmd_gbranch(GTKCommand):
 
147
    """GTK+ branching.
 
148
    
 
149
    """
 
150
 
 
151
    def get_gtk_dialog(self, path):
 
152
        from bzrlib.plugins.gtk.branch import BranchDialog
 
153
        return BranchDialog(path)
 
154
 
 
155
 
 
156
class cmd_gcheckout(GTKCommand):
 
157
    """ GTK+ checkout.
 
158
    
 
159
    """
 
160
    
 
161
    def get_gtk_dialog(self, path):
 
162
        from bzrlib.plugins.gtk.checkout import CheckoutDialog
 
163
        return CheckoutDialog(path)
 
164
 
 
165
 
 
166
 
 
167
class cmd_gpush(GTKCommand):
 
168
    """ GTK+ push.
 
169
    
 
170
    """
 
171
    takes_args = [ "location?" ]
 
172
 
 
173
    def run(self, location="."):
 
174
        (br, path) = branch.Branch.open_containing(location)
 
175
        open_display()
 
176
        from bzrlib.plugins.gtk.push import PushDialog
 
177
        dialog = PushDialog(br.repository, br.last_revision(), br)
 
178
        dialog.run()
 
179
 
 
180
 
 
181
class cmd_gloom(GTKCommand):
 
182
    """ GTK+ loom.
 
183
    
 
184
    """
 
185
    takes_args = [ "location?" ]
 
186
 
 
187
    def run(self, location="."):
 
188
        try:
 
189
            (tree, path) = workingtree.WorkingTree.open_containing(location)
 
190
            br = tree.branch
 
191
        except NoWorkingTree, e:
 
192
            (br, path) = branch.Branch.open_containing(location)
 
193
            tree = None
 
194
        open_display()
 
195
        from bzrlib.plugins.gtk.loom import LoomDialog
 
196
        dialog = LoomDialog(br, tree)
 
197
        dialog.run()
 
198
 
 
199
 
 
200
class cmd_gdiff(GTKCommand):
 
201
    """Show differences in working tree in a GTK+ Window.
 
202
    
 
203
    Otherwise, all changes for the tree are listed.
 
204
    """
 
205
    takes_args = ['filename?']
 
206
    takes_options = ['revision']
 
207
 
 
208
    @display_command
 
209
    def run(self, revision=None, filename=None):
 
210
        set_ui_factory()
 
211
        wt = workingtree.WorkingTree.open_containing(".")[0]
 
212
        wt.lock_read()
 
213
        try:
 
214
            branch = wt.branch
 
215
            if revision is not None:
 
216
                if len(revision) == 1:
 
217
                    tree1 = wt
 
218
                    revision_id = revision[0].as_revision_id(tree1.branch)
 
219
                    tree2 = branch.repository.revision_tree(revision_id)
 
220
                elif len(revision) == 2:
 
221
                    revision_id_0 = revision[0].as_revision_id(branch)
 
222
                    tree2 = branch.repository.revision_tree(revision_id_0)
 
223
                    revision_id_1 = revision[1].as_revision_id(branch)
 
224
                    tree1 = branch.repository.revision_tree(revision_id_1)
 
225
            else:
 
226
                tree1 = wt
 
227
                tree2 = tree1.basis_tree()
 
228
 
 
229
            from diff import DiffWindow
 
230
            import gtk
 
231
            window = DiffWindow()
 
232
            window.connect("destroy", gtk.main_quit)
 
233
            window.set_diff("Working Tree", tree1, tree2)
 
234
            if filename is not None:
 
235
                tree_filename = wt.relpath(filename)
 
236
                try:
 
237
                    window.set_file(tree_filename)
 
238
                except NoSuchFile:
 
239
                    if (tree1.path2id(tree_filename) is None and 
 
240
                        tree2.path2id(tree_filename) is None):
 
241
                        raise NotVersionedError(filename)
 
242
                    raise BzrCommandError('No changes found for file "%s"' % 
 
243
                                          filename)
 
244
            window.show()
 
245
 
 
246
            gtk.main()
 
247
        finally:
 
248
            wt.unlock()
 
249
 
 
250
 
 
251
def start_viz_window(branch, revisions, limit=None):
 
252
    """Start viz on branch with revision revision.
 
253
    
 
254
    :return: The viz window object.
 
255
    """
 
256
    from bzrlib.plugins.gtk.viz import BranchWindow
 
257
    return BranchWindow(branch, revisions, limit)
 
258
 
 
259
 
 
260
class cmd_visualise(Command):
 
261
    """Graphically visualise this branch.
 
262
 
 
263
    Opens a graphical window to allow you to see the history of the branch
 
264
    and relationships between revisions in a visual manner,
 
265
 
 
266
    The default starting point is latest revision on the branch, you can
 
267
    specify a starting point with -r revision.
 
268
    """
 
269
    takes_options = [
 
270
        "revision",
 
271
        Option('limit', "Maximum number of revisions to display.",
 
272
               int, 'count')]
 
273
    takes_args = [ "locations*" ]
 
274
    aliases = [ "visualize", "vis", "viz" ]
 
275
 
 
276
    def run(self, locations_list, revision=None, limit=None):
 
277
        set_ui_factory()
 
278
        if locations_list is None:
 
279
            locations_list = ["."]
 
280
        revids = []
 
281
        for location in locations_list:
 
282
            (br, path) = branch.Branch.open_containing(location)
 
283
            if revision is None:
 
284
                revids.append(br.last_revision())
 
285
            else:
 
286
                revids.append(revision[0].as_revision_id(br))
 
287
        import gtk
 
288
        pp = start_viz_window(br, revids, limit)
 
289
        pp.connect("destroy", lambda w: gtk.main_quit())
 
290
        pp.show()
 
291
        gtk.main()
 
292
 
 
293
 
 
294
class cmd_gannotate(GTKCommand):
 
295
    """GTK+ annotate.
 
296
    
 
297
    Browse changes to FILENAME line by line in a GTK+ window.
 
298
    """
 
299
 
 
300
    takes_args = ["filename", "line?"]
 
301
    takes_options = [
 
302
        Option("all", help="Show annotations on all lines."),
 
303
        Option("plain", help="Don't highlight annotation lines."),
 
304
        Option("line", type=int, argname="lineno",
 
305
               help="Jump to specified line number."),
 
306
        "revision",
 
307
    ]
 
308
    aliases = ["gblame", "gpraise"]
 
309
    
 
310
    def run(self, filename, all=False, plain=False, line='1', revision=None):
 
311
        gtk = open_display()
 
312
 
 
313
        try:
 
314
            line = int(line)
 
315
        except ValueError:
 
316
            raise BzrCommandError('Line argument ("%s") is not a number.' % 
 
317
                                  line)
 
318
 
 
319
        from annotate.gannotate import GAnnotateWindow
 
320
        from annotate.config import GAnnotateConfig
 
321
        from bzrlib.bzrdir import BzrDir
 
322
 
 
323
        wt, br, path = BzrDir.open_containing_tree_or_branch(filename)
 
324
        if wt is not None:
 
325
            tree = wt
 
326
        else:
 
327
            tree = br.basis_tree()
 
328
 
 
329
        file_id = tree.path2id(path)
 
330
 
 
331
        if file_id is None:
 
332
            raise NotVersionedError(filename)
 
333
        if revision is not None:
 
334
            if len(revision) != 1:
 
335
                raise BzrCommandError("Only 1 revion may be specified.")
 
336
            revision_id = revision[0].as_revision_id(br)
 
337
            tree = br.repository.revision_tree(revision_id)
 
338
        else:
 
339
            revision_id = getattr(tree, 'get_revision_id', lambda: None)()
 
340
 
 
341
        window = GAnnotateWindow(all, plain, branch=br)
 
342
        window.connect("destroy", lambda w: gtk.main_quit())
 
343
        config = GAnnotateConfig(window)
 
344
        window.show()
 
345
        br.lock_read()
 
346
        if wt is not None:
 
347
            wt.lock_read()
 
348
        try:
 
349
            window.annotate(tree, br, file_id)
 
350
            window.jump_to_line(line)
 
351
            gtk.main()
 
352
        finally:
 
353
            br.unlock()
 
354
            if wt is not None:
 
355
                wt.unlock()
 
356
 
 
357
 
 
358
 
 
359
class cmd_gcommit(GTKCommand):
 
360
    """GTK+ commit dialog
 
361
 
 
362
    Graphical user interface for committing revisions"""
 
363
 
 
364
    aliases = [ "gci" ]
 
365
    takes_args = []
 
366
    takes_options = []
 
367
 
 
368
    def run(self, filename=None):
 
369
        import os
 
370
        open_display()
 
371
        from commit import CommitDialog
 
372
        from bzrlib.errors import (BzrCommandError,
 
373
                                   NotBranchError,
 
374
                                   NoWorkingTree)
 
375
 
 
376
        wt = None
 
377
        br = None
 
378
        try:
 
379
            (wt, path) = workingtree.WorkingTree.open_containing(filename)
 
380
            br = wt.branch
 
381
        except NoWorkingTree, e:
 
382
            from dialog import error_dialog
 
383
            error_dialog(_i18n('Directory does not have a working tree'),
 
384
                         _i18n('Operation aborted.'))
 
385
            return 1 # should this be retval=3?
 
386
 
 
387
        # It is a good habit to keep things locked for the duration, but it
 
388
        # could cause difficulties if someone wants to do things in another
 
389
        # window... We could lock_read() until we actually go to commit
 
390
        # changes... Just a thought.
 
391
        wt.lock_write()
 
392
        try:
 
393
            dlg = CommitDialog(wt)
 
394
            return dlg.run()
 
395
        finally:
 
396
            wt.unlock()
 
397
 
 
398
 
 
399
class cmd_gstatus(GTKCommand):
 
400
    """GTK+ status dialog
 
401
 
 
402
    Graphical user interface for showing status 
 
403
    information."""
 
404
    
 
405
    aliases = [ "gst" ]
 
406
    takes_args = ['PATH?']
 
407
    takes_options = ['revision']
 
408
 
 
409
    def run(self, path='.', revision=None):
 
410
        import os
 
411
        gtk = open_display()
 
412
        from status import StatusDialog
 
413
        (wt, wt_path) = workingtree.WorkingTree.open_containing(path)
 
414
        
 
415
        if revision is not None:
 
416
            try:
 
417
                revision_id = revision[0].as_revision_id(wt.branch)
 
418
            except:
 
419
                from bzrlib.errors import BzrError
 
420
                raise BzrError('Revision %r doesn\'t exist' % revision[0].user_spec )
 
421
        else:
 
422
            revision_id = None
 
423
 
 
424
        status = StatusDialog(wt, wt_path, revision_id)
 
425
        status.connect("destroy", gtk.main_quit)
 
426
        status.run()
 
427
 
 
428
 
 
429
class cmd_gsend(GTKCommand):
 
430
    """GTK+ send merge directive.
 
431
 
 
432
    """
 
433
    def run(self):
 
434
        (br, path) = branch.Branch.open_containing(".")
 
435
        gtk = open_display()
 
436
        from bzrlib.plugins.gtk.mergedirective import SendMergeDirectiveDialog
 
437
        from StringIO import StringIO
 
438
        dialog = SendMergeDirectiveDialog(br)
 
439
        if dialog.run() == gtk.RESPONSE_OK:
 
440
            outf = StringIO()
 
441
            outf.writelines(dialog.get_merge_directive().to_lines())
 
442
            mail_client = br.get_config().get_mail_client()
 
443
            mail_client.compose_merge_request(dialog.get_mail_to(), "[MERGE]", 
 
444
                outf.getvalue())
 
445
 
 
446
            
 
447
 
 
448
 
 
449
class cmd_gconflicts(GTKCommand):
 
450
    """GTK+ conflicts.
 
451
    
 
452
    Select files from the list of conflicts and run an external utility to
 
453
    resolve them.
 
454
    """
 
455
    def run(self):
 
456
        (wt, path) = workingtree.WorkingTree.open_containing('.')
 
457
        open_display()
 
458
        from bzrlib.plugins.gtk.conflicts import ConflictsDialog
 
459
        dialog = ConflictsDialog(wt)
 
460
        dialog.run()
 
461
 
 
462
 
 
463
class cmd_gpreferences(GTKCommand):
 
464
    """ GTK+ preferences dialog.
 
465
 
 
466
    """
 
467
    def run(self):
 
468
        open_display()
 
469
        from bzrlib.plugins.gtk.preferences import PreferencesWindow
 
470
        dialog = PreferencesWindow()
 
471
        dialog.run()
 
472
 
 
473
 
 
474
class cmd_gmerge(Command):
 
475
    """ GTK+ merge dialog
 
476
    
 
477
    """
 
478
    takes_args = ["merge_from_path?"]
 
479
    def run(self, merge_from_path=None):
 
480
        from bzrlib import workingtree
 
481
        from bzrlib.plugins.gtk.dialog import error_dialog
 
482
        from bzrlib.plugins.gtk.merge import MergeDialog
 
483
        
 
484
        (wt, path) = workingtree.WorkingTree.open_containing('.')
 
485
        old_tree = wt.branch.repository.revision_tree(wt.branch.last_revision())
 
486
        delta = wt.changes_from(old_tree)
 
487
        if len(delta.added) or len(delta.removed) or len(delta.renamed) or len(delta.modified):
 
488
            error_dialog(_i18n('There are local changes in the branch'),
 
489
                         _i18n('Please commit or revert the changes before merging.'))
 
490
        else:
 
491
            parent_branch_path = wt.branch.get_parent()
 
492
            merge = MergeDialog(wt, path, parent_branch_path)
 
493
            response = merge.run()
 
494
            merge.destroy()
 
495
 
 
496
 
 
497
class cmd_gmissing(Command):
 
498
    """ GTK+ missing revisions dialog.
 
499
 
 
500
    """
 
501
    takes_args = ["other_branch?"]
 
502
    def run(self, other_branch=None):
 
503
        pygtk = import_pygtk()
 
504
        try:
 
505
            import gtk
 
506
        except RuntimeError, e:
 
507
            if str(e) == "could not open display":
 
508
                raise NoDisplayError
 
509
 
 
510
        from bzrlib.plugins.gtk.missing import MissingWindow
 
511
        from bzrlib.branch import Branch
 
512
 
 
513
        local_branch = Branch.open_containing(".")[0]
 
514
        if other_branch is None:
 
515
            other_branch = local_branch.get_parent()
 
516
            
 
517
            if other_branch is None:
 
518
                raise errors.BzrCommandError("No peer location known or specified.")
 
519
        remote_branch = Branch.open_containing(other_branch)[0]
 
520
        set_ui_factory()
 
521
        local_branch.lock_read()
 
522
        try:
 
523
            remote_branch.lock_read()
 
524
            try:
 
525
                dialog = MissingWindow(local_branch, remote_branch)
 
526
                dialog.run()
 
527
            finally:
 
528
                remote_branch.unlock()
 
529
        finally:
 
530
            local_branch.unlock()
 
531
 
 
532
 
 
533
class cmd_ginit(GTKCommand):
 
534
    def run(self):
 
535
        open_display()
 
536
        from initialize import InitDialog
 
537
        dialog = InitDialog(os.path.abspath(os.path.curdir))
 
538
        dialog.run()
 
539
 
 
540
 
 
541
class cmd_gtags(GTKCommand):
 
542
    def run(self):
 
543
        br = branch.Branch.open_containing('.')[0]
 
544
        
 
545
        gtk = open_display()
 
546
        from tags import TagsWindow
 
547
        window = TagsWindow(br)
 
548
        window.show()
 
549
        gtk.main()
 
550
 
 
551
 
 
552
commands = [
 
553
    cmd_gannotate, 
 
554
    cmd_gbranch,
 
555
    cmd_gcheckout, 
 
556
    cmd_gcommit, 
 
557
    cmd_gconflicts, 
 
558
    cmd_gdiff,
 
559
    cmd_ginit,
 
560
    cmd_gmerge,
 
561
    cmd_gmissing, 
 
562
    cmd_gpreferences, 
 
563
    cmd_gpush, 
 
564
    cmd_gsend,
 
565
    cmd_gstatus,
 
566
    cmd_gtags,
 
567
    cmd_visualise
 
568
    ]
117
569
 
118
570
try:
119
571
    from bzrlib.plugins import loom
120
572
except ImportError:
121
573
    pass # Loom plugin doesn't appear to be present
122
574
else:
123
 
    commands["gloom"] = []
124
 
 
125
 
for cmd, aliases in commands.iteritems():
126
 
    plugin_cmds.register_lazy("cmd_%s" % cmd, aliases,
127
 
                              "bzrlib.plugins.gtk.commands")
128
 
 
129
 
def save_commit_messages(*args):
130
 
    from bzrlib.plugins.gtk import commitmsgs
131
 
    commitmsgs.save_commit_messages(*args)
132
 
 
133
 
try:
134
 
    from bzrlib.hooks import install_lazy_named_hook
135
 
except ImportError:
136
 
    from bzrlib.branch import Branch
137
 
    Branch.hooks.install_named_hook('post_uncommit',
138
 
                                    save_commit_messages,
139
 
                                    "Saving commit messages for gcommit")
140
 
else:
141
 
    install_lazy_named_hook("bzrlib.branch", "Branch.hooks",
142
 
        'post_uncommit', save_commit_messages, "Saving commit messages for gcommit")
143
 
 
144
 
try:
145
 
    from bzrlib.registry import register_lazy
146
 
except ImportError:
147
 
    from bzrlib import config
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
 
else:
153
 
    register_lazy("bzrlib.config", "option_registry",
154
 
        'nautilus_integration', 'bzrlib.plugins.gtk.config',
155
 
        'opt_nautilus_integration')
156
 
 
157
 
 
158
 
def load_tests(basic_tests, module, loader):
159
 
    testmod_names = [
160
 
        'tests',
161
 
        ]
 
575
    commands.append(cmd_gloom)
 
576
 
 
577
for cmd in commands:
 
578
    register_command(cmd)
 
579
 
 
580
 
 
581
class cmd_gselftest(GTKCommand):
 
582
    """Version of selftest that displays a notification at the end"""
 
583
 
 
584
    takes_args = builtins.cmd_selftest.takes_args
 
585
    takes_options = builtins.cmd_selftest.takes_options
 
586
    _see_also = ['selftest']
 
587
 
 
588
    def run(self, *args, **kwargs):
 
589
        import cgi
 
590
        import sys
 
591
        default_encoding = sys.getdefaultencoding()
 
592
        # prevent gtk from blowing up later
 
593
        gtk = import_pygtk()
 
594
        # prevent gtk from messing with default encoding
 
595
        import pynotify
 
596
        if sys.getdefaultencoding() != default_encoding:
 
597
            reload(sys)
 
598
            sys.setdefaultencoding(default_encoding)
 
599
        result = builtins.cmd_selftest().run(*args, **kwargs)
 
600
        if result == 0:
 
601
            summary = 'Success'
 
602
            body = 'Selftest succeeded in "%s"' % os.getcwd()
 
603
        if result == 1:
 
604
            summary = 'Failure'
 
605
            body = 'Selftest failed in "%s"' % os.getcwd()
 
606
        pynotify.init("bzr gselftest")
 
607
        note = pynotify.Notification(cgi.escape(summary), cgi.escape(body))
 
608
        note.set_timeout(pynotify.EXPIRES_NEVER)
 
609
        note.show()
 
610
 
 
611
 
 
612
register_command(cmd_gselftest)
 
613
 
 
614
 
 
615
class cmd_test_gtk(GTKCommand):
 
616
    """Version of selftest that just runs the gtk test suite."""
 
617
 
 
618
    takes_options = ['verbose',
 
619
                     Option('one', short_name='1',
 
620
                            help='Stop when one test fails.'),
 
621
                     Option('benchmark', help='Run the benchmarks.'),
 
622
                     Option('lsprof-timed',
 
623
                     help='Generate lsprof output for benchmarked'
 
624
                          ' sections of code.'),
 
625
                     Option('list-only',
 
626
                     help='List the tests instead of running them.'),
 
627
                     Option('randomize', type=str, argname="SEED",
 
628
                     help='Randomize the order of tests using the given'
 
629
                          ' seed or "now" for the current time.'),
 
630
                    ]
 
631
    takes_args = ['testspecs*']
 
632
 
 
633
    def run(self, verbose=None, one=False, benchmark=None,
 
634
            lsprof_timed=None, list_only=False, randomize=None,
 
635
            testspecs_list=None):
 
636
        from bzrlib import __path__ as bzrlib_path
 
637
        from bzrlib.tests import selftest
 
638
 
 
639
        print '%10s: %s' % ('bzrlib', bzrlib_path[0])
 
640
        if benchmark:
 
641
            print 'No benchmarks yet'
 
642
            return 3
 
643
 
 
644
            test_suite_factory = bench_suite
 
645
            if verbose is None:
 
646
                verbose = True
 
647
            # TODO: should possibly lock the history file...
 
648
            benchfile = open(".perf_history", "at", buffering=1)
 
649
        else:
 
650
            test_suite_factory = test_suite
 
651
            if verbose is None:
 
652
                verbose = False
 
653
            benchfile = None
 
654
 
 
655
        if testspecs_list is not None:
 
656
            pattern = '|'.join(testspecs_list)
 
657
        else:
 
658
            pattern = ".*"
 
659
 
 
660
        try:
 
661
            result = selftest(verbose=verbose,
 
662
                              pattern=pattern,
 
663
                              stop_on_failure=one,
 
664
                              test_suite_factory=test_suite_factory,
 
665
                              lsprof_timed=lsprof_timed,
 
666
                              bench_history=benchfile,
 
667
                              list_only=list_only,
 
668
                              random_seed=randomize,
 
669
                             )
 
670
        finally:
 
671
            if benchfile is not None:
 
672
                benchfile.close()
 
673
 
 
674
register_command(cmd_test_gtk)
 
675
 
 
676
 
 
677
 
 
678
import gettext
 
679
gettext.install('olive-gtk')
 
680
 
 
681
# Let's create a specialized alias to protect '_' from being erased by other
 
682
# uses of '_' as an anonymous variable (think pdb for one).
 
683
_i18n = gettext.gettext
 
684
 
 
685
class NoDisplayError(BzrCommandError):
 
686
    """gtk could not find a proper display"""
 
687
 
 
688
    def __str__(self):
 
689
        return "No DISPLAY. Unable to run GTK+ application."
 
690
 
 
691
 
 
692
def test_suite():
 
693
    from unittest import TestSuite
 
694
    import tests
162
695
    import sys
163
696
    default_encoding = sys.getdefaultencoding()
164
697
    try:
165
 
        result = basic_tests
 
698
        result = TestSuite()
166
699
        try:
167
 
            import gi.repository.Gtk
168
 
        except ImportError:
169
 
            return basic_tests
170
 
        basic_tests.addTest(loader.loadTestsFromModuleNames(
171
 
                ["%s.%s" % (__name__, tmn) for tmn in testmod_names]))
 
700
            import_pygtk()
 
701
        except errors.BzrCommandError:
 
702
            return result
 
703
        result.addTest(tests.test_suite())
172
704
    finally:
173
705
        if sys.getdefaultencoding() != default_encoding:
174
706
            reload(sys)
175
707
            sys.setdefaultencoding(default_encoding)
176
 
    return basic_tests
177
 
 
 
708
    return result