/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: John Arbash Meinel
  • Date: 2006-09-20 14:51:03 UTC
  • mfrom: (0.8.23 version_info)
  • mto: This revision was merged to the branch mainline in revision 2028.
  • Revision ID: john@arbash-meinel.com-20060920145103-02725c6d6c886040
[merge] version-info plugin, and cleanup for layout in bzr

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2006 by Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
28
28
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
29
29
# the profile output behind so it can be interactively examined?
30
30
 
31
 
import os
32
 
import sys
33
 
 
34
 
from bzrlib.lazy_import import lazy_import
35
 
lazy_import(globals(), """
36
31
import codecs
37
32
import errno
 
33
import os
38
34
from warnings import warn
 
35
import sys
39
36
 
40
37
import bzrlib
41
 
from bzrlib import (
42
 
    debug,
43
 
    errors,
44
 
    option,
45
 
    osutils,
46
 
    trace,
47
 
    )
48
 
""")
49
 
 
50
 
from bzrlib.symbol_versioning import (
51
 
    deprecated_function,
52
 
    deprecated_method,
53
 
    zero_eight,
54
 
    zero_eleven,
55
 
    )
56
 
# Compatibility
 
38
import bzrlib.errors as errors
 
39
from bzrlib.errors import (BzrError,
 
40
                           BzrCommandError,
 
41
                           BzrCheckError,
 
42
                           NotBranchError)
 
43
from bzrlib import option
57
44
from bzrlib.option import Option
58
 
 
 
45
import bzrlib.osutils
 
46
from bzrlib.symbol_versioning import (deprecated_method, zero_eight)
 
47
import bzrlib.trace
 
48
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
59
49
 
60
50
plugin_cmds = {}
61
51
 
76
66
        k_unsquished = k
77
67
    if k_unsquished not in plugin_cmds:
78
68
        plugin_cmds[k_unsquished] = cmd
79
 
        ## trace.mutter('registered plugin command %s', k_unsquished)
 
69
        mutter('registered plugin command %s', k_unsquished)
80
70
        if decorate and k_unsquished in builtin_command_names():
81
71
            return _builtin_commands()[k_unsquished]
82
72
    elif decorate:
84
74
        plugin_cmds[k_unsquished] = cmd
85
75
        return result
86
76
    else:
87
 
        trace.log_error('Two plugins defined the same command: %r' % k)
88
 
        trace.log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
77
        log_error('Two plugins defined the same command: %r' % k)
 
78
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
89
79
 
90
80
 
91
81
def _squish_command_name(cmd):
160
150
    if cmd_obj:
161
151
        return cmd_obj
162
152
 
163
 
    raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
 
153
    raise BzrCommandError('unknown command "%s"' % cmd_name)
164
154
 
165
155
 
166
156
class Command(object):
214
204
            replace - put in a bogus character (typically '?')
215
205
            exact - do not encode sys.stdout
216
206
 
217
 
            NOTE: by default on Windows, sys.stdout is opened as a text
218
 
            stream, therefore LF line-endings are converted to CRLF.
219
 
            When a command uses encoding_type = 'exact', then
220
 
            sys.stdout is forced to be a binary stream, and line-endings
221
 
            will not mangled.
222
 
 
223
207
    """
224
208
    aliases = []
225
209
    takes_args = []
238
222
 
239
223
        Maps from long option name to option object."""
240
224
        r = dict()
241
 
        r['help'] = option.Option.OPTIONS['help']
 
225
        r['help'] = Option.OPTIONS['help']
242
226
        for o in self.takes_options:
243
227
            if isinstance(o, basestring):
244
 
                o = option.Option.OPTIONS[o]
 
228
                o = Option.OPTIONS[o]
245
229
            r[o.name] = o
246
230
        return r
247
231
 
252
236
        # Originally I was using self.stdout, but that looks
253
237
        # *way* too much like sys.stdout
254
238
        if self.encoding_type == 'exact':
255
 
            # force sys.stdout to be binary stream on win32
256
 
            if sys.platform == 'win32':
257
 
                fileno = getattr(sys.stdout, 'fileno', None)
258
 
                if fileno:
259
 
                    import msvcrt
260
 
                    msvcrt.setmode(fileno(), os.O_BINARY)
261
239
            self.outf = sys.stdout
262
240
            return
263
241
 
264
 
        output_encoding = osutils.get_terminal_encoding()
 
242
        output_encoding = bzrlib.osutils.get_terminal_encoding()
265
243
 
266
244
        # use 'replace' so that we don't abort if trying to write out
267
245
        # in e.g. the default C locale.
271
249
        # bogus. So set the attribute, so we can find the correct encoding later.
272
250
        self.outf.encoding = output_encoding
273
251
 
 
252
    @deprecated_method(zero_eight)
 
253
    def run_argv(self, argv):
 
254
        """Parse command line and run.
 
255
        
 
256
        See run_argv_aliases for the 0.8 and beyond api.
 
257
        """
 
258
        return self.run_argv_aliases(argv)
 
259
 
274
260
    def run_argv_aliases(self, argv, alias_argv=None):
275
261
        """Parse the command line and run with extra aliases in alias_argv."""
276
262
        if argv is None:
277
 
            warn("Passing None for [] is deprecated from bzrlib 0.10",
 
263
            warn("Passing None for [] is deprecated from bzrlib 0.10", 
278
264
                 DeprecationWarning, stacklevel=2)
279
265
            argv = []
280
266
        args, opts = parse_args(self, argv, alias_argv)
305
291
        shell error code if not.  It's OK for this method to allow
306
292
        an exception to raise up.
307
293
        """
308
 
        raise NotImplementedError('no implementation of command %r'
 
294
        raise NotImplementedError('no implementation of command %r' 
309
295
                                  % self.name())
310
296
 
311
297
    def help(self):
330
316
            return None
331
317
 
332
318
 
333
 
# Technically, this function hasn't been use in a *really* long time
334
 
# but we are only deprecating it now.
335
 
@deprecated_function(zero_eleven)
336
319
def parse_spec(spec):
337
320
    """
338
321
    >>> parse_spec(None)
380
363
        args = argv
381
364
 
382
365
    options, args = parser.parse_args(args)
383
 
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
 
366
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if 
384
367
                 v is not option.OptionParser.DEFAULT_VALUE])
385
368
    return args, opts
386
369
 
402
385
                argdict[argname + '_list'] = None
403
386
        elif ap[-1] == '+':
404
387
            if not args:
405
 
                raise errors.BzrCommandError("command %r needs one or more %s"
406
 
                                             % (cmd, argname.upper()))
 
388
                raise BzrCommandError("command %r needs one or more %s"
 
389
                        % (cmd, argname.upper()))
407
390
            else:
408
391
                argdict[argname + '_list'] = args[:]
409
392
                args = []
410
393
        elif ap[-1] == '$': # all but one
411
394
            if len(args) < 2:
412
 
                raise errors.BzrCommandError("command %r needs one or more %s"
413
 
                                             % (cmd, argname.upper()))
 
395
                raise BzrCommandError("command %r needs one or more %s"
 
396
                        % (cmd, argname.upper()))
414
397
            argdict[argname + '_list'] = args[:-1]
415
398
            args[:-1] = []
416
399
        else:
417
400
            # just a plain arg
418
401
            argname = ap
419
402
            if not args:
420
 
                raise errors.BzrCommandError("command %r requires argument %s"
421
 
                               % (cmd, argname.upper()))
 
403
                raise BzrCommandError("command %r requires argument %s"
 
404
                        % (cmd, argname.upper()))
422
405
            else:
423
406
                argdict[argname] = args.pop(0)
424
407
            
425
408
    if args:
426
 
        raise errors.BzrCommandError("extra argument to command %s: %s"
427
 
                                     % (cmd, args[0]))
 
409
        raise BzrCommandError("extra argument to command %s: %s"
 
410
                              % (cmd, args[0]))
428
411
 
429
412
    return argdict
430
413
 
467
450
    return ret
468
451
 
469
452
 
470
 
def get_alias(cmd, config=None):
471
 
    """Return an expanded alias, or None if no alias exists.
472
 
 
473
 
    cmd
474
 
        Command to be checked for an alias.
475
 
    config
476
 
        Used to specify an alternative config to use,
477
 
        which is especially useful for testing.
478
 
        If it is unspecified, the global config will be used.
479
 
    """
480
 
    if config is None:
481
 
        import bzrlib.config
482
 
        config = bzrlib.config.GlobalConfig()
483
 
    alias = config.get_alias(cmd)
 
453
def get_alias(cmd):
 
454
    """Return an expanded alias, or None if no alias exists"""
 
455
    import bzrlib.config
 
456
    alias = bzrlib.config.GlobalConfig().get_alias(cmd)
484
457
    if (alias):
485
 
        import shlex
486
 
        return [a.decode('utf-8') for a in shlex.split(alias.encode('utf-8'))]
 
458
        return alias.split(' ')
487
459
    return None
488
460
 
489
461
 
520
492
        Run under the Python lsprof profiler.
521
493
    """
522
494
    argv = list(argv)
523
 
    trace.mutter("bzr arguments: %r", argv)
524
495
 
525
496
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
526
497
                opt_no_aliases = False
549
520
        elif a == '--builtin':
550
521
            opt_builtin = True
551
522
        elif a in ('--quiet', '-q'):
552
 
            trace.be_quiet()
553
 
        elif a.startswith('-D'):
554
 
            debug.debug_flags.add(a[2:])
 
523
            be_quiet()
555
524
        else:
556
525
            argv_copy.append(a)
557
526
        i += 1
588
557
    # 'command not found' error later.
589
558
 
590
559
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
591
 
    run = cmd_obj.run_argv_aliases
592
 
    run_argv = [argv, alias_argv]
 
560
    if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
 
561
        run = cmd_obj.run_argv
 
562
        run_argv = [argv]
 
563
    else:
 
564
        run = cmd_obj.run_argv_aliases
 
565
        run_argv = [argv, alias_argv]
593
566
 
594
567
    try:
595
568
        if opt_lsprof:
601
574
        return ret or 0
602
575
    finally:
603
576
        # reset, in case we may do other commands later within the same process
604
 
        trace.be_quiet(False)
 
577
        be_quiet(False)
605
578
 
606
579
def display_command(func):
607
580
    """Decorator that suppresses pipe/interrupt errors."""
615
588
                raise
616
589
            if e.errno != errno.EPIPE:
617
590
                # Win32 raises IOError with errno=0 on a broken pipe
618
 
                if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
 
591
                if sys.platform != 'win32' or e.errno != 0:
619
592
                    raise
620
593
            pass
621
594
        except KeyboardInterrupt:
629
602
    bzrlib.ui.ui_factory = TextUIFactory()
630
603
    argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
631
604
    ret = run_bzr_catch_errors(argv)
632
 
    trace.mutter("return code %d", ret)
 
605
    mutter("return code %d", ret)
633
606
    return ret
634
607
 
635
608
 
638
611
        return run_bzr(argv)
639
612
        # do this here inside the exception wrappers to catch EPIPE
640
613
        sys.stdout.flush()
641
 
    except (KeyboardInterrupt, Exception), e:
 
614
    except Exception, e:
642
615
        # used to handle AssertionError and KeyboardInterrupt
643
616
        # specially here, but hopefully they're handled ok by the logger now
644
 
        trace.report_exception(sys.exc_info(), sys.stderr)
 
617
        bzrlib.trace.report_exception(sys.exc_info(), sys.stderr)
645
618
        if os.environ.get('BZR_PDB'):
646
619
            print '**** entering debugger'
647
620
            import pdb