/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: Jelmer Vernooij
  • Date: 2020-04-05 19:11:34 UTC
  • mto: (7490.7.16 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200405191134-0aebh8ikiwygxma5
Populate the .gitignore file.

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
 
20
22
import optparse
21
23
import re
22
24
 
23
 
from bzrlib.lazy_import import lazy_import
24
 
lazy_import(globals(), """
25
 
from bzrlib import (
 
25
from . import (
26
26
    errors,
 
27
    registry as _mod_registry,
27
28
    revisionspec,
28
29
    )
29
 
""")
30
 
 
31
 
from bzrlib import (
32
 
    registry as _mod_registry,
 
30
from .sixish import (
 
31
    text_type,
33
32
    )
34
33
 
35
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)
 
41
 
 
42
 
36
43
def _parse_revision_str(revstr):
37
44
    """This handles a revision string -> revno.
38
45
 
116
123
def _parse_merge_type(typestring):
117
124
    return get_merge_type(typestring)
118
125
 
 
126
 
119
127
def get_merge_type(typestring):
120
128
    """Attempt to find the merge class/factory associated with a string."""
121
129
    from merge import merge_types
122
130
    try:
123
131
        return merge_types[typestring][0]
124
132
    except KeyError:
125
 
        templ = '%s%%7s: %%s' % (' '*12)
126
 
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
133
        templ = '%s%%7s: %%s' % (' ' * 12)
 
134
        lines = [templ % (f[0], f[1][1]) for f in merge_types.items()]
127
135
        type_list = '\n'.join(lines)
128
136
        msg = "No known merge type %s. Supported types are:\n%s" %\
129
137
            (typestring, type_list)
238
246
            self.custom_callback(option, self._param_name, bool_v, parser)
239
247
 
240
248
    def _optparse_callback(self, option, opt, value, parser):
241
 
        v = self.type(value)
 
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))
242
254
        setattr(parser.values, self._param_name, v)
243
255
        if self.custom_callback is not None:
244
256
            self.custom_callback(option, self.name, v, parser)
248
260
 
249
261
        :return: an iterator of (name, short_name, argname, help)
250
262
        """
251
 
        argname =  self.argname
 
263
        argname = self.argname
252
264
        if argname is not None:
253
265
            argname = argname.upper()
254
266
        yield self.name, self.short_name(), argname, self.help
300
312
    def validate_value(self, value):
301
313
        """Validate a value name"""
302
314
        if value not in self.registry:
303
 
            raise errors.BadOptionValue(self.name, value)
 
315
            raise BadOptionValue(self.name, value)
304
316
 
305
317
    def convert(self, value):
306
318
        """Convert a value name into an output type"""
311
323
            return self.converter(value)
312
324
 
313
325
    def __init__(self, name, help, registry=None, converter=None,
314
 
        value_switches=False, title=None, enum_switch=True,
315
 
        lazy_registry=None):
 
326
                 value_switches=False, title=None, enum_switch=True,
 
327
                 lazy_registry=None, short_name=None, short_value_switches=None):
316
328
        """
317
329
        Constructor.
318
330
 
328
340
            which takes a value.
329
341
        :param lazy_registry: A tuple of (module name, attribute name) for a
330
342
            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
331
345
        """
332
 
        Option.__init__(self, name, help, type=self.convert)
 
346
        Option.__init__(self, name, help, type=self.convert,
 
347
                        short_name=short_name)
333
348
        self._registry = registry
334
349
        if registry is None:
335
350
            if lazy_registry is None:
344
359
        self.converter = converter
345
360
        self.value_switches = value_switches
346
361
        self.enum_switch = enum_switch
 
362
        self.short_value_switches = short_value_switches
347
363
        self.title = title
348
364
        if self.title is None:
349
365
            self.title = name
372
388
                if not help.endswith("."):
373
389
                    help = help + "."
374
390
        return RegistryOption(name_, help, reg, title=title,
375
 
            value_switches=value_switches, enum_switch=enum_switch)
 
391
                              value_switches=value_switches, enum_switch=enum_switch)
376
392
 
377
393
    def add_option(self, parser, short_name):
378
394
        """Add this option to an Optparse parser"""
381
397
        if self.enum_switch:
382
398
            Option.add_option(self, parser, short_name)
383
399
        if self.value_switches:
 
400
            alias_map = self.registry.alias_map()
384
401
            for key in self.registry.keys():
385
 
                option_strings = ['--%s' % key]
 
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)]]
386
409
                if self.is_hidden(key):
387
410
                    help = optparse.SUPPRESS_HELP
388
411
                else:
389
412
                    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])
390
417
                parser.add_option(action='callback',
391
 
                              callback=self._optparse_value_callback(key),
 
418
                                  callback=self._optparse_value_callback(key),
392
419
                                  help=help,
393
420
                                  *option_strings)
394
421
 
411
438
            for key in sorted(self.registry.keys()):
412
439
                yield key, None, None, self.registry.get_help(key)
413
440
 
 
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
 
414
447
    def is_hidden(self, name):
415
448
        if name == self.name:
416
449
            return Option.is_hidden(self, name)
422
455
 
423
456
    DEFAULT_VALUE = object()
424
457
 
 
458
    def __init__(self):
 
459
        optparse.OptionParser.__init__(self)
 
460
        self.formatter = GettextIndentedHelpFormatter()
 
461
 
425
462
    def error(self, message):
426
463
        raise errors.BzrCommandError(message)
427
464
 
428
465
 
 
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
 
429
480
def get_optparser(options):
430
 
    """Generate an optparse parser for bzrlib-style options"""
 
481
    """Generate an optparse parser for breezy-style options"""
431
482
 
432
483
    parser = OptionParser()
433
484
    parser.remove_option('--help')
434
 
    for option in options.itervalues():
 
485
    for option in options:
435
486
        option.add_option(parser, option.short_name())
436
487
    return parser
437
488
 
451
502
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
452
503
 
453
504
 
 
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
 
454
512
def _global_option(name, **kwargs):
455
513
    """Register a global option."""
456
514
    Option.OPTIONS[name] = Option(name, **kwargs)
488
546
            _verbosity_level = -1
489
547
 
490
548
 
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
549
# Declare the standard options
507
550
_standard_option('help', short_name='h',
508
551
                 help='Show help message.')
 
552
_standard_option('quiet', short_name='q',
 
553
                 help="Only display errors and warnings.",
 
554
                 custom_callback=_verbosity_level_callback)
509
555
_standard_option('usage',
510
556
                 help='Show usage message and options.')
511
557
_standard_option('verbose', short_name='v',
512
558
                 help='Display more information.',
513
559
                 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
560
 
518
561
# Declare commonly used options
519
 
_global_option('all')
 
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,
 
578
               short_name='m',
 
579
               help='Message string.')
 
580
_global_option('null', short_name='0',
 
581
               help='Use an ASCII NUL (\\0) separator rather than '
 
582
               'a newline.')
520
583
_global_option('overwrite', help='Ignore differences between branches and '
521
584
               '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.')
 
585
_global_option('remember', help='Remember the specified location as a'
 
586
               ' default.')
 
587
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
535
588
_global_option('revision',
536
589
               type=_parse_revision_str,
537
590
               short_name='r',
538
591
               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
592
_global_option('show-ids',
545
593
               help='Show internal object ids.')
546
594
_global_option('timezone',
547
595
               type=str,
548
596
               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
597
 
574
598
diff_writer_registry = _mod_registry.Registry()
575
599
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')