Debian Codegraph @

docs/source/commands.rst

raw
1 .. _Commands:
2
3 ========
4 Commands
5 ========
6
7 There are two different ways of registering functions:
8
9 1. :meth:`app.default <cyclopts.App.default>` -
10 Registers an action for when no registered command is provided.
11 This was previously demonstrated in :ref:`Getting Started`.
12
13 A sub-app **cannot** be registered with :meth:`app.default <cyclopts.App.default>`.
14 If no ``default`` command is registered, Cyclopts will display the help-page.
15
16 2. :meth:`app.command <cyclopts.App.command>` - Registers a function or :class:`.App` as a command.
17
18 This section will detail how to use the :meth:`@app.command <cyclopts.App.command>` decorator.
19
20 ---------------------
21 Registering a Command
22 ---------------------
23 The :meth:`@app.command <cyclopts.App.command>` decorator adds a **command** to a Cyclopts application.
24
25 .. code-block:: python
26
27 from cyclopts import App
28
29 app = App()
30
31 @app.command
32 def fizz(n: int):
33 print(f"FIZZ: {n}")
34
35 @app.command
36 def buzz(n: int):
37 print(f"BUZZ: {n}")
38
39 app()
40
41 We can now control which command runs from the CLI:
42
43 .. code-block:: console
44
45 $ my-script fizz 3
46 FIZZ: 3
47
48 $ my-script buzz 4
49 BUZZ: 4
50
51 $ my-script fuzz
52 ╭─ Error ────────────────────────────────────────────────────────────────────╮
53 │ Unknown command "fuzz". Did you mean "fizz"? │
54 ╰────────────────────────────────────────────────────────────────────────────╯
55
56 ------------------------
57 Registering a SubCommand
58 ------------------------
59 The :meth:`app.command <cyclopts.App.command>` method can also register another Cyclopts :class:`.App` as a command.
60
61 .. code-block:: python
62
63 from cyclopts import App
64
65 app = App()
66 sub_app = App(name="foo") # "foo" would be a better variable name than "sub_app".
67 # "sub_app" in this example emphasizes the name comes from name="foo".
68 app.command(sub_app) # Registers sub_app to command "foo"
69 # Or, as a one-liner: sub_app = app.command(App(name="foo"))
70
71
72 @sub_app.command
73 def bar(n: int):
74 print(f"BAR: {n}")
75
76
77 # Alternatively, access subapps from app like a dictionary.
78 @app["foo"].command
79 def baz(n: int):
80 print(f"BAZ: {n}")
81
82
83 app()
84
85
86 .. code-block:: console
87
88 $ my-script foo bar 3
89 BAR: 3
90
91 $ my-script foo baz 4
92 BAZ: 4
93
94 The subcommand may have their own registered ``default`` action.
95 Cyclopts's command structure is fully recursive.
96
97 .. _Flattening SubCommands:
98
99 -----------------------
100 Flattening SubCommands
101 -----------------------
102 Sometimes you want to make all commands from a sub-app directly accessible from the parent app,
103 without requiring users to type the intermediate subcommand name.
104
105 You can flatten a sub-app by registering it with the special ``name="*"``:
106
107 .. code-block:: python
108
109 from cyclopts import App
110
111 app = App()
112 tools_app = App(name="tools")
113
114 @tools_app.command
115 def compress(file: str):
116 print(f"Compressing {file}")
117
118 @tools_app.command
119 def extract(file: str):
120 print(f"Extracting {file}")
121
122 # Flatten: make all tools_app commands directly accessible
123 app.command(tools_app, name="*")
124
125 app()
126
127 .. code-block:: console
128
129 $ my-script compress data.txt
130 Compressing data.txt
131
132 $ my-script extract archive.zip
133 Extracting archive.zip
134
135 Caveats of flattening:
136
137 - Parent app commands take precedence over flattened commands if there are name collisions.
138 - Multiple sub-apps can be flattened into the same parent app.
139 - You cannot supply additional configuration kwargs when using ``name="*"``.
140 - Only :class:`.App` instances can be flattened (not functions or import paths).
141
142 Flattening is useful for organizing related commands into logical groups in your code while keeping
143 the CLI interface simple and flat.
144
145 ------------------------
146 SubCommand Configuration
147 ------------------------
148 Subcommands inherit configuration from their parent apps.
149
150 .. code-block:: python
151
152 from cyclopts import App
153
154 # Root app with specific error handling
155 root_app = App(
156 exit_on_error=False,
157 print_error=False,
158 )
159
160 # Child app inherits parent's settings
161 child_app = root_app.command(App(name="child"))
162
163 @child_app.default
164 def child_action():
165 return "Child executed successfully"
166
167 # Child can override parent settings if needed
168 grandchild_app = child_app.command(App(name="grandchild", exit_on_error=True))
169
170 When ``parent_app("child ...")`` is called, the child command will use the parent's
171 error handling settings unless explicitly overridden.
172
173 .. _Command Changing Name:
174
175 ---------------------
176 Changing Command Name
177 ---------------------
178 By default, commands are registered to the python function's name with underscores replaced with hyphens.
179 Any leading or trailing underscores will be stripped.
180 For example, the function ``_foo_bar()`` will become the command ``foo-bar``.
181 This renaming is done because CLI programs generally tend to use hyphens instead of underscores.
182 The name transform can be configured by :attr:`App.name_transform <cyclopts.App.name_transform>`.
183 For example, to make CLI command names be identical to their python function name counterparts, we can configure :class:`~cyclopts.App` as follows:
184
185 .. code-block:: python
186
187 from cyclopts import App
188
189 app = App(name_transform=lambda s: s)
190
191 @app.command
192 def foo_bar(): # will now be "foo_bar" instead of "foo-bar"
193 print("running function foo_bar")
194
195 app()
196
197 .. code-block:: console
198
199 $ my-script foo_bar
200 running function foo_bar
201
202
203 Alternatively, the name can be **manually** changed in the :meth:`@app.command <cyclopts.App.command>` decorator.
204 Manually set names are **not** subject to :attr:`App.name_transform <cyclopts.App.name_transform>`.
205
206 .. code-block:: python
207
208 from cyclopts import App
209
210 app = App()
211
212 @app.command(name="bar")
213 def foo(): # function name will NOT be used.
214 print("Hello World!")
215
216 app()
217
218 .. code-block:: console
219
220 $ my-script bar
221 Hello World!
222
223 Finally, if you would like to register an **additional** name to the Cyclopts-derived names, you can set an :attr:`~.App.alias`:
224
225 .. code-block:: python
226
227 from cyclopts import App
228
229 app = App()
230
231 @app.command(alias="bar")
232 def foo(): # both "foo" and "bar" will trigger this function.
233 print("Running foo.")
234
235 app()
236
237 .. code-block:: console
238
239 $ my-script foo
240 Running bar.
241
242 $ my-script bar
243 Running bar.
244
245 .. _Synonyms:
246
247 --------
248 Synonyms
249 --------
250 A common CLI problem is remembering subcommand synonyms. Did this CLI's developer decide to call it ``remove``, ``uninstall``, or ``delete``?
251
252 The :attr:`~.App.synonym` field declares **alternate names** that trigger a "Did you mean..."
253 suggestion **without** registering the command under those names.
254 It accepts either a single :obj:`str` or an iterable of strings:
255
256 .. code-block:: python
257
258 from cyclopts import App
259
260 app = App()
261
262 @app.command(synonym="add") # single string
263 def install(name: str): ...
264
265 @app.command(synonym=["remove", "rm"]) # list of strings
266 def uninstall(name: str):
267 print(f"uninstalling {name}")
268
269 app()
270
271 .. code-block:: console
272
273 $ my-script uninstall mypackage
274 uninstalling mypackage
275
276 $ my-script remove mypackage
277 ╭─ Error ────────────────────────────────────────────────────────────────────╮
278 │ Unknown command "remove". Did you mean "uninstall"? Available commands: │
279 │ uninstall. │
280 ╰────────────────────────────────────────────────────────────────────────────╯
281
282 Synonyms differ from :attr:`~.App.alias` in two important ways:
283
284 * **Synonyms are not runnable.** ``my-script remove`` raises an error; it doesn't invoke ``uninstall``.
285 Use :attr:`~.App.alias` when you want the command to be callable under multiple names.
286 * **Synonyms are hidden from** ``--help``. They exist only to guide users who type the "wrong" word.
287
288 If two commands declare the same synonym, both are suggested:
289
290 .. code-block:: python
291
292 @app.command(synonym="erase")
293 def uninstall(name: str): ...
294
295 @app.command(synonym="erase")
296 def purge(name: str): ...
297
298 .. code-block:: console
299
300 $ my-script erase mypackage
301 ╭─ Error ────────────────────────────────────────────────────────────────────╮
302 │ Unknown command "erase". Did you mean "uninstall" or "purge"? ... │
303 ╰────────────────────────────────────────────────────────────────────────────╯
304
305 When a typed token is not declared as any synonym, Cyclopts falls back to its standard
306 typo-fuzzy-match suggestion.
307
308 -----------
309 Adding Help
310 -----------
311 There are a few ways to add a help string to a command:
312
313 1. If the function has a docstring, the **short description** will be used as the help string for the command.
314 This is generally the preferred method of providing help strings.
315
316 2. If the registered command is a sub app, the sub app's :attr:`help <cyclopts.App.help>` field will be used.
317
318 .. code-block:: python
319
320 sub_app = App(name="foo", help="Help text for foo.")
321 app.command(sub_app)
322
323 3. The :attr:`help <cyclopts.App.help>` field of :meth:`@app.command <cyclopts.App.command>`. If provided, the docstring or subapp help field will **not** be used.
324
325 .. code-block:: python
326
327 from cyclopts import App
328
329 app = App()
330
331 @app.command
332 def foo():
333 """Help string for foo."""
334 pass
335
336 @app.command(help="Help string for bar.")
337 def bar():
338 """This got overridden."""
339
340 app()
341
342 .. code-block:: console
343
344 $ my-script --help
345 ╭─ Commands ────────────────────────────────────────────────────────────╮
346 │ bar Help string for bar. │
347 │ foo Help string for foo. │
348 │ --help,-h Display this message and exit. │
349 │ --version Display application version. │
350 ╰───────────────────────────────────────────────────────────────────────╯
351
352 -----
353 Async
354 -----
355 Cyclopts also works with **async** commands; when an async command is encountered, an event loop will be automatically created using the specified ``backend`` parameter (default :mod:`asyncio`).
356
357 .. code-block:: python
358
359 import asyncio
360 from cyclopts import App
361
362 app = App()
363
364 @app.command
365 async def foo():
366 await asyncio.sleep(10)
367
368 app()
369
370 When calling from within an existing async context, :keyword:`await` the async method :meth:`~cyclopts.App.run_async`:
371
372 .. code-block:: python
373
374 async def main():
375 result = await app.run_async(["foo"])
376 # Instead of: app(["foo"]) which would raise RuntimeError
377
378 --------------------------
379 Decorated Function Details
380 --------------------------
381 Cyclopts **does not modify the decorated function in any way**.
382 The returned function is the **exact same function** being decorated and can be used exactly as if it were not decorated by Cyclopts.
383
384 --------
385 See Also
386 --------
387
388 For improved CLI startup performance with large applications, see :ref:`Lazy Loading`.