/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: 2019-02-04 01:01:24 UTC
  • mto: This revision was merged to the branch mainline in revision 7268.
  • Revision ID: jelmer@jelmer.uk-20190204010124-ni0i4qc6f5tnbvux
Fix source tests.

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)
248
256
 
249
257
        :return: an iterator of (name, short_name, argname, help)
250
258
        """
251
 
        argname =  self.argname
 
259
        argname = self.argname
252
260
        if argname is not None:
253
261
            argname = argname.upper()
254
262
        yield self.name, self.short_name(), argname, self.help
300
308
    def validate_value(self, value):
301
309
        """Validate a value name"""
302
310
        if value not in self.registry:
303
 
            raise errors.BadOptionValue(self.name, value)
 
311
            raise BadOptionValue(self.name, value)
304
312
 
305
313
    def convert(self, value):
306
314
        """Convert a value name into an output type"""
311
319
            return self.converter(value)
312
320
 
313
321
    def __init__(self, name, help, registry=None, converter=None,
314
 
        value_switches=False, title=None, enum_switch=True,
315
 
        lazy_registry=None):
 
322
                 value_switches=False, title=None, enum_switch=True,
 
323
                 lazy_registry=None, short_name=None, short_value_switches=None):
316
324
        """
317
325
        Constructor.
318
326
 
328
336
            which takes a value.
329
337
        :param lazy_registry: A tuple of (module name, attribute name) for a
330
338
            registry to be lazily loaded.
 
339
        :param short_name: The short name for the enum switch, if any
 
340
        :param short_value_switches: A dict mapping values to short names
331
341
        """
332
 
        Option.__init__(self, name, help, type=self.convert)
 
342
        Option.__init__(self, name, help, type=self.convert,
 
343
                        short_name=short_name)
333
344
        self._registry = registry
334
345
        if registry is None:
335
346
            if lazy_registry is None:
344
355
        self.converter = converter
345
356
        self.value_switches = value_switches
346
357
        self.enum_switch = enum_switch
 
358
        self.short_value_switches = short_value_switches
347
359
        self.title = title
348
360
        if self.title is None:
349
361
            self.title = name
372
384
                if not help.endswith("."):
373
385
                    help = help + "."
374
386
        return RegistryOption(name_, help, reg, title=title,
375
 
            value_switches=value_switches, enum_switch=enum_switch)
 
387
                              value_switches=value_switches, enum_switch=enum_switch)
376
388
 
377
389
    def add_option(self, parser, short_name):
378
390
        """Add this option to an Optparse parser"""
381
393
        if self.enum_switch:
382
394
            Option.add_option(self, parser, short_name)
383
395
        if self.value_switches:
 
396
            alias_map = self.registry.alias_map()
384
397
            for key in self.registry.keys():
385
 
                option_strings = ['--%s' % key]
 
398
                if key in self.registry.aliases():
 
399
                    continue
 
400
                option_strings = [
 
401
                    ('--%s' % name)
 
402
                    for name in [key] +
 
403
                    [alias for alias in alias_map.get(key, [])
 
404
                        if not self.is_hidden(alias)]]
386
405
                if self.is_hidden(key):
387
406
                    help = optparse.SUPPRESS_HELP
388
407
                else:
389
408
                    help = self.registry.get_help(key)
 
409
                if (self.short_value_switches and
 
410
                        key in self.short_value_switches):
 
411
                    option_strings.append('-%s' %
 
412
                                          self.short_value_switches[key])
390
413
                parser.add_option(action='callback',
391
 
                              callback=self._optparse_value_callback(key),
 
414
                                  callback=self._optparse_value_callback(key),
392
415
                                  help=help,
393
416
                                  *option_strings)
394
417
 
411
434
            for key in sorted(self.registry.keys()):
412
435
                yield key, None, None, self.registry.get_help(key)
413
436
 
 
437
    def is_alias(self, name):
 
438
        """Check whether a particular format is an alias."""
 
439
        if name == self.name:
 
440
            return False
 
441
        return name in self.registry.aliases()
 
442
 
414
443
    def is_hidden(self, name):
415
444
        if name == self.name:
416
445
            return Option.is_hidden(self, name)
422
451
 
423
452
    DEFAULT_VALUE = object()
424
453
 
 
454
    def __init__(self):
 
455
        optparse.OptionParser.__init__(self)
 
456
        self.formatter = GettextIndentedHelpFormatter()
 
457
 
425
458
    def error(self, message):
426
459
        raise errors.BzrCommandError(message)
427
460
 
428
461
 
 
462
class GettextIndentedHelpFormatter(optparse.IndentedHelpFormatter):
 
463
    """Adds gettext() call to format_option()"""
 
464
 
 
465
    def __init__(self):
 
466
        optparse.IndentedHelpFormatter.__init__(self)
 
467
 
 
468
    def format_option(self, option):
 
469
        """code taken from Python's optparse.py"""
 
470
        if option.help:
 
471
            from .i18n import gettext
 
472
            option.help = gettext(option.help)
 
473
        return optparse.IndentedHelpFormatter.format_option(self, option)
 
474
 
 
475
 
429
476
def get_optparser(options):
430
 
    """Generate an optparse parser for bzrlib-style options"""
 
477
    """Generate an optparse parser for breezy-style options"""
431
478
 
432
479
    parser = OptionParser()
433
480
    parser.remove_option('--help')
434
 
    for option in options.itervalues():
 
481
    for option in options:
435
482
        option.add_option(parser, option.short_name())
436
483
    return parser
437
484
 
451
498
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
452
499
 
453
500
 
 
501
def _standard_list_option(name, **kwargs):
 
502
    """Register a standard option."""
 
503
    # All standard options are implicitly 'global' ones
 
504
    Option.STD_OPTIONS[name] = ListOption(name, **kwargs)
 
505
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
 
506
 
 
507
 
454
508
def _global_option(name, **kwargs):
455
509
    """Register a global option."""
456
510
    Option.OPTIONS[name] = Option(name, **kwargs)
488
542
            _verbosity_level = -1
489
543
 
490
544
 
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
545
# Declare the standard options
507
546
_standard_option('help', short_name='h',
508
547
                 help='Show help message.')
 
548
_standard_option('quiet', short_name='q',
 
549
                 help="Only display errors and warnings.",
 
550
                 custom_callback=_verbosity_level_callback)
509
551
_standard_option('usage',
510
552
                 help='Show usage message and options.')
511
553
_standard_option('verbose', short_name='v',
512
554
                 help='Display more information.',
513
555
                 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
556
 
518
557
# Declare commonly used options
519
 
_global_option('all')
 
558
_global_option('change',
 
559
               type=_parse_change_str,
 
560
               short_name='c',
 
561
               param_name='revision',
 
562
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
 
563
_global_option('directory', short_name='d', type=text_type,
 
564
               help='Branch to operate on, instead of working directory.')
 
565
_global_option('file', type=text_type, short_name='F')
 
566
_global_registry_option('log-format', "Use specified log format.",
 
567
                        lazy_registry=('breezy.log', 'log_formatter_registry'),
 
568
                        value_switches=True, title='Log format',
 
569
                        short_value_switches={'short': 'S'})
 
570
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
 
571
                        lazy_registry=('breezy.merge', 'merge_type_registry'),
 
572
                        value_switches=True, title='Merge algorithm')
 
573
_global_option('message', type=text_type,
 
574
               short_name='m',
 
575
               help='Message string.')
 
576
_global_option('null', short_name='0',
 
577
               help='Use an ASCII NUL (\\0) separator rather than '
 
578
               'a newline.')
520
579
_global_option('overwrite', help='Ignore differences between branches and '
521
580
               '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.')
 
581
_global_option('remember', help='Remember the specified location as a'
 
582
               ' default.')
 
583
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
535
584
_global_option('revision',
536
585
               type=_parse_revision_str,
537
586
               short_name='r',
538
587
               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
588
_global_option('show-ids',
545
589
               help='Show internal object ids.')
546
590
_global_option('timezone',
547
591
               type=str,
548
592
               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
593
 
574
594
diff_writer_registry = _mod_registry.Registry()
575
595
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')