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

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2020-08-23 01:15:41 UTC
  • mfrom: (7520.1.4 merge-3.1)
  • Revision ID: breezy.the.bot@gmail.com-20200823011541-nv0oh7nzaganx2qy
Merge lp:brz/3.1.

Merged from https://code.launchpad.net/~jelmer/brz/merge-3.1/+merge/389690

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
import optparse
21
21
import re
22
22
 
23
 
from bzrlib.lazy_import import lazy_import
24
 
lazy_import(globals(), """
25
 
from bzrlib import (
 
23
from . import (
26
24
    errors,
 
25
    registry as _mod_registry,
27
26
    revisionspec,
28
27
    )
29
 
""")
30
 
 
31
 
from bzrlib import (
32
 
    registry as _mod_registry,
33
 
    )
 
28
 
 
29
 
 
30
class BadOptionValue(errors.BzrError):
 
31
 
 
32
    _fmt = """Bad value "%(value)s" for option "%(name)s"."""
 
33
 
 
34
    def __init__(self, name, value):
 
35
        errors.BzrError.__init__(self, name=name, value=value)
34
36
 
35
37
 
36
38
def _parse_revision_str(revstr):
104
106
    >>> _parse_change_str('123..124')
105
107
    Traceback (most recent call last):
106
108
      ...
107
 
    RangeInChangeOption: Option --change does not accept revision ranges
 
109
    breezy.errors.RangeInChangeOption: Option --change does not accept revision ranges
108
110
    """
109
111
    revs = _parse_revision_str(revstr)
110
112
    if len(revs) > 1:
116
118
def _parse_merge_type(typestring):
117
119
    return get_merge_type(typestring)
118
120
 
 
121
 
119
122
def get_merge_type(typestring):
120
123
    """Attempt to find the merge class/factory associated with a string."""
121
124
    from merge import merge_types
122
125
    try:
123
126
        return merge_types[typestring][0]
124
127
    except KeyError:
125
 
        templ = '%s%%7s: %%s' % (' '*12)
126
 
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
128
        templ = '%s%%7s: %%s' % (' ' * 12)
 
129
        lines = [templ % (f[0], f[1][1]) for f in merge_types.items()]
127
130
        type_list = '\n'.join(lines)
128
131
        msg = "No known merge type %s. Supported types are:\n%s" %\
129
132
            (typestring, type_list)
130
 
        raise errors.BzrCommandError(msg)
 
133
        raise errors.CommandError(msg)
131
134
 
132
135
 
133
136
class Option(object):
238
241
            self.custom_callback(option, self._param_name, bool_v, parser)
239
242
 
240
243
    def _optparse_callback(self, option, opt, value, parser):
241
 
        v = self.type(value)
 
244
        try:
 
245
            v = self.type(value)
 
246
        except ValueError as e:
 
247
            raise optparse.OptionValueError(
 
248
                'invalid value for option %s: %s' % (option, value))
242
249
        setattr(parser.values, self._param_name, v)
243
250
        if self.custom_callback is not None:
244
251
            self.custom_callback(option, self.name, v, parser)
248
255
 
249
256
        :return: an iterator of (name, short_name, argname, help)
250
257
        """
251
 
        argname =  self.argname
 
258
        argname = self.argname
252
259
        if argname is not None:
253
260
            argname = argname.upper()
254
261
        yield self.name, self.short_name(), argname, self.help
300
307
    def validate_value(self, value):
301
308
        """Validate a value name"""
302
309
        if value not in self.registry:
303
 
            raise errors.BadOptionValue(self.name, value)
 
310
            raise BadOptionValue(self.name, value)
304
311
 
305
312
    def convert(self, value):
306
313
        """Convert a value name into an output type"""
311
318
            return self.converter(value)
312
319
 
313
320
    def __init__(self, name, help, registry=None, converter=None,
314
 
        value_switches=False, title=None, enum_switch=True,
315
 
        lazy_registry=None):
 
321
                 value_switches=False, title=None, enum_switch=True,
 
322
                 lazy_registry=None, short_name=None, short_value_switches=None):
316
323
        """
317
324
        Constructor.
318
325
 
328
335
            which takes a value.
329
336
        :param lazy_registry: A tuple of (module name, attribute name) for a
330
337
            registry to be lazily loaded.
 
338
        :param short_name: The short name for the enum switch, if any
 
339
        :param short_value_switches: A dict mapping values to short names
331
340
        """
332
 
        Option.__init__(self, name, help, type=self.convert)
 
341
        Option.__init__(self, name, help, type=self.convert,
 
342
                        short_name=short_name)
333
343
        self._registry = registry
334
344
        if registry is None:
335
345
            if lazy_registry is None:
344
354
        self.converter = converter
345
355
        self.value_switches = value_switches
346
356
        self.enum_switch = enum_switch
 
357
        self.short_value_switches = short_value_switches
347
358
        self.title = title
348
359
        if self.title is None:
349
360
            self.title = name
372
383
                if not help.endswith("."):
373
384
                    help = help + "."
374
385
        return RegistryOption(name_, help, reg, title=title,
375
 
            value_switches=value_switches, enum_switch=enum_switch)
 
386
                              value_switches=value_switches, enum_switch=enum_switch)
376
387
 
377
388
    def add_option(self, parser, short_name):
378
389
        """Add this option to an Optparse parser"""
381
392
        if self.enum_switch:
382
393
            Option.add_option(self, parser, short_name)
383
394
        if self.value_switches:
 
395
            alias_map = self.registry.alias_map()
384
396
            for key in self.registry.keys():
385
 
                option_strings = ['--%s' % key]
 
397
                if key in self.registry.aliases():
 
398
                    continue
 
399
                option_strings = [
 
400
                    ('--%s' % name)
 
401
                    for name in [key] +
 
402
                    [alias for alias in alias_map.get(key, [])
 
403
                        if not self.is_hidden(alias)]]
386
404
                if self.is_hidden(key):
387
405
                    help = optparse.SUPPRESS_HELP
388
406
                else:
389
407
                    help = self.registry.get_help(key)
 
408
                if (self.short_value_switches and
 
409
                        key in self.short_value_switches):
 
410
                    option_strings.append('-%s' %
 
411
                                          self.short_value_switches[key])
390
412
                parser.add_option(action='callback',
391
 
                              callback=self._optparse_value_callback(key),
 
413
                                  callback=self._optparse_value_callback(key),
392
414
                                  help=help,
393
415
                                  *option_strings)
394
416
 
411
433
            for key in sorted(self.registry.keys()):
412
434
                yield key, None, None, self.registry.get_help(key)
413
435
 
 
436
    def is_alias(self, name):
 
437
        """Check whether a particular format is an alias."""
 
438
        if name == self.name:
 
439
            return False
 
440
        return name in self.registry.aliases()
 
441
 
414
442
    def is_hidden(self, name):
415
443
        if name == self.name:
416
444
            return Option.is_hidden(self, name)
422
450
 
423
451
    DEFAULT_VALUE = object()
424
452
 
 
453
    def __init__(self):
 
454
        optparse.OptionParser.__init__(self)
 
455
        self.formatter = GettextIndentedHelpFormatter()
 
456
 
425
457
    def error(self, message):
426
 
        raise errors.BzrCommandError(message)
 
458
        raise errors.CommandError(message)
 
459
 
 
460
 
 
461
class GettextIndentedHelpFormatter(optparse.IndentedHelpFormatter):
 
462
    """Adds gettext() call to format_option()"""
 
463
 
 
464
    def __init__(self):
 
465
        optparse.IndentedHelpFormatter.__init__(self)
 
466
 
 
467
    def format_option(self, option):
 
468
        """code taken from Python's optparse.py"""
 
469
        if option.help:
 
470
            from .i18n import gettext
 
471
            option.help = gettext(option.help)
 
472
        return optparse.IndentedHelpFormatter.format_option(self, option)
427
473
 
428
474
 
429
475
def get_optparser(options):
430
 
    """Generate an optparse parser for bzrlib-style options"""
 
476
    """Generate an optparse parser for breezy-style options"""
431
477
 
432
478
    parser = OptionParser()
433
479
    parser.remove_option('--help')
434
 
    for option in options.itervalues():
 
480
    for option in options:
435
481
        option.add_option(parser, option.short_name())
436
482
    return parser
437
483
 
451
497
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
452
498
 
453
499
 
 
500
def _standard_list_option(name, **kwargs):
 
501
    """Register a standard option."""
 
502
    # All standard options are implicitly 'global' ones
 
503
    Option.STD_OPTIONS[name] = ListOption(name, **kwargs)
 
504
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
 
505
 
 
506
 
454
507
def _global_option(name, **kwargs):
455
508
    """Register a global option."""
456
509
    Option.OPTIONS[name] = Option(name, **kwargs)
488
541
            _verbosity_level = -1
489
542
 
490
543
 
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
 
 
506
544
# Declare the standard options
507
545
_standard_option('help', short_name='h',
508
546
                 help='Show help message.')
 
547
_standard_option('quiet', short_name='q',
 
548
                 help="Only display errors and warnings.",
 
549
                 custom_callback=_verbosity_level_callback)
509
550
_standard_option('usage',
510
551
                 help='Show usage message and options.')
511
552
_standard_option('verbose', short_name='v',
512
553
                 help='Display more information.',
513
554
                 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)
517
555
 
518
556
# Declare commonly used options
519
 
_global_option('all')
 
557
_global_option('change',
 
558
               type=_parse_change_str,
 
559
               short_name='c',
 
560
               param_name='revision',
 
561
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
 
562
_global_option('directory', short_name='d', type=str,
 
563
               help='Branch to operate on, instead of working directory.')
 
564
_global_option('file', type=str, short_name='F')
 
565
_global_registry_option('log-format', "Use specified log format.",
 
566
                        lazy_registry=('breezy.log', 'log_formatter_registry'),
 
567
                        value_switches=True, title='Log format',
 
568
                        short_value_switches={'short': 'S'})
 
569
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
 
570
                        lazy_registry=('breezy.merge', 'merge_type_registry'),
 
571
                        value_switches=True, title='Merge algorithm')
 
572
_global_option('message', type=str,
 
573
               short_name='m',
 
574
               help='Message string.')
 
575
_global_option('null', short_name='0',
 
576
               help='Use an ASCII NUL (\\0) separator rather than '
 
577
               'a newline.')
520
578
_global_option('overwrite', help='Ignore differences between branches and '
521
579
               '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,
530
 
               short_name='m',
531
 
               help='Message string.')
532
 
_global_option('no-recurse')
533
 
_global_option('profile',
534
 
               help='Show performance profiling information.')
 
580
_global_option('remember', help='Remember the specified location as a'
 
581
               ' default.')
 
582
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
535
583
_global_option('revision',
536
584
               type=_parse_revision_str,
537
585
               short_name='r',
538
586
               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".')
544
587
_global_option('show-ids',
545
588
               help='Show internal object ids.')
546
589
_global_option('timezone',
547
590
               type=str,
548
591
               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.')
573
592
 
574
593
diff_writer_registry = _mod_registry.Registry()
575
594
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')