Merge pull request #433 from sampsyo/argparse

Add vararg_callback utility function to beets.ui
This commit is contained in:
Pedro Silva 2013-10-22 12:50:07 -07:00
commit 0eb70ebfa5
3 changed files with 41 additions and 0 deletions

View file

@ -695,6 +695,41 @@ class SubcommandsOptionParser(optparse.OptionParser):
return options, subcommand, suboptions, subargs
def vararg_callback(option, opt_str, value, parser):
"""Callback for an option with variable arguments.
Manually collect arguments right of a callback-action
option (ie. with action="callback"), and add the resulting
list to the destination var.
Usage:
parser.add_option("-c", "--callback", dest="vararg_attr",
action="callback", callback=vararg_callback)
Details:
http://docs.python.org/2/library/optparse.html#callback-example-6-variable-arguments
"""
assert value is None
value = []
def floatable(str):
try:
float(str)
return True
except ValueError:
return False
for arg in parser.rargs:
# stop on --foo like options
if arg[:2] == "--" and len(arg) > 2:
break
# stop on -a, but not on -3 or -3.0
if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
break
value.append(arg)
del parser.rargs[:len(value)]
setattr(parser.values, option.dest, value)
# The root parser and its main function.
def _raw_main(args):

View file

@ -6,6 +6,10 @@ Changelog
New features:
* :ref:`add_subcommands`: Added ``optparse`` callback utility function, allowing
plugin developers to add options with ``action=callback`` and
``callback=beets.ui.varargs_callback`` and a variable number of arguments.
* :doc:`/plugins/duplicates`: The new ``keys`` option allows you to specify
arbitrary fields over which to consider potential duplicates.

View file

@ -44,6 +44,8 @@ containing your plugin).
.. _virtualenv: http://pypi.python.org/pypi/virtualenv
.. _add_subcommands:
Add Commands to the CLI
^^^^^^^^^^^^^^^^^^^^^^^