2010-03-18 07:32:47 +01:00
|
|
|
# Copyright (C) 2009-2010 Alexander Cherniuk <ts33kr@gmail.com>
|
2009-10-02 22:57:11 +02:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
"""
|
2010-02-26 11:35:09 +01:00
|
|
|
The module contains routines to parse command arguments and map them to
|
2018-06-22 00:47:29 +02:00
|
|
|
the command handler's positional and keyword arguments.
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
Mapping is done in two stages: 1) parse arguments into positional
|
|
|
|
arguments and options; 2) adapt them to the specific command handler
|
|
|
|
according to the command properties.
|
2009-10-02 22:57:11 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
import re
|
|
|
|
from operator import itemgetter
|
|
|
|
|
2017-06-13 23:58:06 +02:00
|
|
|
from gajim.command_system.errors import DefinitionError, CommandError
|
2009-10-02 22:57:11 +02:00
|
|
|
|
|
|
|
# Quite complex piece of regular expression logic to parse options and
|
|
|
|
# arguments. Might need some tweaking along the way.
|
|
|
|
ARG_PATTERN = re.compile(r'(\'|")?(?P<body>(?(1).+?|\S+))(?(1)\1)')
|
|
|
|
OPT_PATTERN = re.compile(r'(?<!\w)--?(?P<key>[\w-]+)(?:(?:=|\s)(\'|")?(?P<value>(?(2)[^-]+?|[^-\s]+))(?(2)\2))?')
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Option keys needs to be encoded to a specific encoding as Python does
|
2018-06-22 00:47:29 +02:00
|
|
|
# not allow to expand dictionary with raw Unicode strings as keys from a
|
2010-02-26 11:35:09 +01:00
|
|
|
# **kwargs.
|
2009-10-02 22:57:11 +02:00
|
|
|
KEY_ENCODING = 'UTF-8'
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Defines how complete representation of command usage (generated based
|
|
|
|
# on command handler argument specification) will be rendered.
|
2009-10-02 22:57:11 +02:00
|
|
|
USAGE_PATTERN = 'Usage: %s %s'
|
|
|
|
|
|
|
|
def parse_arguments(arguments):
|
|
|
|
"""
|
2010-02-26 11:35:09 +01:00
|
|
|
Simple yet effective and sufficient in most cases parser which
|
|
|
|
parses command arguments and returns them as two lists.
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
First list represents positional arguments as (argument, position),
|
|
|
|
and second representing options as (key, value, position) tuples,
|
|
|
|
where position is a (start, end) span tuple of where it was found in
|
|
|
|
the string.
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
Options may be given in --long or -short format. As --option=value
|
|
|
|
or --option value or -option value. Keys without values will get
|
|
|
|
None as value.
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
Arguments and option values that contain spaces may be given as 'one
|
|
|
|
two three' or "one two three"; that is between single or double
|
|
|
|
quotes.
|
2009-10-02 22:57:11 +02:00
|
|
|
"""
|
|
|
|
args, opts = [], []
|
|
|
|
|
2013-01-02 13:54:02 +01:00
|
|
|
def intersects_opts(given_start, given_end):
|
2009-10-02 22:57:11 +02:00
|
|
|
"""
|
|
|
|
Check if given span intersects with any of options.
|
|
|
|
"""
|
2018-09-17 21:11:45 +02:00
|
|
|
for _key, _value, (start, end) in opts:
|
2009-10-02 22:57:11 +02:00
|
|
|
if given_start >= start and given_end <= end:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2013-01-02 13:54:02 +01:00
|
|
|
def intersects_args(given_start, given_end):
|
2009-10-02 22:57:11 +02:00
|
|
|
"""
|
|
|
|
Check if given span intersects with any of arguments.
|
|
|
|
"""
|
2018-09-17 21:11:45 +02:00
|
|
|
for _arg, (start, end) in args:
|
2009-10-02 22:57:11 +02:00
|
|
|
if given_start >= start and given_end <= end:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
for match in re.finditer(OPT_PATTERN, arguments):
|
|
|
|
if match:
|
|
|
|
key = match.group('key')
|
|
|
|
value = match.group('value') or None
|
|
|
|
position = match.span()
|
|
|
|
opts.append((key, value, position))
|
|
|
|
|
|
|
|
for match in re.finditer(ARG_PATTERN, arguments):
|
|
|
|
if match:
|
|
|
|
body = match.group('body')
|
|
|
|
position = match.span()
|
|
|
|
args.append((body, position))
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Primitive but sufficiently effective way of disposing of
|
|
|
|
# conflicted sectors. Remove any arguments that intersect with
|
|
|
|
# options.
|
2009-10-02 22:57:11 +02:00
|
|
|
for arg, position in args[:]:
|
2013-01-02 13:54:02 +01:00
|
|
|
if intersects_opts(*position):
|
2009-10-02 22:57:11 +02:00
|
|
|
args.remove((arg, position))
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Primitive but sufficiently effective way of disposing of
|
|
|
|
# conflicted sectors. Remove any options that intersect with
|
|
|
|
# arguments.
|
2009-10-02 22:57:11 +02:00
|
|
|
for key, value, position in opts[:]:
|
2013-01-02 13:54:02 +01:00
|
|
|
if intersects_args(*position):
|
2009-10-02 22:57:11 +02:00
|
|
|
opts.remove((key, value, position))
|
|
|
|
|
|
|
|
return args, opts
|
|
|
|
|
|
|
|
def adapt_arguments(command, arguments, args, opts):
|
|
|
|
"""
|
2010-02-26 11:35:09 +01:00
|
|
|
Adapt args and opts got from the parser to a specific handler by
|
|
|
|
means of arguments specified on command definition. That is
|
|
|
|
transform them to *args and **kwargs suitable for passing to a
|
|
|
|
command handler.
|
|
|
|
|
|
|
|
Dashes (-) in the option names will be converted to underscores. So
|
|
|
|
you can map --one-more-option to a one_more_option=None.
|
|
|
|
|
|
|
|
If the initial value of a keyword argument is a boolean (False in
|
|
|
|
most cases) - then this option will be treated as a switch, that is
|
|
|
|
an option which does not take an argument. If a switch is followed
|
|
|
|
by an argument - then this argument will be treated just like a
|
|
|
|
normal positional argument.
|
2009-10-02 22:57:11 +02:00
|
|
|
"""
|
2018-09-17 21:11:45 +02:00
|
|
|
spec_args, spec_kwargs, var_args, _var_kwargs = command.extract_specification()
|
2009-10-02 22:57:11 +02:00
|
|
|
norm_kwargs = dict(spec_kwargs)
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Quite complex piece of neck-breaking logic to extract raw
|
|
|
|
# arguments if there is more, then one positional argument specified
|
|
|
|
# by the command. In case if it's just one argument which is the
|
|
|
|
# collector - this is fairly easy. But when it's more then one
|
|
|
|
# argument - the neck-breaking logic of how to retrieve residual
|
|
|
|
# arguments as a raw, all in one piece string, kicks in.
|
2009-10-02 22:57:11 +02:00
|
|
|
if command.raw:
|
|
|
|
if arguments:
|
|
|
|
spec_fix = 1 if command.source else 0
|
|
|
|
spec_len = len(spec_args) - spec_fix
|
|
|
|
arguments_end = len(arguments) - 1
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# If there are any optional arguments given they should be
|
2018-06-22 00:47:29 +02:00
|
|
|
# either an unquoted positional argument or part of the raw
|
2010-02-26 11:35:09 +01:00
|
|
|
# argument. So we find all optional arguments that can
|
|
|
|
# possibly be unquoted argument and append them as is to the
|
|
|
|
# args.
|
2009-10-02 22:57:11 +02:00
|
|
|
for key, value, (start, end) in opts[:spec_len]:
|
|
|
|
if value:
|
|
|
|
end -= len(value) + 1
|
|
|
|
args.append((arguments[start:end], (start, end)))
|
|
|
|
args.append((value, (end, end + len(value) + 1)))
|
|
|
|
else:
|
|
|
|
args.append((arguments[start:end], (start, end)))
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# We need in-place sort here because after manipulations
|
|
|
|
# with options order of arguments might be wrong and we just
|
|
|
|
# can't have more complex logic to not let that happen.
|
2009-10-02 22:57:11 +02:00
|
|
|
args.sort(key=itemgetter(1))
|
|
|
|
|
|
|
|
if spec_len > 1:
|
|
|
|
try:
|
2018-09-17 21:11:45 +02:00
|
|
|
_stopper, (start, end) = args[spec_len - 2]
|
2009-10-02 22:57:11 +02:00
|
|
|
except IndexError:
|
2012-08-11 12:59:05 +02:00
|
|
|
raise CommandError(_("Missing arguments"), command)
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# The essential point of the whole play. After
|
2018-06-22 00:47:29 +02:00
|
|
|
# boundaries are being determined (supposedly correct)
|
2010-02-26 11:35:09 +01:00
|
|
|
# we separate raw part from the rest of arguments, which
|
|
|
|
# should be normally processed.
|
2009-10-02 22:57:11 +02:00
|
|
|
raw = arguments[end:]
|
|
|
|
raw = raw.strip() or None
|
|
|
|
|
|
|
|
if not raw and not command.empty:
|
2012-08-11 12:59:05 +02:00
|
|
|
raise CommandError(_("Missing arguments"), command)
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Discard residual arguments and all of the options as
|
|
|
|
# raw command does not support options and if an option
|
|
|
|
# is given it is rather a part of a raw argument.
|
2009-10-02 22:57:11 +02:00
|
|
|
args = args[:spec_len - 1]
|
|
|
|
opts = []
|
|
|
|
|
|
|
|
args.append((raw, (end, arguments_end)))
|
|
|
|
else:
|
2018-06-22 00:47:29 +02:00
|
|
|
# Substitute all of the arguments with only one, which
|
2010-02-26 11:35:09 +01:00
|
|
|
# contain raw and unprocessed arguments as a string. And
|
|
|
|
# discard all the options, as raw command does not
|
|
|
|
# support them.
|
2009-10-02 22:57:11 +02:00
|
|
|
args = [(arguments, (0, arguments_end))]
|
|
|
|
opts = []
|
|
|
|
else:
|
|
|
|
if command.empty:
|
|
|
|
args.append((None, (0, 0)))
|
|
|
|
else:
|
2012-08-11 12:59:05 +02:00
|
|
|
raise CommandError(_("Missing arguments"), command)
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# The first stage of transforming options we have got to a format
|
|
|
|
# that can be used to associate them with declared keyword
|
|
|
|
# arguments. Substituting dashes (-) in their names with
|
|
|
|
# underscores (_).
|
2009-10-02 22:57:11 +02:00
|
|
|
for index, (key, value, position) in enumerate(opts):
|
|
|
|
if '-' in key:
|
|
|
|
opts[index] = (key.replace('-', '_'), value, position)
|
|
|
|
|
2018-06-22 00:47:29 +02:00
|
|
|
# The second stage of transforming options to an associable state.
|
2010-02-26 11:35:09 +01:00
|
|
|
# Expanding short, one-letter options to a verbose ones, if
|
2018-06-22 00:47:29 +02:00
|
|
|
# corresponding opt-in has been given.
|
2010-08-05 13:06:36 +02:00
|
|
|
if command.expand:
|
2009-10-02 22:57:11 +02:00
|
|
|
expanded = []
|
2018-09-17 21:11:45 +02:00
|
|
|
for spec_key in norm_kwargs.keys():
|
2009-10-02 22:57:11 +02:00
|
|
|
letter = spec_key[0] if len(spec_key) > 1 else None
|
|
|
|
if letter and letter not in expanded:
|
|
|
|
for index, (key, value, position) in enumerate(opts):
|
|
|
|
if key == letter:
|
|
|
|
expanded.append(letter)
|
|
|
|
opts[index] = (spec_key, value, position)
|
|
|
|
break
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Detect switches and set their values accordingly. If any of them
|
|
|
|
# carries a value - append it to args.
|
2009-10-02 22:57:11 +02:00
|
|
|
for index, (key, value, position) in enumerate(opts):
|
2013-01-02 13:54:02 +01:00
|
|
|
if isinstance(norm_kwargs.get(key), bool):
|
2009-10-02 22:57:11 +02:00
|
|
|
opts[index] = (key, True, position)
|
|
|
|
if value:
|
|
|
|
args.append((value, position))
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Sorting arguments and options (just to be sure) in regarding to
|
|
|
|
# their positions in the string.
|
2009-10-02 22:57:11 +02:00
|
|
|
args.sort(key=itemgetter(1))
|
|
|
|
opts.sort(key=itemgetter(2))
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Stripping down position information supplied with arguments and
|
|
|
|
# options as it won't be needed again.
|
2013-01-27 19:51:11 +01:00
|
|
|
args = list(map(lambda t: t[0], args))
|
|
|
|
opts = list(map(lambda t: (t[0], t[1]), opts))
|
2009-10-02 22:57:11 +02:00
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# If command has extra option enabled - collect all extra arguments
|
|
|
|
# and pass them to a last positional argument command defines as a
|
|
|
|
# list.
|
2009-10-02 22:57:11 +02:00
|
|
|
if command.extra:
|
|
|
|
if not var_args:
|
|
|
|
spec_fix = 1 if not command.source else 2
|
|
|
|
spec_len = len(spec_args) - spec_fix
|
|
|
|
extra = args[spec_len:]
|
|
|
|
args = args[:spec_len]
|
|
|
|
args.append(extra)
|
|
|
|
else:
|
|
|
|
raise DefinitionError("Can not have both, extra and *args")
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Detect if positional arguments overlap keyword arguments. If so
|
|
|
|
# and this is allowed by command options - then map them directly to
|
2018-06-22 00:47:29 +02:00
|
|
|
# their options, so they can get proper further processing.
|
2009-10-02 22:57:11 +02:00
|
|
|
spec_fix = 1 if command.source else 0
|
|
|
|
spec_len = len(spec_args) - spec_fix
|
|
|
|
if len(args) > spec_len:
|
|
|
|
if command.overlap:
|
|
|
|
overlapped = args[spec_len:]
|
|
|
|
args = args[:spec_len]
|
2018-09-17 21:11:45 +02:00
|
|
|
for arg, spec_key, _spec_value in zip(overlapped, spec_kwargs):
|
2009-10-02 22:57:11 +02:00
|
|
|
opts.append((spec_key, arg))
|
|
|
|
else:
|
2017-02-04 23:29:45 +01:00
|
|
|
raise CommandError(_("Too many arguments"), command)
|
2009-10-02 22:57:11 +02:00
|
|
|
|
|
|
|
# Detect every switch and ensure it will not receive any arguments.
|
|
|
|
# Normally this does not happen unless overlapping is enabled.
|
|
|
|
for key, value in opts:
|
|
|
|
initial = norm_kwargs.get(key)
|
2013-01-02 13:54:02 +01:00
|
|
|
if isinstance(initial, bool):
|
|
|
|
if not isinstance(value, bool):
|
2009-10-02 22:57:11 +02:00
|
|
|
raise CommandError("%s: Switch can not take an argument" % key, command)
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Inject the source arguments as a string as a first argument, if
|
|
|
|
# command has enabled the corresponding option.
|
2009-10-02 22:57:11 +02:00
|
|
|
if command.source:
|
|
|
|
args.insert(0, arguments)
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Return *args and **kwargs in the form suitable for passing to a
|
|
|
|
# command handler and being expanded.
|
2009-10-02 22:57:11 +02:00
|
|
|
return tuple(args), dict(opts)
|
|
|
|
|
|
|
|
def generate_usage(command, complete=True):
|
|
|
|
"""
|
2010-02-26 11:35:09 +01:00
|
|
|
Extract handler's arguments specification and wrap them in a
|
|
|
|
human-readable format usage information. If complete is given - then
|
2018-06-22 00:47:29 +02:00
|
|
|
USAGE_PATTERN will be used to render the specification completely.
|
2009-10-02 22:57:11 +02:00
|
|
|
"""
|
|
|
|
spec_args, spec_kwargs, var_args, var_kwargs = command.extract_specification()
|
|
|
|
|
2018-06-22 00:47:29 +02:00
|
|
|
# Remove some special positional arguments from the specification,
|
2010-02-26 11:35:09 +01:00
|
|
|
# but store their names so they can be used for usage info
|
|
|
|
# generation.
|
2018-09-17 21:11:45 +02:00
|
|
|
_sp_source = spec_args.pop(0) if command.source else None
|
2009-10-02 22:57:11 +02:00
|
|
|
sp_extra = spec_args.pop() if command.extra else None
|
|
|
|
|
|
|
|
kwargs = []
|
|
|
|
letters = []
|
|
|
|
|
|
|
|
for key, value in spec_kwargs:
|
|
|
|
letter = key[0]
|
|
|
|
key = key.replace('_', '-')
|
|
|
|
|
2013-01-02 13:54:02 +01:00
|
|
|
if isinstance(value, bool):
|
2009-10-02 22:57:11 +02:00
|
|
|
value = str()
|
|
|
|
else:
|
|
|
|
value = '=%s' % value
|
|
|
|
|
|
|
|
if letter not in letters:
|
|
|
|
kwargs.append('-(-%s)%s%s' % (letter, key[1:], value))
|
|
|
|
letters.append(letter)
|
|
|
|
else:
|
|
|
|
kwargs.append('--%s%s' % (key, value))
|
|
|
|
|
|
|
|
usage = str()
|
|
|
|
args = str()
|
|
|
|
|
|
|
|
if command.raw:
|
|
|
|
spec_len = len(spec_args) - 1
|
|
|
|
if spec_len:
|
|
|
|
args += ('<%s>' % ', '.join(spec_args[:spec_len])) + ' '
|
|
|
|
args += ('(|%s|)' if command.empty else '|%s|') % spec_args[-1]
|
|
|
|
else:
|
|
|
|
if spec_args:
|
|
|
|
args += '<%s>' % ', '.join(spec_args)
|
|
|
|
if var_args or sp_extra:
|
|
|
|
args += (' ' if spec_args else str()) + '<<%s>>' % (var_args or sp_extra)
|
|
|
|
|
|
|
|
usage += args
|
|
|
|
|
|
|
|
if kwargs or var_kwargs:
|
|
|
|
if kwargs:
|
|
|
|
usage += (' ' if args else str()) + '[%s]' % ', '.join(kwargs)
|
|
|
|
if var_kwargs:
|
|
|
|
usage += (' ' if args else str()) + '[[%s]]' % var_kwargs
|
|
|
|
|
2010-02-26 11:35:09 +01:00
|
|
|
# Native name will be the first one if it is included. Otherwise,
|
|
|
|
# names will be in the order they were specified.
|
2009-10-02 22:57:11 +02:00
|
|
|
if len(command.names) > 1:
|
|
|
|
names = '%s (%s)' % (command.first_name, ', '.join(command.names[1:]))
|
|
|
|
else:
|
|
|
|
names = command.first_name
|
|
|
|
|
|
|
|
return USAGE_PATTERN % (names, usage) if complete else usage
|