Ship a modified version of optparse with click
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 7360097 · Browse files · 2 files·+655 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+655 added−39 removed
- other:+655 added−39 removed
Provenance
- Commit
82d9b0c- Tree
d066f99- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
7360097
2 files changed+655 added−39 removed
modified:click/_optparse.py+649 added-32 removed
1-import sys1+# -*- coding: utf-8 -*-2+"""3+ click._optparse4+ ~~~~~~~~~~~~~~~5 3-# optparse never fully supported gettext but for some reason it still4-# imports it which slows things down quite a bit. In case we are the5-# first importer of optparse and gettext we can disable gettext support6-# through this hackery.7-#8-# In case someone does depend on gettext being loaded into optparse we9-# might have a problem but I don't think anyone will actually notice.10-_gettext = sys.modules.get('gettext')11-sys.modules['gettext'] = None12-from optparse import IndentedHelpFormatter, OptionParser, Option, \13- SUPPRESS_HELP14-if _gettext is not None:15- sys.modules['gettext'] = _gettext16-else:17- del sys.modules['gettext']6+ This module is largely a copy paste from the stdlib's optparse module7+ with the features removed that we do not need from optparse because8+ we implement them in click on a higher level (for instance type9+ handling and some other things).10 11+ The plan is to remove more and more from here over time.12+13+ The reason this is a different module and not optparse from the stdlib14+ is that there are differences in 2.x and 3.x about the error messages15+ generated and optparse in the stdlib uses gettext for no good reason16+ and might cause us issues.17+"""18+import sys19+import textwrap20+21 from .helpers import get_terminal_size22 from .formatting import TextWrapper23 from .exceptions import UsageError24 25 24-class _SimplifiedFormatter(IndentedHelpFormatter):26+class HelpFormatter(object):27 26- def __init__(self):27- IndentedHelpFormatter.__init__(self,28- width=min(get_terminal_size()[0], 80) - 2)29- self.default_tag = ''28+ def __init__(self, indent_increment, max_help_position, width,29+ short_first):30+ self.parser = None31+ self.indent_increment = indent_increment32+ if width is None:33+ width = min(get_terminal_size()[0], 80) - 234+ self.width = width35+ self.help_position = self.max_help_position = \36+ min(max_help_position, max(width - 20, indent_increment * 2))37+ self.current_indent = 038+ self.level = 039+ self.help_width = None40+ self.short_first = short_first41+ self.option_strings = {}42+ self._short_opt_fmt = '%s %s'43+ self._long_opt_fmt = '%s=%s'44 45+ def set_parser(self, parser):46+ self.parser = parser47+48+ def indent(self):49+ self.current_indent += self.indent_increment50+ self.level += 151+52+ def dedent(self):53+ self.current_indent -= self.indent_increment54+ assert self.current_indent >= 0, 'Indent decreased below 0.'55+ self.level -= 156+57 def format_usage(self, usage):58+ raise NotImplementedError('subclasses must implement')59+60+ def format_heading(self, heading):61+ raise NotImplementedError('subclasses must implement')62+63+ def _format_text(self, text):64+ """65+ Format a paragraph of free-form text for inclusion in the66+ help output at the current indentation level.67+ """68+ text_width = max(self.width - self.current_indent, 11)69+ indent = ' ' * self.current_indent70+ return textwrap.fill(text,71+ text_width,72+ initial_indent=indent,73+ subsequent_indent=indent)74+75+ def format_description(self, description):76+ if description:77+ return self._format_text(description) + '\n'78+ else:79+ return ''80+81+ def format_epilog(self, epilog):82+ if epilog:83+ return '\n' + self._format_text(epilog) + '\n'84+ else:85+ return ''86+87+ def format_option(self, option):88+ result = []89+ opts = self.option_strings[option]90+ opt_width = self.help_position - self.current_indent - 291+ if len(opts) > opt_width:92+ opts = '%*s%s\n' % (self.current_indent, '', opts)93+ indent_first = self.help_position94+ else: # start help on same line as opts95+ opts = '%*s%-*s ' % (self.current_indent, '', opt_width, opts)96+ indent_first = 097+ result.append(opts)98+ if option.help:99+ help_text = option.help100+ help_lines = textwrap.wrap(help_text, self.help_width)101+ result.append('%*s%s\n' % (indent_first, '', help_lines[0]))102+ result.extend(['%*s%s\n' % (self.help_position, '', line)103+ for line in help_lines[1:]])104+ elif opts[-1] != '\n':105+ result.append('\n')106+ return ''.join(result)107+108+ def store_option_strings(self, parser):109+ self.indent()110+ max_len = 0111+ for opt in parser.option_list:112+ strings = self.format_option_strings(opt)113+ self.option_strings[opt] = strings114+ max_len = max(max_len, len(strings) + self.current_indent)115+ self.indent()116+ for group in parser.option_groups:117+ for opt in group.option_list:118+ strings = self.format_option_strings(opt)119+ self.option_strings[opt] = strings120+ max_len = max(max_len, len(strings) + self.current_indent)121+ self.dedent()122+ self.dedent()123+ self.help_position = min(max_len + 2, self.max_help_position)124+ self.help_width = max(self.width - self.help_position, 11)125+126+ def format_option_strings(self, option):127+ if option.takes_value():128+ metavar = option.metavar or option.dest.upper()129+ short_opts = [self._short_opt_fmt % (sopt, metavar)130+ for sopt in option._short_opts]131+ long_opts = [self._long_opt_fmt % (lopt, metavar)132+ for lopt in option._long_opts]133+ else:134+ short_opts = option._short_opts135+ long_opts = option._long_opts136+137+ if self.short_first:138+ opts = short_opts + long_opts139+ else:140+ opts = long_opts + short_opts141+142+ return ', '.join(opts)143+144+145+class IndentedHelpFormatter(HelpFormatter):146+ """Format help with indented section bodies.147+ """148+149+ def __init__(self, indent_increment=2, max_help_position=24,150+ width=None, short_first=1):151+ HelpFormatter.__init__(152+ self, indent_increment, max_help_position, width, short_first)153+154+ def format_usage(self, usage):155+ return 'Usage: %s\n' % usage156+157+ def format_heading(self, heading):158+ return '%*s%s:\n' % (self.current_indent, '', heading)159+160+161+class Option(object):162+ ATTRS = ['action', 'type', 'dest', 'nargs', 'const', 'help',163+ 'metavar']164+ ACTIONS = ('store', 'store_const', 'append', 'append_const')165+ STORE_ACTIONS = ('store', 'store_const', 'append', 'append_const')166+ TYPED_ACTIONS = ('store', 'append')167+ TAKES_VALUE_ACTIONS = ('store', 'append')168+ CONST_ACTIONS = ('store_const', 'append_const')169+170+ def __init__(self, *opts, **attrs):171+ self._short_opts = []172+ self._long_opts = []173+ self._set_opt_strings(self._check_opt_strings(opts))174+ self._set_attrs(attrs)175+ self._check_attrs()176+177+ def _check_attrs(self):178+ if self.action is None:179+ self.action = 'store'180+ elif self.action not in self.ACTIONS:181+ raise TypeError('invalid action: %r' % self.action)182+183+ takes_value = (self.action in self.STORE_ACTIONS or184+ self.takes_value)185+ if self.dest is None and takes_value:186+ # Glean a destination from the first long option string,187+ # or from the first short option string if no long options.188+ if self._long_opts:189+ # eg. '--foo-bar' -> 'foo_bar'190+ self.dest = self._long_opts[0][2:].replace('-', '_')191+ else:192+ self.dest = self._short_opts[0][1]193+194+ if self.action in self.TYPED_ACTIONS:195+ if self.nargs is None:196+ self.nargs = 1197+ elif self.nargs is not None:198+ raise TypeError(199+ '\'nargs\' must not be supplied for action %r' % self.action)200+201+ def _check_opt_strings(self, opts):202+ # Filter out None because early versions of Optik had exactly203+ # one short option and one long option, either of which204+ # could be None.205+ opts = [opt for opt in opts if opt]206+ if not opts:207+ raise TypeError('at least one option string must be supplied')208+ return opts209+210+ def _set_opt_strings(self, opts):211+ for opt in opts:212+ if len(opt) < 2:213+ raise TypeError(214+ 'invalid option string %r: '215+ 'must be at least two characters long' % opt)216+ elif len(opt) == 2:217+ if not (opt[0] == '-' and opt[1] != '-'):218+ raise TypeError(219+ 'invalid short option string %r: '220+ 'must be of the form -x, (x any non-dash char)' % opt)221+ self._short_opts.append(opt)222+ else:223+ if not (opt[0:2] == '--' and opt[2] != '-'):224+ raise TypeError(225+ 'invalid long option string %r: '226+ 'must start with --, followed by non-dash' % opt)227+ self._long_opts.append(opt)228+229+ def _set_attrs(self, attrs):230+ for attr in self.ATTRS:231+ if attr in attrs:232+ setattr(self, attr, attrs[attr])233+ del attrs[attr]234+ else:235+ setattr(self, attr, None)236+ if attrs:237+ attrs = sorted(attrs.keys())238+ raise TypeError('invalid keyword arguments: %s' %239+ ', '.join(attrs))240+241+ def __str__(self):242+ return '/'.join(self._short_opts + self._long_opts)243+244+ def takes_value(self):245+ return self.action in self.TAKES_VALUE_ACTIONS246+247+ def get_opt_string(self):248+ if self._long_opts:249+ return self._long_opts[0]250+ else:251+ return self._short_opts[0]252+253+ def process(self, opt, value, values, parser):254+ # And then take whatever action is expected of us.255+ # This is a separate method to make life easier for256+ # subclasses to add new actions.257+ return self.take_action(258+ self.action, self.dest, opt, value, values, parser)259+260+ def take_action(self, action, dest, opt, value, values, parser):261+ if action == 'store':262+ values[dest] = value263+ elif action == 'store_const':264+ values[dest] = self.const265+ elif action == 'append':266+ values.setdefault(dest, []).append(value)267+ elif action == 'append_const':268+ values.setdefault(dest, []).append(self.const)269+ else:270+ raise ValueError('unknown action %r' % self.action)271+ return 1272+273+274+SUPPRESS_HELP = object()275+276+277+class OptionContainer(object):278+279+ def __init__(self, option_class, description):280+ # Initialize the option list and related data structures.281+ # This method must be provided by subclasses, and it must282+ # initialize at least the following instance attributes:283+ # option_list, _short_opt, _long_opt.284+ self._create_option_list()285+286+ self.option_class = option_class287+ self.description = description288+289+ def _create_option_mappings(self):290+ # For use by OptionParser constructor -- create the master291+ # option mappings used by this OptionParser and all292+ # OptionGroups that it owns.293+ self._short_opt = {} # single letter -> Option instance294+ self._long_opt = {} # long option -> Option instance295+296+ def _share_option_mappings(self, parser):297+ # For use by OptionGroup constructor -- use shared option298+ # mappings from the OptionParser that owns this OptionGroup.299+ self._short_opt = parser._short_opt300+ self._long_opt = parser._long_opt301+302+ def add_option(self, *args, **kwargs):303+ if isinstance(args[0], str):304+ option = self.option_class(*args, **kwargs)305+ elif len(args) == 1 and not kwargs:306+ option = args[0]307+ if not isinstance(option, Option):308+ raise TypeError('not an Option instance: %r' % option)309+ else:310+ raise TypeError('invalid arguments')311+312+ self.option_list.append(option)313+ option.container = self314+ for opt in option._short_opts:315+ self._short_opt[opt] = option316+ for opt in option._long_opts:317+ self._long_opt[opt] = option318+319+ return option320+321+ def add_options(self, option_list):322+ for option in option_list:323+ self.add_option(option)324+325+ def get_option(self, opt_str):326+ return (self._short_opt.get(opt_str) or327+ self._long_opt.get(opt_str))328+329+ def has_option(self, opt_str):330+ return (opt_str in self._short_opt or331+ opt_str in self._long_opt)332+333+ def remove_option(self, opt_str):334+ option = self._short_opt.get(opt_str)335+ if option is None:336+ option = self._long_opt.get(opt_str)337+ if option is None:338+ raise ValueError('no such option %r' % opt_str)339+340+ for opt in option._short_opts:341+ del self._short_opt[opt]342+ for opt in option._long_opts:343+ del self._long_opt[opt]344+ option.container.option_list.remove(option)345+346+ def format_option_help(self, formatter):347+ if not self.option_list:348+ return ''349+ result = []350+ for option in self.option_list:351+ if not option.help is SUPPRESS_HELP:352+ result.append(formatter.format_option(option))353+ return ''.join(result)354+355+ def format_description(self, formatter):356+ return formatter.format_description(self.description)357+358+ def format_help(self, formatter):359+ result = []360+ if self.description:361+ result.append(self.format_description(formatter))362+ if self.option_list:363+ result.append(self.format_option_help(formatter))364+ return '\n'.join(result)365+366+367+class OptionGroup(OptionContainer):368+369+ def __init__(self, parser, title, description=None):370+ self.parser = parser371+ OptionContainer.__init__(372+ self, parser.option_class, description)373+ self.title = title374+375+ def _create_option_list(self):376+ self.option_list = []377+ self._share_option_mappings(self.parser)378+379+ def set_title(self, title):380+ self.title = title381+382+ def format_help(self, formatter):383+ result = formatter.format_heading(self.title)384+ formatter.indent()385+ result += OptionContainer.format_help(self, formatter)386+ formatter.dedent()387+ return result388+389+390+class OptionParser(OptionContainer):391+ standard_option_list = []392+393+ def __init__(self,394+ usage=None,395+ option_list=None,396+ option_class=Option,397+ description=None,398+ formatter=None,399+ epilog=None):400+ OptionContainer.__init__(401+ self, option_class, description)402+ self.usage = usage403+ self.allow_interspersed_args = True404+ if formatter is None:405+ formatter = IndentedHelpFormatter()406+ self.formatter = formatter407+ self.formatter.set_parser(self)408+ self.epilog = epilog409+410+ self._populate_option_list(option_list)411+412+ self._init_parsing_state()413+414+ def _create_option_list(self):415+ self.option_list = []416+ self.option_groups = []417+ self._create_option_mappings()418+419+ def _populate_option_list(self, option_list):420+ if self.standard_option_list:421+ self.add_options(self.standard_option_list)422+ if option_list:423+ self.add_options(option_list)424+425+ def _init_parsing_state(self):426+ self.rargs = None427+ self.largs = None428+ self.values = None429+430+ def _get_all_options(self):431+ options = self.option_list[:]432+ for group in self.option_groups:433+ options.extend(group.option_list)434+ return options435+436+ def add_option_group(self, *args, **kwargs):437+ if isinstance(args[0], str):438+ group = OptionGroup(self, *args, **kwargs)439+ elif len(args) == 1 and not kwargs:440+ group = args[0]441+ if not isinstance(group, OptionGroup):442+ raise TypeError('not an OptionGroup instance: %r' % group)443+ if group.parser is not self:444+ raise ValueError('invalid OptionGroup (wrong parser)')445+ else:446+ raise TypeError('invalid arguments')447+448+ self.option_groups.append(group)449+ return group450+451+ def get_option_group(self, opt_str):452+ option = (self._short_opt.get(opt_str) or453+ self._long_opt.get(opt_str))454+ if option and option.container is not self:455+ return option.container456+ return None457+458+ def parse_args(self, args, values=None):459+ rargs = args460+ if values is None:461+ values = {}462+ self.rargs = rargs463+ self.largs = largs = []464+ self.values = values465+466+ self._process_args(largs, rargs, values)467+468+ args = largs + rargs469+ return values, args470+471+ def _process_args(self, largs, rargs, values):472+ while rargs:473+ arg = rargs[0]474+ # We handle bare '--' explicitly, and bare '-' is handled by the475+ # standard arg handler since the short arg case ensures that the476+ # len of the opt string is greater than 1.477+ if arg == '--':478+ del rargs[0]479+ return480+ elif arg[0:2] == '--':481+ # process a single long option (possibly with value(s))482+ self._process_long_opt(rargs, values)483+ elif arg[:1] == '-' and len(arg) > 1:484+ # process a cluster of short options (possibly with485+ # value(s) for the last one only)486+ self._process_short_opts(rargs, values)487+ elif self.allow_interspersed_args:488+ largs.append(arg)489+ del rargs[0]490+ else:491+ return492+493+ # Say this is the original argument list:494+ # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]495+ # ^496+ # (we are about to process arg(i)).497+ #498+ # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of499+ # [arg0, ..., arg(i-1)] (any options and their arguments will have500+ # been removed from largs).501+ #502+ # The while loop will usually consume 1 or more arguments per pass.503+ # If it consumes 1 (eg. arg is an option that takes no arguments),504+ # then after _process_arg() is done the situation is:505+ #506+ # largs = subset of [arg0, ..., arg(i)]507+ # rargs = [arg(i+1), ..., arg(N-1)]508+ #509+ # If allow_interspersed_args is false, largs will always be510+ # *empty* -- still a subset of [arg0, ..., arg(i-1)], but511+ # not a very interesting subset!512+513+ def _match_long_opt(self, opt):514+ # Is there an exact match?515+ if opt in self._long_opt:516+ return opt517+518+ # Isolate all words with s as a prefix.519+ possibilities = [word for word in self._long_opt520+ if word.startswith(opt)]521+522+ # No exact match, so there had better be just one possibility.523+ if not possibilities:524+ self.error('no such option: %s' % opt)525+ elif len(possibilities) == 1:526+ self.error('no such option: %s. Did you mean %s?' %527+ (opt, possibilities[0]))528+ return possibilities[0]529+ else:530+ # More than one possible completion: ambiguous prefix.531+ possibilities.sort()532+ self.error('no such option: %s. (Possible options: %s)'533+ % (opt, ', '.join(possibilities)))534+535+ def _process_long_opt(self, rargs, values):536+ arg = rargs.pop(0)537+538+ # Value explicitly attached to arg? Pretend it's the next539+ # argument.540+ if '=' in arg:541+ opt, next_arg = arg.split('=', 1)542+ rargs.insert(0, next_arg)543+ had_explicit_value = True544+ else:545+ opt = arg546+ had_explicit_value = False547+548+ opt = self._match_long_opt(opt)549+ option = self._long_opt[opt]550+ if option.takes_value():551+ nargs = option.nargs552+ if len(rargs) < nargs:553+ if nargs == 1:554+ self.error('%s option requires an argument' % opt)555+ else:556+ self.error('%s option requires %d arguments' % (opt, nargs))557+ elif nargs == 1:558+ value = rargs.pop(0)559+ else:560+ value = tuple(rargs[0:nargs])561+ del rargs[0:nargs]562+563+ elif had_explicit_value:564+ self.error('%s option does not take a value' % opt)565+566+ else:567+ value = None568+569+ option.process(opt, value, values, self)570+571+ def _process_short_opts(self, rargs, values):572+ arg = rargs.pop(0)573+ stop = False574+ i = 1575+ for ch in arg[1:]:576+ opt = '-' + ch577+ option = self._short_opt.get(opt)578+ i += 1 # we have consumed a character579+580+ if not option:581+ self.fail('no such option: %s' % opt)582+ if option.takes_value():583+ # Any characters left in arg? Pretend they're the584+ # next arg, and stop consuming characters of arg.585+ if i < len(arg):586+ rargs.insert(0, arg[i:])587+ stop = True588+589+ nargs = option.nargs590+ if len(rargs) < nargs:591+ if nargs == 1:592+ self.error('%s option requires an argument' % opt)593+ else:594+ self.error('%s option requires %d arguments' %595+ (opt, nargs))596+ elif nargs == 1:597+ value = rargs.pop(0)598+ else:599+ value = tuple(rargs[0:nargs])600+ del rargs[0:nargs]601+602+ else:603+ value = None604+605+ option.process(opt, value, values, self)606+607+ if stop:608+ break609+610+ def exit(self, status=0, msg=None):611+ if msg:612+ sys.stderr.write(msg)613+ sys.exit(status)614+615+ def error(self, msg):616+ raise Exception(msg)617+618+ def get_usage(self):619+ if self.usage:620+ return self.formatter.format_usage(self.usage)621+ return ''622+623+ def format_option_help(self, formatter=None):624+ if formatter is None:625+ formatter = self.formatter626+ formatter.store_option_strings(self)627+ result = []628+ result.append(formatter.format_heading('Options'))629+ formatter.indent()630+ if self.option_list:631+ result.append(OptionContainer.format_option_help(self, formatter))632+ result.append('\n')633+ for group in self.option_groups:634+ result.append(group.format_help(formatter))635+ result.append('\n')636+ formatter.dedent()637+ # Drop the last '\n', or the header if no options or option groups:638+ return ''.join(result[:-1])639+640+ def format_epilog(self, formatter):641+ return formatter.format_epilog(self.epilog)642+643+ def format_help(self, formatter=None):644+ if formatter is None:645+ formatter = self.formatter646+ result = []647+ if self.usage:648+ result.append(self.get_usage() + '\n')649+ if self.description:650+ result.append(self.format_description(formatter) + '\n')651+ result.append(self.format_option_help(formatter))652+ result.append(self.format_epilog(formatter))653+ return ''.join(result)654+655+656+class _SimplifiedFormatter(IndentedHelpFormatter):657+658+ def format_usage(self, usage):659 prefix = 'Usage: '660 indent = len(prefix)661 text_width = self.width - indent662 return '%s%s\n' % (prefix, TextWrapper(29 unmodified lines692 class _SimplifiedOptionParser(OptionParser):693 694 def __init__(self, ctx, **extra):695 usage = ctx.command_path + ' ' + ctx.command.options_metavar69- OptionParser.__init__(self, prog=ctx.command_path,70- usage=usage,71- add_help_option=False,696+ OptionParser.__init__(self, usage=usage,697 formatter=_SimplifiedFormatter(),698 **extra)699 self.__ctx = ctx700 76- def expand_prog_name(self, s):77- return s78-701 def format_option_help(self, formatter):702 rv = OptionParser.format_option_help(self, formatter)703 extra_help = self.__ctx.command._format_extra_help(self.__ctx)704 if extra_help:1 unmodified line706 return rv707 708 def error(self, msg):709 raise UsageError(msg, self.__ctx)88-89-90-# Re-exports91-make_option = Option92-SUPPRESS_HELP = SUPPRESS_HELPmodified:click/core.py+6 added-7 removed
255 unmodified lines256 constructor.257 """258 ctx = Context(self, info_name=info_name, parent=parent, **extra)259 opts, args = ctx._parser.parse_args(args=args)260- opts = opts.__dict__260 261 for param in ctx.command.iter_params_for_processing():262 value, args = param.handle_parse_result(ctx, opts, args)263 107 unmodified lines371 372 def _make_parser(self, ctx):373 parser = Command._make_parser(self, ctx)374 parser.usage += ' ' + self.subcommand_metavar376- parser.disable_interspersed_args()375+ parser.allow_interspersed_args = False376 return parser377 378 def _format_extra_help(self, ctx):379 commands = self.list_commands(ctx)389 unmodified lines769 770 if self.is_flag:771 kwargs.pop('nargs', None)772 if self.is_bool_flag and self.secondary_opts:774- pos_opt = _optparse.make_option(775- *self.opts, action=action + '_true', **kwargs)773+ pos_opt = _optparse.Option(774+ *self.opts, action=action + '_const', const=True, **kwargs)775 kwargs.pop('default', None)776 kwargs.pop('help', None)778- neg_opt = _optparse.make_option(779- *self.secondary_opts, action=action + '_false',780- help=_optparse.SUPPRESS_HELP, **kwargs)777+ neg_opt = _optparse.Option(778+ *self.secondary_opts, action=action + '_const',779+ const=False, help=_optparse.SUPPRESS_HELP, **kwargs)780 pos_opt._negative_version = neg_opt781 parser.add_option(pos_opt)782 parser.add_option(neg_opt)783 else:120 unmodified lines