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

  • Committer: Robert Collins
  • Date: 2010-05-06 23:41:35 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506234135-yivbzczw1sejxnxc
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
expected to return an object which can be used to unlock them. This reduces
duplicate code when using cleanups. The previous 'tokens's returned by
``Branch.lock_write`` and ``Repository.lock_write`` are now attributes
on the result of the lock_write. ``repository.RepositoryWriteLockResult``
and ``branch.BranchWriteLockResult`` document this. (Robert Collins)

``log._get_info_for_log_files`` now takes an add_cleanup callable.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
# TODO: For things like --diff-prefix, we want a way to customize the display
18
18
# of the option argument.
19
19
 
20
 
from __future__ import absolute_import
21
 
 
22
20
import optparse
23
21
import re
24
22
 
25
 
from . import (
 
23
from bzrlib.lazy_import import lazy_import
 
24
lazy_import(globals(), """
 
25
from bzrlib import (
26
26
    errors,
 
27
    revisionspec,
 
28
    )
 
29
""")
 
30
 
 
31
from bzrlib import (
27
32
    registry as _mod_registry,
28
 
    revisionspec,
29
 
    )
30
 
from .sixish import (
31
 
    text_type,
32
 
    )
33
 
 
34
 
 
35
 
class BadOptionValue(errors.BzrError):
36
 
 
37
 
    _fmt = """Bad value "%(value)s" for option "%(name)s"."""
38
 
 
39
 
    def __init__(self, name, value):
40
 
        errors.BzrError.__init__(self, name=name, value=value)
 
33
    )
41
34
 
42
35
 
43
36
def _parse_revision_str(revstr):
123
116
def _parse_merge_type(typestring):
124
117
    return get_merge_type(typestring)
125
118
 
126
 
 
127
119
def get_merge_type(typestring):
128
120
    """Attempt to find the merge class/factory associated with a string."""
129
121
    from merge import merge_types
130
122
    try:
131
123
        return merge_types[typestring][0]
132
124
    except KeyError:
133
 
        templ = '%s%%7s: %%s' % (' ' * 12)
134
 
        lines = [templ % (f[0], f[1][1]) for f in merge_types.items()]
 
125
        templ = '%s%%7s: %%s' % (' '*12)
 
126
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
135
127
        type_list = '\n'.join(lines)
136
128
        msg = "No known merge type %s. Supported types are:\n%s" %\
137
129
            (typestring, type_list)
246
238
            self.custom_callback(option, self._param_name, bool_v, parser)
247
239
 
248
240
    def _optparse_callback(self, option, opt, value, parser):
249
 
        try:
250
 
            v = self.type(value)
251
 
        except ValueError as e:
252
 
            raise optparse.OptionValueError(
253
 
                'invalid value for option %s: %s' % (option, value))
 
241
        v = self.type(value)
254
242
        setattr(parser.values, self._param_name, v)
255
243
        if self.custom_callback is not None:
256
244
            self.custom_callback(option, self.name, v, parser)
260
248
 
261
249
        :return: an iterator of (name, short_name, argname, help)
262
250
        """
263
 
        argname = self.argname
 
251
        argname =  self.argname
264
252
        if argname is not None:
265
253
            argname = argname.upper()
266
254
        yield self.name, self.short_name(), argname, self.help
312
300
    def validate_value(self, value):
313
301
        """Validate a value name"""
314
302
        if value not in self.registry:
315
 
            raise BadOptionValue(self.name, value)
 
303
            raise errors.BadOptionValue(self.name, value)
316
304
 
317
305
    def convert(self, value):
318
306
        """Convert a value name into an output type"""
323
311
            return self.converter(value)
324
312
 
325
313
    def __init__(self, name, help, registry=None, converter=None,
326
 
                 value_switches=False, title=None, enum_switch=True,
327
 
                 lazy_registry=None, short_name=None, short_value_switches=None):
 
314
        value_switches=False, title=None, enum_switch=True,
 
315
        lazy_registry=None):
328
316
        """
329
317
        Constructor.
330
318
 
340
328
            which takes a value.
341
329
        :param lazy_registry: A tuple of (module name, attribute name) for a
342
330
            registry to be lazily loaded.
343
 
        :param short_name: The short name for the enum switch, if any
344
 
        :param short_value_switches: A dict mapping values to short names
345
331
        """
346
 
        Option.__init__(self, name, help, type=self.convert,
347
 
                        short_name=short_name)
 
332
        Option.__init__(self, name, help, type=self.convert)
348
333
        self._registry = registry
349
334
        if registry is None:
350
335
            if lazy_registry is None:
359
344
        self.converter = converter
360
345
        self.value_switches = value_switches
361
346
        self.enum_switch = enum_switch
362
 
        self.short_value_switches = short_value_switches
363
347
        self.title = title
364
348
        if self.title is None:
365
349
            self.title = name
388
372
                if not help.endswith("."):
389
373
                    help = help + "."
390
374
        return RegistryOption(name_, help, reg, title=title,
391
 
                              value_switches=value_switches, enum_switch=enum_switch)
 
375
            value_switches=value_switches, enum_switch=enum_switch)
392
376
 
393
377
    def add_option(self, parser, short_name):
394
378
        """Add this option to an Optparse parser"""
397
381
        if self.enum_switch:
398
382
            Option.add_option(self, parser, short_name)
399
383
        if self.value_switches:
400
 
            alias_map = self.registry.alias_map()
401
384
            for key in self.registry.keys():
402
 
                if key in self.registry.aliases():
403
 
                    continue
404
 
                option_strings = [
405
 
                    ('--%s' % name)
406
 
                    for name in [key] +
407
 
                    [alias for alias in alias_map.get(key, [])
408
 
                        if not self.is_hidden(alias)]]
 
385
                option_strings = ['--%s' % key]
409
386
                if self.is_hidden(key):
410
387
                    help = optparse.SUPPRESS_HELP
411
388
                else:
412
389
                    help = self.registry.get_help(key)
413
 
                if (self.short_value_switches and
414
 
                        key in self.short_value_switches):
415
 
                    option_strings.append('-%s' %
416
 
                                          self.short_value_switches[key])
417
390
                parser.add_option(action='callback',
418
 
                                  callback=self._optparse_value_callback(key),
 
391
                              callback=self._optparse_value_callback(key),
419
392
                                  help=help,
420
393
                                  *option_strings)
421
394
 
438
411
            for key in sorted(self.registry.keys()):
439
412
                yield key, None, None, self.registry.get_help(key)
440
413
 
441
 
    def is_alias(self, name):
442
 
        """Check whether a particular format is an alias."""
443
 
        if name == self.name:
444
 
            return False
445
 
        return name in self.registry.aliases()
446
 
 
447
414
    def is_hidden(self, name):
448
415
        if name == self.name:
449
416
            return Option.is_hidden(self, name)
455
422
 
456
423
    DEFAULT_VALUE = object()
457
424
 
458
 
    def __init__(self):
459
 
        optparse.OptionParser.__init__(self)
460
 
        self.formatter = GettextIndentedHelpFormatter()
461
 
 
462
425
    def error(self, message):
463
426
        raise errors.BzrCommandError(message)
464
427
 
465
428
 
466
 
class GettextIndentedHelpFormatter(optparse.IndentedHelpFormatter):
467
 
    """Adds gettext() call to format_option()"""
468
 
 
469
 
    def __init__(self):
470
 
        optparse.IndentedHelpFormatter.__init__(self)
471
 
 
472
 
    def format_option(self, option):
473
 
        """code taken from Python's optparse.py"""
474
 
        if option.help:
475
 
            from .i18n import gettext
476
 
            option.help = gettext(option.help)
477
 
        return optparse.IndentedHelpFormatter.format_option(self, option)
478
 
 
479
 
 
480
429
def get_optparser(options):
481
 
    """Generate an optparse parser for breezy-style options"""
 
430
    """Generate an optparse parser for bzrlib-style options"""
482
431
 
483
432
    parser = OptionParser()
484
433
    parser.remove_option('--help')
485
 
    for option in options:
 
434
    for option in options.itervalues():
486
435
        option.add_option(parser, option.short_name())
487
436
    return parser
488
437
 
502
451
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
503
452
 
504
453
 
505
 
def _standard_list_option(name, **kwargs):
506
 
    """Register a standard option."""
507
 
    # All standard options are implicitly 'global' ones
508
 
    Option.STD_OPTIONS[name] = ListOption(name, **kwargs)
509
 
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
510
 
 
511
 
 
512
454
def _global_option(name, **kwargs):
513
455
    """Register a global option."""
514
456
    Option.OPTIONS[name] = Option(name, **kwargs)
546
488
            _verbosity_level = -1
547
489
 
548
490
 
 
491
class MergeTypeRegistry(_mod_registry.Registry):
 
492
 
 
493
    pass
 
494
 
 
495
 
 
496
_merge_type_registry = MergeTypeRegistry()
 
497
_merge_type_registry.register_lazy('merge3', 'bzrlib.merge', 'Merge3Merger',
 
498
                                   "Native diff3-style merge")
 
499
_merge_type_registry.register_lazy('diff3', 'bzrlib.merge', 'Diff3Merger',
 
500
                                   "Merge using external diff3")
 
501
_merge_type_registry.register_lazy('weave', 'bzrlib.merge', 'WeaveMerger',
 
502
                                   "Weave-based merge")
 
503
_merge_type_registry.register_lazy('lca', 'bzrlib.merge', 'LCAMerger',
 
504
                                   "LCA-newness merge")
 
505
 
549
506
# Declare the standard options
550
507
_standard_option('help', short_name='h',
551
508
                 help='Show help message.')
552
 
_standard_option('quiet', short_name='q',
553
 
                 help="Only display errors and warnings.",
554
 
                 custom_callback=_verbosity_level_callback)
555
509
_standard_option('usage',
556
510
                 help='Show usage message and options.')
557
511
_standard_option('verbose', short_name='v',
558
512
                 help='Display more information.',
559
513
                 custom_callback=_verbosity_level_callback)
 
514
_standard_option('quiet', short_name='q',
 
515
                 help="Only display errors and warnings.",
 
516
                 custom_callback=_verbosity_level_callback)
560
517
 
561
518
# Declare commonly used options
562
 
_global_option('change',
563
 
               type=_parse_change_str,
564
 
               short_name='c',
565
 
               param_name='revision',
566
 
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
567
 
_global_option('directory', short_name='d', type=text_type,
568
 
               help='Branch to operate on, instead of working directory.')
569
 
_global_option('file', type=text_type, short_name='F')
570
 
_global_registry_option('log-format', "Use specified log format.",
571
 
                        lazy_registry=('breezy.log', 'log_formatter_registry'),
572
 
                        value_switches=True, title='Log format',
573
 
                        short_value_switches={'short': 'S'})
574
 
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
575
 
                        lazy_registry=('breezy.merge', 'merge_type_registry'),
576
 
                        value_switches=True, title='Merge algorithm')
577
 
_global_option('message', type=text_type,
 
519
_global_option('all')
 
520
_global_option('overwrite', help='Ignore differences between branches and '
 
521
               'overwrite unconditionally.')
 
522
_global_option('basis', type=str)
 
523
_global_option('bound')
 
524
_global_option('diff-options', type=str)
 
525
_global_option('file', type=unicode, short_name='F')
 
526
_global_option('force')
 
527
_global_option('format', type=unicode)
 
528
_global_option('forward')
 
529
_global_option('message', type=unicode,
578
530
               short_name='m',
579
531
               help='Message string.')
580
 
_global_option('null', short_name='0',
581
 
               help='Use an ASCII NUL (\\0) separator rather than '
582
 
               'a newline.')
583
 
_global_option('overwrite', help='Ignore differences between branches and '
584
 
               'overwrite unconditionally.')
585
 
_global_option('remember', help='Remember the specified location as a'
586
 
               ' default.')
587
 
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
 
532
_global_option('no-recurse')
 
533
_global_option('profile',
 
534
               help='Show performance profiling information.')
588
535
_global_option('revision',
589
536
               type=_parse_revision_str,
590
537
               short_name='r',
591
538
               help='See "help revisionspec" for details.')
 
539
_global_option('change',
 
540
               type=_parse_change_str,
 
541
               short_name='c',
 
542
               param_name='revision',
 
543
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
592
544
_global_option('show-ids',
593
545
               help='Show internal object ids.')
594
546
_global_option('timezone',
595
547
               type=str,
596
548
               help='Display timezone as local, original, or utc.')
 
549
_global_option('unbound')
 
550
_global_option('version')
 
551
_global_option('email')
 
552
_global_option('update')
 
553
_global_registry_option('log-format', "Use specified log format.",
 
554
                        lazy_registry=('bzrlib.log', 'log_formatter_registry'),
 
555
                        value_switches=True, title='Log format')
 
556
_global_option('long', help='Use detailed log format. Same as --log-format long',
 
557
               short_name='l')
 
558
_global_option('short', help='Use moderately short log format. Same as --log-format short')
 
559
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
 
560
_global_option('root', type=str)
 
561
_global_option('no-backup')
 
562
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
 
563
                        _merge_type_registry, value_switches=True,
 
564
                        title='Merge algorithm')
 
565
_global_option('pattern', type=str)
 
566
_global_option('remember', help='Remember the specified location as a'
 
567
               ' default.')
 
568
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
 
569
_global_option('kind', type=str)
 
570
_global_option('dry-run',
 
571
               help="Show what would be done, but don't actually do anything.")
 
572
_global_option('name-from-revision', help='The path name in the old tree.')
597
573
 
598
574
diff_writer_registry = _mod_registry.Registry()
599
575
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')