Remove name annotation for cmdutils.register.

See #637.
This commit is contained in:
Florian Bruhin 2015-04-20 22:25:27 +02:00
parent b805f903c9
commit 9ee74253e4
4 changed files with 26 additions and 41 deletions

View File

@ -397,10 +397,12 @@ then automatically checked. Possible values:
e.g. `('foo', 'bar')` or `(int, 'foo')`. e.g. `('foo', 'bar')` or `(int, 'foo')`.
* `flag`: The flag to be used, as 1-char string (default: First char of the * `flag`: The flag to be used, as 1-char string (default: First char of the
long name). long name).
* `name`: The long name to be used, as string (default: Name of the parameter).
* `nargs`: Gets passed to argparse, see * `nargs`: Gets passed to argparse, see
https://docs.python.org/dev/library/argparse.html#nargs[its documentation]. https://docs.python.org/dev/library/argparse.html#nargs[its documentation].
The name of an argument will always be the parameter name, with any trailing
underscores stripped.
[[handling-urls]] [[handling-urls]]
Handling URLs Handling URLs
~~~~~~~~~~~~~ ~~~~~~~~~~~~~

View File

@ -918,7 +918,7 @@ class DownloadManager(QAbstractListModel):
@cmdutils.register(instance='download-manager', scope='window', @cmdutils.register(instance='download-manager', scope='window',
count='count') count='count')
def download_remove(self, all_: {'name': 'all'}=False, count=0): def download_remove(self, all_=False, count=0):
"""Remove the last/[count]th download from the list. """Remove the last/[count]th download from the list.
Args: Args:

View File

@ -49,7 +49,6 @@ class Command:
flags_with_args: A list of flags which take an argument. flags_with_args: A list of flags which take an argument.
no_cmd_split: If true, ';;' to split sub-commands is ignored. no_cmd_split: If true, ';;' to split sub-commands is ignored.
_type_conv: A mapping of conversion functions for arguments. _type_conv: A mapping of conversion functions for arguments.
_name_conv: A mapping of argument names to parameter names.
_needs_js: Whether the command needs javascript enabled _needs_js: Whether the command needs javascript enabled
_modes: The modes the command can be executed in. _modes: The modes the command can be executed in.
_not_modes: The modes the command can not be executed in. _not_modes: The modes the command can not be executed in.
@ -62,7 +61,7 @@ class Command:
""" """
AnnotationInfo = collections.namedtuple('AnnotationInfo', AnnotationInfo = collections.namedtuple('AnnotationInfo',
['kwargs', 'type', 'name', 'flag']) ['kwargs', 'type', 'flag'])
def __init__(self, *, handler, name, instance=None, maxsplit=None, def __init__(self, *, handler, name, instance=None, maxsplit=None,
hide=False, completion=None, modes=None, not_modes=None, hide=False, completion=None, modes=None, not_modes=None,
@ -115,7 +114,6 @@ class Command:
self.desc = None self.desc = None
self.flags_with_args = [] self.flags_with_args = []
self._type_conv = {} self._type_conv = {}
self._name_conv = {}
count = self._inspect_func() count = self._inspect_func()
if self.completion is not None and len(self.completion) > count: if self.completion is not None and len(self.completion) > count:
raise ValueError("Got {} completions, but only {} " raise ValueError("Got {} completions, but only {} "
@ -177,18 +175,6 @@ class Command:
type_conv[param.name] = argparser.multitype_conv(typ) type_conv[param.name] = argparser.multitype_conv(typ)
return type_conv return type_conv
def _get_nameconv(self, param, annotation_info):
"""Get a dict with a name conversion for the parameter.
Args:
param: The inspect.Parameter to handle.
annotation_info: The AnnotationInfo tuple for the parameter.
"""
d = {}
if annotation_info.name is not None:
d[param.name] = annotation_info.name
return d
def _inspect_special_param(self, param): def _inspect_special_param(self, param):
"""Check if the given parameter is a special one. """Check if the given parameter is a special one.
@ -244,8 +230,6 @@ class Command:
kwargs = self._param_to_argparse_kwargs(param, annotation_info) kwargs = self._param_to_argparse_kwargs(param, annotation_info)
args = self._param_to_argparse_args(param, annotation_info) args = self._param_to_argparse_args(param, annotation_info)
self._type_conv.update(self._get_typeconv(param, typ)) self._type_conv.update(self._get_typeconv(param, typ))
self._name_conv.update(
self._get_nameconv(param, annotation_info))
callsig = debug_utils.format_call( callsig = debug_utils.format_call(
self.parser.add_argument, args, kwargs, self.parser.add_argument, args, kwargs,
full=False) full=False)
@ -303,8 +287,8 @@ class Command:
A list of args. A list of args.
""" """
args = [] args = []
name = annotation_info.name or param.name name = param.name.rstrip('_')
shortname = annotation_info.flag or param.name[0] shortname = annotation_info.flag or name[0]
if len(shortname) != 1: if len(shortname) != 1:
raise ValueError("Flag '{}' of parameter {} (command {}) must be " raise ValueError("Flag '{}' of parameter {} (command {}) must be "
"exactly 1 char!".format(shortname, name, "exactly 1 char!".format(shortname, name,
@ -337,7 +321,7 @@ class Command:
flag: The short name/flag if overridden. flag: The short name/flag if overridden.
name: The long name if overridden. name: The long name if overridden.
""" """
info = {'kwargs': {}, 'type': None, 'flag': None, 'name': None} info = {'kwargs': {}, 'type': None, 'flag': None}
if param.annotation is not inspect.Parameter.empty: if param.annotation is not inspect.Parameter.empty:
log.commands.vdebug("Parsing annotation {}".format( log.commands.vdebug("Parsing annotation {}".format(
param.annotation)) param.annotation))
@ -423,7 +407,7 @@ class Command:
def _get_param_name_and_value(self, param): def _get_param_name_and_value(self, param):
"""Get the converted name and value for an inspect.Parameter.""" """Get the converted name and value for an inspect.Parameter."""
name = self._name_conv.get(param.name, param.name) name = param.name.rstrip('_')
value = getattr(self.namespace, name) value = getattr(self.namespace, name)
if param.name in self._type_conv: if param.name in self._type_conv:
# We convert enum types after getting the values from # We convert enum types after getting the values from

View File

@ -582,9 +582,8 @@ class ConfigManager(QObject):
@cmdutils.register(name='set', instance='config', win_id='win_id', @cmdutils.register(name='set', instance='config', win_id='win_id',
completion=[Completion.section, Completion.option, completion=[Completion.section, Completion.option,
Completion.value]) Completion.value])
def set_command(self, win_id, sectname: {'name': 'section'}=None, def set_command(self, win_id, section_=None, option=None, value=None,
optname: {'name': 'option'}=None, value=None, temp=False, temp=False, print_=False):
print_val: {'name': 'print'}=False):
"""Set an option. """Set an option.
If the option name ends with '?', the value of the option is shown If the option name ends with '?', the value of the option is shown
@ -597,38 +596,38 @@ class ConfigManager(QObject):
Wrapper for self.set() to output exceptions in the status bar. Wrapper for self.set() to output exceptions in the status bar.
Args: Args:
sectname: The section where the option is in. section_: The section where the option is in.
optname: The name of the option. option: The name of the option.
value: The value to set. value: The value to set.
temp: Set value temporarily. temp: Set value temporarily.
print_val: Print the value after setting. print_: Print the value after setting.
""" """
if sectname is not None and optname is None: if section_ is not None and option is None:
raise cmdexc.CommandError( raise cmdexc.CommandError(
"set: Either both section and option have to be given, or " "set: Either both section and option have to be given, or "
"neither!") "neither!")
if sectname is None and optname is None: if section_ is None and option is None:
tabbed_browser = objreg.get('tabbed-browser', scope='window', tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=win_id) window=win_id)
tabbed_browser.openurl(QUrl('qute:settings'), newtab=False) tabbed_browser.openurl(QUrl('qute:settings'), newtab=False)
return return
if optname.endswith('?'): if option.endswith('?'):
optname = optname[:-1] option = option[:-1]
print_val = True print_ = True
else: else:
try: try:
if optname.endswith('!') and value is None: if option.endswith('!') and value is None:
val = self.get(sectname, optname[:-1]) val = self.get(section_, option[:-1])
layer = 'temp' if temp else 'conf' layer = 'temp' if temp else 'conf'
if isinstance(val, bool): if isinstance(val, bool):
self.set(layer, sectname, optname[:-1], str(not val)) self.set(layer, section_, option[:-1], str(not val))
else: else:
raise cmdexc.CommandError( raise cmdexc.CommandError(
"set: Attempted inversion of non-boolean value.") "set: Attempted inversion of non-boolean value.")
elif value is not None: elif value is not None:
layer = 'temp' if temp else 'conf' layer = 'temp' if temp else 'conf'
self.set(layer, sectname, optname, value) self.set(layer, section_, option, value)
else: else:
raise cmdexc.CommandError("set: The following arguments " raise cmdexc.CommandError("set: The following arguments "
"are required: value") "are required: value")
@ -636,10 +635,10 @@ class ConfigManager(QObject):
raise cmdexc.CommandError("set: {} - {}".format( raise cmdexc.CommandError("set: {} - {}".format(
e.__class__.__name__, e)) e.__class__.__name__, e))
if print_val: if print_:
val = self.get(sectname, optname, transformed=False) val = self.get(section_, option, transformed=False)
message.info(win_id, "{} {} = {}".format( message.info(win_id, "{} {} = {}".format(
sectname, optname, val), immediately=True) section_, option, val), immediately=True)
def set(self, layer, sectname, optname, value, validate=True): def set(self, layer, sectname, optname, value, validate=True):
"""Set an option. """Set an option.