Debian Codegraph @

docs/dev/plugins/commands.rst

raw
1 .. _add_subcommands:
2
3 Add Commands to the CLI
4 =======================
5
6 Plugins can add new subcommands to the ``beet`` command-line interface. Define
7 the plugin class' ``commands()`` method to return a list of ``Subcommand``
8 objects. (The ``Subcommand`` class is defined in the ``beets.ui`` module.)
9 Here's an example plugin that adds a simple command:
10
11 .. code-block:: python
12
13 from beets.plugins import BeetsPlugin
14 from beets.ui import Subcommand
15
16 my_super_command = Subcommand("super", help="do something super")
17
18
19 def say_hi(lib, opts, args):
20 print("Hello everybody! I'm a plugin!")
21
22
23 my_super_command.func = say_hi
24
25
26 class SuperPlug(BeetsPlugin):
27 def commands(self):
28 return [my_super_command]
29
30 To make a subcommand, invoke the constructor like so: ``Subcommand(name, parser,
31 help, aliases)``. The ``name`` parameter is the only required one and should
32 just be the name of your command. ``parser`` can be an `OptionParser instance`_,
33 but it defaults to an empty parser (you can extend it later). ``help`` is a
34 description of your command, and ``aliases`` is a list of shorthand versions of
35 your command name.
36
37 .. _optionparser instance: https://docs.python.org/3/library/optparse.html
38
39 You'll need to add a function to your command by saying ``mycommand.func =
40 myfunction``. This function should take the following parameters: ``lib`` (a
41 beets ``Library`` object) and ``opts`` and ``args`` (command-line options and
42 arguments as returned by OptionParser.parse_args_).
43
44 .. _optionparser.parse_args: https://docs.python.org/3/library/optparse.html#parsing-arguments
45
46 The function should use any of the utility functions defined in ``beets.ui``.
47 Try running ``pydoc beets.ui`` to see what's available.
48
49 You can add command-line options to your new command using the ``parser`` member
50 of the ``Subcommand`` class, which is a ``CommonOptionsParser`` instance. Just
51 use it like you would a normal ``OptionParser`` in an independent script. Note
52 that it offers several methods to add common options: ``--album``, ``--path``
53 and ``--format``. This feature is versatile and extensively documented, try
54 ``pydoc beets.ui.CommonOptionsParser`` for more information.