Removed more unneeded leftovers from optparse
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 a25bf13 · Browse files · 3 files·+289 added−363 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+289 added−363 removed
- other:+289 added−363 removed
Provenance
- Commit
d5e2fbf- Tree
ed9f81c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
a25bf13
3 files changed+289 added−363 removed
deleted:click/_optparse.py-342 removed
1-# -*- coding: utf-8 -*-2-"""3- click._optparse4- ~~~~~~~~~~~~~~~5-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, help formatting and a lot more).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-20-from .exceptions import UsageError21-22-23-class Option(object):24- ATTRS = ['action', 'type', 'dest', 'nargs', 'const', 'help',25- 'metavar']26- ACTIONS = ('store', 'store_const', 'append', 'append_const')27- STORE_ACTIONS = ('store', 'store_const', 'append', 'append_const')28- TYPED_ACTIONS = ('store', 'append')29- TAKES_VALUE_ACTIONS = ('store', 'append')30- CONST_ACTIONS = ('store_const', 'append_const')31-32- def __init__(self, *opts, **attrs):33- self._short_opts = []34- self._long_opts = []35-36- for opt in opts:37- if len(opt) < 2:38- raise TypeError(39- 'invalid option string %r: '40- 'must be at least two characters long' % opt)41- elif len(opt) == 2:42- if not (opt[0] == '-' and opt[1] != '-'):43- raise TypeError(44- 'invalid short option string %r: '45- 'must be of the form -x, (x any non-dash char)' % opt)46- self._short_opts.append(opt)47- else:48- if not (opt[:2] == '--' and opt[2] != '-'):49- raise TypeError(50- 'invalid long option string %r: '51- 'must start with --, followed by non-dash' % opt)52- self._long_opts.append(opt)53-54- for attr in self.ATTRS:55- if attr in attrs:56- setattr(self, attr, attrs[attr])57- del attrs[attr]58- else:59- setattr(self, attr, None)60- if attrs:61- attrs = sorted(attrs.keys())62- raise TypeError('invalid keyword arguments: %s' %63- ', '.join(attrs))64-65- if self.action is None:66- self.action = 'store'67- if self.action in self.TYPED_ACTIONS:68- if self.nargs is None:69- self.nargs = 170-71- @property72- def takes_value(self):73- return self.action in self.TAKES_VALUE_ACTIONS74-75- def get_opt_string(self):76- if self._long_opts:77- return self._long_opts[0]78- return self._short_opts[0]79-80- def process(self, opt, value, values, parser):81- if self.action == 'store':82- values[self.dest] = value83- elif self.action == 'store_const':84- values[self.dest] = self.const85- elif self.action == 'append':86- values.setdefault(self.dest, []).append(value)87- elif self.action == 'append_const':88- values.setdefault(self.dest, []).append(self.const)89- else:90- raise ValueError('unknown action %r' % self.action)91-92-93-class OptionContainer(object):94-95- def __init__(self, option_class):96- # Initialize the option list and related data structures.97- # This method must be provided by subclasses, and it must98- # initialize at least the following instance attributes:99- # option_list, _short_opt, _long_opt.100- self._create_option_list()101-102- self.option_class = option_class103-104- def _create_option_mappings(self):105- # For use by OptionParser constructor -- create the master106- # option mappings used by this OptionParser and all107- # OptionGroups that it owns.108- self._short_opt = {} # single letter -> Option instance109- self._long_opt = {} # long option -> Option instance110-111- def add_option(self, *args, **kwargs):112- if isinstance(args[0], str):113- option = self.option_class(*args, **kwargs)114- elif len(args) == 1 and not kwargs:115- option = args[0]116- if not isinstance(option, Option):117- raise TypeError('not an Option instance: %r' % option)118- else:119- raise TypeError('invalid arguments')120-121- self.option_list.append(option)122- option.container = self123- for opt in option._short_opts:124- self._short_opt[opt] = option125- for opt in option._long_opts:126- self._long_opt[opt] = option127-128- return option129-130- def add_options(self, option_list):131- for option in option_list:132- self.add_option(option)133-134- def get_option(self, opt_str):135- return (self._short_opt.get(opt_str) or136- self._long_opt.get(opt_str))137-138- def has_option(self, opt_str):139- return (opt_str in self._short_opt or140- opt_str in self._long_opt)141-142- def remove_option(self, opt_str):143- option = self._short_opt.get(opt_str)144- if option is None:145- option = self._long_opt.get(opt_str)146- if option is None:147- raise ValueError('no such option %r' % opt_str)148-149- for opt in option._short_opts:150- del self._short_opt[opt]151- for opt in option._long_opts:152- del self._long_opt[opt]153- option.container.option_list.remove(option)154-155-156-class OptionParser(OptionContainer):157-158- def __init__(self, option_list=None, option_class=Option):159- OptionContainer.__init__(self, option_class)160- self.allow_interspersed_args = True161- if option_list:162- self.add_options(option_list)163- self._init_parsing_state()164-165- def _create_option_list(self):166- self.option_list = []167- self._create_option_mappings()168-169- def _init_parsing_state(self):170- self.rargs = None171- self.largs = None172- self.values = None173-174- def parse_args(self, args, values=None):175- rargs = args176- if values is None:177- values = {}178- self.rargs = rargs179- self.largs = largs = []180- self.values = values181-182- self._process_args(largs, rargs, values)183-184- args = largs + rargs185- return values, args186-187- def _process_args(self, largs, rargs, values):188- while rargs:189- arg = rargs[0]190- # We handle bare '--' explicitly, and bare '-' is handled by the191- # standard arg handler since the short arg case ensures that the192- # len of the opt string is greater than 1.193- if arg == '--':194- del rargs[0]195- return196- elif arg[0:2] == '--':197- # process a single long option (possibly with value(s))198- self._process_long_opt(rargs, values)199- elif arg[:1] == '-' and len(arg) > 1:200- # process a cluster of short options (possibly with201- # value(s) for the last one only)202- self._process_short_opts(rargs, values)203- elif self.allow_interspersed_args:204- largs.append(arg)205- del rargs[0]206- else:207- return208-209- # Say this is the original argument list:210- # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]211- # ^212- # (we are about to process arg(i)).213- #214- # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of215- # [arg0, ..., arg(i-1)] (any options and their arguments will have216- # been removed from largs).217- #218- # The while loop will usually consume 1 or more arguments per pass.219- # If it consumes 1 (eg. arg is an option that takes no arguments),220- # then after _process_arg() is done the situation is:221- #222- # largs = subset of [arg0, ..., arg(i)]223- # rargs = [arg(i+1), ..., arg(N-1)]224- #225- # If allow_interspersed_args is false, largs will always be226- # *empty* -- still a subset of [arg0, ..., arg(i-1)], but227- # not a very interesting subset!228-229- def _match_long_opt(self, opt):230- # Is there an exact match?231- if opt in self._long_opt:232- return opt233-234- # Isolate all words with s as a prefix.235- possibilities = [word for word in self._long_opt236- if word.startswith(opt)]237-238- # No exact match, so there had better be just one possibility.239- if not possibilities:240- self.error('no such option: %s' % opt)241- elif len(possibilities) == 1:242- self.error('no such option: %s. Did you mean %s?' %243- (opt, possibilities[0]))244- return possibilities[0]245- else:246- # More than one possible completion: ambiguous prefix.247- possibilities.sort()248- self.error('no such option: %s. (Possible options: %s)'249- % (opt, ', '.join(possibilities)))250-251- def _process_long_opt(self, rargs, values):252- arg = rargs.pop(0)253-254- # Value explicitly attached to arg? Pretend it's the next255- # argument.256- if '=' in arg:257- opt, next_arg = arg.split('=', 1)258- rargs.insert(0, next_arg)259- had_explicit_value = True260- else:261- opt = arg262- had_explicit_value = False263-264- opt = self._match_long_opt(opt)265- option = self._long_opt[opt]266- if option.takes_value:267- nargs = option.nargs268- if len(rargs) < nargs:269- if nargs == 1:270- self.error('%s option requires an argument' % opt)271- else:272- self.error('%s option requires %d arguments' % (opt, nargs))273- elif nargs == 1:274- value = rargs.pop(0)275- else:276- value = tuple(rargs[0:nargs])277- del rargs[0:nargs]278-279- elif had_explicit_value:280- self.error('%s option does not take a value' % opt)281-282- else:283- value = None284-285- option.process(opt, value, values, self)286-287- def _process_short_opts(self, rargs, values):288- arg = rargs.pop(0)289- stop = False290- i = 1291- for ch in arg[1:]:292- opt = '-' + ch293- option = self._short_opt.get(opt)294- i += 1 # we have consumed a character295-296- if not option:297- self.error('no such option: %s' % opt)298- if option.takes_value:299- # Any characters left in arg? Pretend they're the300- # next arg, and stop consuming characters of arg.301- if i < len(arg):302- rargs.insert(0, arg[i:])303- stop = True304-305- nargs = option.nargs306- if len(rargs) < nargs:307- if nargs == 1:308- self.error('%s option requires an argument' % opt)309- else:310- self.error('%s option requires %d arguments' %311- (opt, nargs))312- elif nargs == 1:313- value = rargs.pop(0)314- else:315- value = tuple(rargs[0:nargs])316- del rargs[0:nargs]317-318- else:319- value = None320-321- option.process(opt, value, values, self)322-323- if stop:324- break325-326- def exit(self, status=0, msg=None):327- if msg:328- sys.stderr.write(msg)329- sys.exit(status)330-331- def error(self, msg):332- raise Exception(msg)333-334-335-class _SimplifiedOptionParser(OptionParser):336-337- def __init__(self, ctx, **extra):338- OptionParser.__init__(self, **extra)339- self.__ctx = ctx340-341- def error(self, msg):342- raise UsageError(msg, self.__ctx)modified:click/core.py+14 added-21 removed
6 unmodified lines7 from .utils import make_str, make_default_short_help8 from .exceptions import UsageError, Abort9 from .helpers import prompt, confirm, echo10 from .formatting import HelpFormatter11+from .parser import OptionParser12 12-from . import _optparse13 from ._compat import PY214 15 _missing = object()16 250 unmodified lines267 """Iterates over all parameter names."""268 for param in self.iter_params_for_processing():269 yield param.name270 271- def _make_parser(self, ctx):272- parser = _optparse._SimplifiedOptionParser(ctx)271+ def make_parser(self, ctx):272+ parser = OptionParser(ctx)273 for param in self.params:274- param._add_to_parser(parser, ctx)274+ param.add_to_parser(parser, ctx)275 return parser276 277 def format_usage(self, ctx):278 """Formats the usage line."""61 unmodified lines340 :param extra: extra keyword arguments forwarded to the context341 constructor.342 """343 ctx = Context(self, info_name=info_name, parent=parent, **extra)344- parser = self._make_parser(ctx)344+ parser = self.make_parser(ctx)345 opts, args = parser.parse_args(args=args)346 347 for param in ctx.command.iter_params_for_processing():348 value, args = param.handle_parse_result(ctx, opts, args)105 unmodified lines454 self.no_args_is_help = no_args_is_help455 self.invoke_without_command = invoke_without_command456 self.subcommand_metavar = subcommand_metavar457 458- def _make_parser(self, ctx):459- parser = Command._make_parser(self, ctx)458+ def make_parser(self, ctx):459+ parser = Command.make_parser(self, ctx)460 parser.allow_interspersed_args = False461 return parser462 463 def _collect_usage_pieces(self, ctx):196 unmodified lines660 else:661 rv = self.default662 return self.type(rv, self, ctx)663 664- def _add_to_parser(self, parser, ctx):665- raise NotImplementedError()664+ def add_to_parser(self, parser, ctx):665+ pass666 667 def process_value(self, ctx, value):668 """Given a value and context this runs the logic to convert the669 value as necessary.171 unmodified lines841 raise TypeError('Could not determine name for option')842 843 return name.replace('-', '_'), opts, secondary_opts844 845- def _add_to_parser(self, parser, ctx):845+ def add_to_parser(self, parser, ctx):846 kwargs = {847 'dest': self.name,848 'nargs': self.nargs,849 }2 unmodified lines852 853 if self.is_flag:854 kwargs.pop('nargs', None)855 if self.is_bool_flag and self.secondary_opts:856- pos_opt = _optparse.Option(857- *self.opts, action=action + '_const', const=True, **kwargs)856+ parser.add_option(*self.opts, action=action + '_const',857+ const=True, **kwargs)858 kwargs.pop('default', None)859- neg_opt = _optparse.Option(860- *self.secondary_opts, action=action + '_const',861- const=False, **kwargs)862- pos_opt._negative_version = neg_opt863- parser.add_option(pos_opt)864- parser.add_option(neg_opt)859+ parser.add_option(*self.secondary_opts, action=action +860+ '_const', const=False, **kwargs)861 else:862 parser.add_option(*self.opts, action=action + '_const',863 const=self.flag_value,864 **kwargs)110 unmodified lines975 raise TypeError('Arguments take exactly one or two '976 'parameter declarations, got %d' % len(decls))977 return name.replace('-', '_'), [arg], []978 983- def _add_to_parser(self, parser, ctx):984- pass985-979 def get_usage_pieces(self, ctx):980 return [self.make_metavar()]981 982 def consume_value(self, ctx, opts, args):24 unmodified linesadded:click/parser.py+275 added
1+# -*- coding: utf-8 -*-2+"""3+ click.parser4+ ~~~~~~~~~~~~5+6+ This module started out as largely a copy paste from the stdlib's7+ optparse module with the features removed that we do not need from8+ optparse because we implement them in click on a higher level (for9+ instance type handling, help formatting and a lot more).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+from .exceptions import UsageError19+20+21+class Option(object):22+ ATTRS = ['action', 'type', 'dest', 'nargs', 'const', 'help',23+ 'metavar']24+ ACTIONS = ('store', 'store_const', 'append', 'append_const')25+ STORE_ACTIONS = ('store', 'store_const', 'append', 'append_const')26+ TYPED_ACTIONS = ('store', 'append')27+ TAKES_VALUE_ACTIONS = ('store', 'append')28+ CONST_ACTIONS = ('store_const', 'append_const')29+30+ def __init__(self, *opts, **attrs):31+ self._short_opts = []32+ self._long_opts = []33+34+ for opt in opts:35+ if len(opt) < 2:36+ raise TypeError(37+ 'invalid option string %r: '38+ 'must be at least two characters long' % opt)39+ elif len(opt) == 2:40+ if not (opt[0] == '-' and opt[1] != '-'):41+ raise TypeError(42+ 'invalid short option string %r: '43+ 'must be of the form -x, (x any non-dash char)' % opt)44+ self._short_opts.append(opt)45+ else:46+ if not (opt[:2] == '--' and opt[2] != '-'):47+ raise TypeError(48+ 'invalid long option string %r: '49+ 'must start with --, followed by non-dash' % opt)50+ self._long_opts.append(opt)51+52+ for attr in self.ATTRS:53+ if attr in attrs:54+ setattr(self, attr, attrs[attr])55+ del attrs[attr]56+ else:57+ setattr(self, attr, None)58+ if attrs:59+ attrs = sorted(attrs.keys())60+ raise TypeError('invalid keyword arguments: %s' %61+ ', '.join(attrs))62+63+ if self.action is None:64+ self.action = 'store'65+ if self.action in self.TYPED_ACTIONS:66+ if self.nargs is None:67+ self.nargs = 168+69+ @property70+ def takes_value(self):71+ return self.action in self.TAKES_VALUE_ACTIONS72+73+ def get_opt_string(self):74+ if self._long_opts:75+ return self._long_opts[0]76+ return self._short_opts[0]77+78+ def process(self, opt, value, opts, parser):79+ if self.action == 'store':80+ opts[self.dest] = value81+ elif self.action == 'store_const':82+ opts[self.dest] = self.const83+ elif self.action == 'append':84+ opts.setdefault(self.dest, []).append(value)85+ elif self.action == 'append_const':86+ opts.setdefault(self.dest, []).append(self.const)87+ else:88+ raise ValueError('unknown action %r' % self.action)89+90+91+class OptionParser(object):92+93+ def __init__(self, ctx):94+ self.ctx = ctx95+ self.allow_interspersed_args = True96+ self.option_list = []97+ self._short_opt = {}98+ self._long_opt = {}99+ self.rargs = None100+ self.largs = None101+ self.opts = None102+103+ def add_option(self, *args, **kwargs):104+ if isinstance(args[0], str):105+ option = Option(*args, **kwargs)106+ elif len(args) == 1 and not kwargs:107+ option = args[0]108+ if not isinstance(option, Option):109+ raise TypeError('not an Option instance: %r' % option)110+ else:111+ raise TypeError('invalid arguments')112+113+ self.option_list.append(option)114+ option.container = self115+ for opt in option._short_opts:116+ self._short_opt[opt] = option117+ for opt in option._long_opts:118+ self._long_opt[opt] = option119+120+ return option121+122+ def parse_args(self, args, opts=None):123+ rargs = args124+ if opts is None:125+ opts = {}126+ self.rargs = rargs127+ self.largs = largs = []128+ self.opts = opts129+130+ self._process_args(largs, rargs, opts)131+132+ args = largs + rargs133+ return opts, args134+135+ def _process_args(self, largs, rargs, opts):136+ while rargs:137+ arg = rargs[0]138+ # We handle bare '--' explicitly, and bare '-' is handled by the139+ # standard arg handler since the short arg case ensures that the140+ # len of the opt string is greater than 1.141+ if arg == '--':142+ del rargs[0]143+ return144+ elif arg[0:2] == '--':145+ # process a single long option (possibly with value(s))146+ self._process_long_opt(rargs, opts)147+ elif arg[:1] == '-' and len(arg) > 1:148+ # process a cluster of short options (possibly with149+ # value(s) for the last one only)150+ self._process_short_opts(rargs, opts)151+ elif self.allow_interspersed_args:152+ largs.append(arg)153+ del rargs[0]154+ else:155+ return156+157+ # Say this is the original argument list:158+ # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]159+ # ^160+ # (we are about to process arg(i)).161+ #162+ # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of163+ # [arg0, ..., arg(i-1)] (any options and their arguments will have164+ # been removed from largs).165+ #166+ # The while loop will usually consume 1 or more arguments per pass.167+ # If it consumes 1 (eg. arg is an option that takes no arguments),168+ # then after _process_arg() is done the situation is:169+ #170+ # largs = subset of [arg0, ..., arg(i)]171+ # rargs = [arg(i+1), ..., arg(N-1)]172+ #173+ # If allow_interspersed_args is false, largs will always be174+ # *empty* -- still a subset of [arg0, ..., arg(i-1)], but175+ # not a very interesting subset!176+177+ def _match_long_opt(self, opt):178+ # Is there an exact match?179+ if opt in self._long_opt:180+ return opt181+182+ # Isolate all words with s as a prefix.183+ possibilities = [word for word in self._long_opt184+ if word.startswith(opt)]185+186+ # No exact match, so there had better be just one possibility.187+ if not possibilities:188+ self.error('no such option: %s' % opt)189+ elif len(possibilities) == 1:190+ self.error('no such option: %s. Did you mean %s?' %191+ (opt, possibilities[0]))192+ return possibilities[0]193+ else:194+ # More than one possible completion: ambiguous prefix.195+ possibilities.sort()196+ self.error('no such option: %s. (Possible options: %s)'197+ % (opt, ', '.join(possibilities)))198+199+ def _process_long_opt(self, rargs, opts):200+ arg = rargs.pop(0)201+202+ # Value explicitly attached to arg? Pretend it's the next203+ # argument.204+ if '=' in arg:205+ opt, next_arg = arg.split('=', 1)206+ rargs.insert(0, next_arg)207+ had_explicit_value = True208+ else:209+ opt = arg210+ had_explicit_value = False211+212+ opt = self._match_long_opt(opt)213+ option = self._long_opt[opt]214+ if option.takes_value:215+ nargs = option.nargs216+ if len(rargs) < nargs:217+ if nargs == 1:218+ self.error('%s option requires an argument' % opt)219+ else:220+ self.error('%s option requires %d arguments' % (opt, nargs))221+ elif nargs == 1:222+ value = rargs.pop(0)223+ else:224+ value = tuple(rargs[0:nargs])225+ del rargs[0:nargs]226+227+ elif had_explicit_value:228+ self.error('%s option does not take a value' % opt)229+230+ else:231+ value = None232+233+ option.process(opt, value, opts, self)234+235+ def _process_short_opts(self, rargs, opts):236+ arg = rargs.pop(0)237+ stop = False238+ i = 1239+ for ch in arg[1:]:240+ opt = '-' + ch241+ option = self._short_opt.get(opt)242+ i += 1 # we have consumed a character243+244+ if not option:245+ self.error('no such option: %s' % opt)246+ if option.takes_value:247+ # Any characters left in arg? Pretend they're the248+ # next arg, and stop consuming characters of arg.249+ if i < len(arg):250+ rargs.insert(0, arg[i:])251+ stop = True252+253+ nargs = option.nargs254+ if len(rargs) < nargs:255+ if nargs == 1:256+ self.error('%s option requires an argument' % opt)257+ else:258+ self.error('%s option requires %d arguments' %259+ (opt, nargs))260+ elif nargs == 1:261+ value = rargs.pop(0)262+ else:263+ value = tuple(rargs[0:nargs])264+ del rargs[0:nargs]265+266+ else:267+ value = None268+269+ option.process(opt, value, opts, self)270+271+ if stop:272+ break273+274+ def error(self, msg):275+ raise UsageError(msg, self.ctx)