summaryrefslogtreecommitdiff
path: root/docs/features/modular_commands.rst
blob: 82298c8f73c237fcd0d6973eda76dcabc86b1a13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
Modular Commands
================

Overview
--------

Cmd2 also enables developers to modularize their command definitions into Command Sets. Command sets represent
a logical grouping of commands within an cmd2 application. By default, all CommandSets will be discovered and loaded
automatically when the cmd2.Cmd class is instantiated with this mixin. This also enables the developer to
dynamically add/remove commands from the cmd2 application. This could be useful for loadable plugins that
add additional capabilities.

Features
~~~~~~~~

* Modular Command Sets - Commands can be broken into separate modules rather than in one god class holding all commands.
* Automatic Command Discovery - In your application, merely defining and importing a CommandSet is sufficient for
  cmd2 to discover and load your command. No manual registration is necessary.
* Dynamically Loadable/Unloadable Commands - Command functions and CommandSets can both be loaded and unloaded
  dynamically during application execution. This can enable features such as dynamically loaded modules that
  add additional commands.
* Sub-command Injection - Sub-commands can be defined separately from the base command. This allows for a more
  action-centric instead of object-centric command system while still organizing your code and handlers around the
  objects being managed.

See the examples for more details: https://github.com/python-cmd2/cmd2/tree/master/plugins/command_sets/examples


Defining Commands
-----------------

Command Sets
~~~~~~~~~~~~~

CommandSets group multiple commands together. The plugin will inspect functions within a ``CommandSet``
using the same rules as when they're defined in ``cmd2.Cmd``. Commands must be prefixed with ``do_``, help
functions with ``help_``, and completer functions with ``complete_``.

A new decorator ``with_default_category`` is provided to categorize all commands within a CommandSet in the
same command category.  Individual commands in a CommandSet may be override the default category by specifying a
specific category with ``cmd.with_category``.

CommandSet methods will always expect ``self``, and ``cmd2.Cmd`` as the first two parameters. The parameters that
follow will depend on the specific command decorator being used.

CommandSets will only be auto-loaded if the constructor takes no arguments.
If you need to provide constructor arguments, see :ref:`features/modular_commands:Manual CommandSet Construction`

.. code-block:: python

    import cmd2
    from cmd2 import CommandSet, with_default_category

    @with_default_category('My Category')
    class AutoLoadCommandSet(CommandSet):
        def __init__(self):
            super().__init__()

        def do_hello(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Hello')

        def do_world(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('World')

    class ExampleApp(cmd2.Cmd):
        """
        CommandSets are automatically loaded. Nothing needs to be done.
        """
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        def do_something(self, arg):
            self.poutput('this is the something command')


Manual CommandSet Construction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If a CommandSet class requires parameters to be provided to the constructor, you man manually construct
CommandSets and pass in the constructor to Cmd2.

.. code-block:: python

    import cmd2
    from cmd2 import CommandSet, with_default_category

    @with_default_category('My Category')
    class CustomInitCommandSet(CommandSet):
        def __init__(self, arg1, arg2):
            super().__init__()

            self._arg1 = arg1
            self._arg2 = arg2

        def do_show_arg1(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Arg1: ' + self._arg1)

        def do_show_arg2(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Arg2: ' + self._arg2)

    class ExampleApp(cmd2.Cmd):
        """
        CommandSets with constructor parameters are provided in the constructor
        """
        def __init__(self, *args, **kwargs):
            # gotta have this or neither the plugin or cmd2 will initialize
            super().__init__(*args, **kwargs)

        def do_something(self, arg):
            self.last_result = 5
            self.poutput('this is the something command')


    def main():
        my_commands = CustomInitCommandSet(1, 2)
        app = ExampleApp(command_sets=[my_commands])
        app.cmdloop()


Dynamic Commands
~~~~~~~~~~~~~~~~

You man also dynamically load and unload commands by installing and removing CommandSets at runtime. For example,
if you could support runtime loadable plugins or add/remove commands based on your state.

You may need to disable command auto-loading if you need dynamically load commands at runtime.

.. code-block:: python

    import argparse
    import cmd2
    from cmd2 import CommandSet, with_argparser, with_category, with_default_category


    @with_default_category('Fruits')
    class LoadableFruits(CommandSet):
        def __init__(self):
            super().__init__()

        def do_apple(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Apple')

        def do_banana(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Banana')


    @with_default_category('Vegetables')
    class LoadableVegetables(CommandSet):
        def __init__(self):
            super().__init__()

        def do_arugula(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Arugula')

        def do_bokchoy(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Bok Choy')


    class ExampleApp(cmd2.Cmd):
        """
        CommandSets are loaded via the `load` and `unload` commands
        """

        def __init__(self, *args, **kwargs):
            # gotta have this or neither the plugin or cmd2 will initialize
            super().__init__(*args, auto_load_commands=False, **kwargs)

            self._fruits = LoadableFruits()
            self._vegetables = LoadableVegetables()

        load_parser = cmd2.Cmd2ArgumentParser('load')
        load_parser.add_argument('cmds', choices=['fruits', 'vegetables'])

        @with_argparser(load_parser)
        @with_category('Command Loading')
        def do_load(self, ns: argparse.Namespace):
            if ns.cmds == 'fruits':
                try:
                    self.install_command_set(self._fruits)
                    self.poutput('Fruits loaded')
                except ValueError:
                    self.poutput('Fruits already loaded')

            if ns.cmds == 'vegetables':
                try:
                    self.install_command_set(self._vegetables)
                    self.poutput('Vegetables loaded')
                except ValueError:
                    self.poutput('Vegetables already loaded')

        @with_argparser(load_parser)
        def do_unload(self, ns: argparse.Namespace):
            if ns.cmds == 'fruits':
                self.uninstall_command_set(self._fruits)
                self.poutput('Fruits unloaded')

            if ns.cmds == 'vegetables':
                self.uninstall_command_set(self._vegetables)
                self.poutput('Vegetables unloaded')


    if __name__ == '__main__':
        app = ExampleApp()
        app.cmdloop()


Injecting Sub-Commands
----------------------

Description
~~~~~~~~~~~
Using the `with_argparse` decorator, it is possible to define sub-commands for your command. This has a tendency to
either drive your interface into an object-centric interface. For example, imagine you have a tool that manages your
media collection and you want to manage movies or shows. An object-centric approach would push you to have base commands
such as `movies` and `shows` which each have sub-commands `add`, `edit`, `list`, `delete`. If you wanted to present an
action-centric command set, so that `add`, `edit`, `list`, and `delete` are the base commands, you'd have to organize
your code around these similar actions rather than organizing your code around similar objects being managed.

Sub-command injection allows you to inject sub-commands into a base command to present an interface that is sensible to
a user while still organizing your code in whatever structure make more logical sense to the developer.

Example
~~~~~~~

This example is a variation on the Dynamic Commands example above. A `cut` command is introduced as a base
command and each CommandSet

.. code-block:: python

    import argparse
    import cmd2
    from cmd2 import CommandSet, with_argparser, with_category, with_default_category


    @with_default_category('Fruits')
    class LoadableFruits(CommandSet):
        def __init__(self):
            super().__init__()

        def do_apple(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Apple')

        banana_parser = cmd2.Cmd2ArgumentParser(add_help=False)
        banana_parser.add_argument('direction', choices=['discs', 'lengthwise'])

        @cmd2.as_subcommand_to('cut', 'banana', banana_parser)
        def cut_banana(self, cmd: cmd2.Cmd, ns: argparse.Namespace):
            """Cut banana"""
            cmd.poutput('cutting banana: ' + ns.direction)


    @with_default_category('Vegetables')
    class LoadableVegetables(CommandSet):
        def __init__(self):
            super().__init__()

        def do_arugula(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Arugula')

        bokchoy_parser = cmd2.Cmd2ArgumentParser(add_help=False)
        bokchoy_parser.add_argument('style', choices=['quartered', 'diced'])

        @cmd2.as_subcommand_to('cut', 'bokchoy', bokchoy_parser)
        def cut_bokchoy(self, cmd: cmd2.Cmd, _: cmd2.Statement):
            cmd.poutput('Bok Choy')


    class ExampleApp(cmd2.Cmd):
        """
        CommandSets are automatically loaded. Nothing needs to be done.
        """

        def __init__(self, *args, **kwargs):
            # gotta have this or neither the plugin or cmd2 will initialize
            super().__init__(*args, auto_load_commands=False, **kwargs)

            self._fruits = LoadableFruits()
            self._vegetables = LoadableVegetables()

        load_parser = cmd2.Cmd2ArgumentParser('load')
        load_parser.add_argument('cmds', choices=['fruits', 'vegetables'])

        @with_argparser(load_parser)
        @with_category('Command Loading')
        def do_load(self, ns: argparse.Namespace):
            if ns.cmds == 'fruits':
                try:
                    self.install_command_set(self._fruits)
                    self.poutput('Fruits loaded')
                except ValueError:
                    self.poutput('Fruits already loaded')

            if ns.cmds == 'vegetables':
                try:
                    self.install_command_set(self._vegetables)
                    self.poutput('Vegetables loaded')
                except ValueError:
                    self.poutput('Vegetables already loaded')

        @with_argparser(load_parser)
        def do_unload(self, ns: argparse.Namespace):
            if ns.cmds == 'fruits':
                self.uninstall_command_set(self._fruits)
                self.poutput('Fruits unloaded')

            if ns.cmds == 'vegetables':
                self.uninstall_command_set(self._vegetables)
                self.poutput('Vegetables unloaded')

        cut_parser = cmd2.Cmd2ArgumentParser('cut')
        cut_subparsers = cut_parser.add_subparsers(title='item', help='item to cut', unloadable=True)

        @with_argparser(cut_parser)
        def do_cut(self, ns: argparse.Namespace):
            func = getattr(ns, 'handler', None)
            if func is not None:
                # Call whatever subcommand function was selected
                func(ns)
            else:
                # No subcommand was provided, so call help
                self.poutput('This command does nothing without sub-parsers registered')
                self.do_help('cut')


    if __name__ == '__main__':
        app = ExampleApp()
        app.cmdloop()