Debian Codegraph @

docs/source/sphinx_integration.rst

raw
1 Sphinx Integration
2 ==================
3
4 Cyclopts provides builtin `Sphinx <https://www.sphinx-doc.org/>`_ support.
5
6 .. contents:: Table of Contents
7 :local:
8 :depth: 2
9
10 Quick Start
11 -----------
12
13 1. Add the extension to your Sphinx configuration (``docs/conf.py``):
14
15 .. code-block:: python
16
17 extensions = [
18 'cyclopts.sphinx_ext', # Add this line
19 # ... your other extensions
20 ]
21
22 2. Use the directive in your RST files:
23
24 .. code-block:: rst
25
26 .. cyclopts:: mypackage.cli:app
27
28 Directive Usage
29 ---------------
30
31 Basic Syntax
32 ~~~~~~~~~~~~
33
34 The ``cyclopts`` directive accepts a module path to your Cyclopts ``App`` object:
35
36 .. code-block:: rst
37
38 .. cyclopts:: mypackage.cli:app
39
40 Module Path Formats
41 ~~~~~~~~~~~~~~~~~~~
42
43 The directive accepts two module path formats:
44
45 1. **Explicit format** (``module.path:app_name``):
46
47 .. code-block:: rst
48
49 .. cyclopts:: mypackage.cli:app
50 .. cyclopts:: myapp.commands:main_app
51 .. cyclopts:: src.cli:cli
52
53 This explicitly specifies which ``App`` object to document.
54
55 2. **Automatic discovery** (``module.path``):
56
57 .. code-block:: rst
58
59 .. cyclopts:: mypackage.cli
60 .. cyclopts:: myapp.main
61
62 The extension will search the module for an ``App`` instance, looking for common names like ``app``, ``cli``, or ``main``.
63
64 Directive Options
65 -----------------
66
67 The directive supports several options to customize the generated documentation:
68
69 ``:heading-level:`` - Heading Level
70 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
71
72 Set the starting heading level for the generated documentation (1-6, default: 2):
73
74 .. code-block:: rst
75
76 .. cyclopts:: mypackage.cli:app
77 :heading-level: 3
78
79 This is useful when you need to adjust the heading hierarchy. The default of 2 works well for most cases where the directive is placed under a page title.
80
81 ``:max-heading-level:`` - Maximum Heading Level
82 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83
84 Set the maximum heading level to use (1-6, default: 6):
85
86 .. code-block:: rst
87
88 .. cyclopts:: mypackage.cli:app
89 :max-heading-level: 4
90
91 Headings deeper than this level will be capped at this value. This is useful for deeply nested command hierarchies where you want to prevent headings from becoming too small.
92
93 ``:no-recursive:`` - Exclude Subcommands
94 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
95
96 Disable recursive documentation of subcommands (by default, subcommands are included):
97
98 .. code-block:: rst
99
100 .. cyclopts:: mypackage.cli:app
101 :no-recursive:
102
103 When this flag is present, only the top-level commands are documented.
104
105 ``:include-hidden:`` - Show Hidden Commands
106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107
108 Include commands marked with ``show=False`` in the documentation:
109
110 .. code-block:: rst
111
112 .. cyclopts:: mypackage.cli:app
113 :include-hidden: true
114
115 By default, hidden commands are not included in the generated documentation.
116
117 ``:flatten-commands:`` - Generate Flat Command Hierarchy
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119
120 Generate all commands at the same heading level instead of nested hierarchy:
121
122 .. code-block:: rst
123
124 .. cyclopts:: mypackage.cli:app
125 :flatten-commands:
126
127 This creates distinct, equally-weighted headings for each command and subcommand, making them easier to reference and navigate in the documentation. Without this option, subcommands are nested with incrementing heading levels.
128
129 ``:code-block-title:`` - Render Titles as Inline Code
130 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
131
132 Render command titles with inline code formatting instead of plain text:
133
134 .. code-block:: rst
135
136 .. cyclopts:: mypackage.cli:app
137 :code-block-title:
138
139 When this flag is present, command titles are rendered with monospace formatting, which can be useful for certain documentation themes or to make command names stand out visually.
140
141 ``:commands:`` - Filter Specific Commands
142 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
143
144 Document only specific commands from your CLI application:
145
146 .. code-block:: rst
147
148 .. cyclopts:: mypackage.cli:app
149 :commands: init, build, deploy
150
151 This will only document the specified commands. You can also use nested command paths with dot notation:
152
153 .. code-block:: rst
154
155 .. cyclopts:: mypackage.cli:app
156 :commands: db.migrate, db.backup, api
157
158 - ``db.migrate`` - Documents only the ``migrate`` subcommand under ``db``
159 - ``db.backup`` - Documents only the ``backup`` subcommand under ``db``
160 - ``api`` - Documents the ``api`` command and all its subcommands
161
162 You can use either underscore or dash notation in command names - they will be normalized automatically.
163
164 ``:exclude-commands:`` - Exclude Specific Commands
165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166
167 Exclude specific commands from the documentation:
168
169 .. code-block:: rst
170
171 .. cyclopts:: mypackage.cli:app
172 :exclude-commands: debug, internal-test
173
174 This is useful for hiding internal or debug commands from user-facing documentation. Like ``:commands:``, this also supports nested command paths with dot notation.
175
176 ``:skip-preamble:`` - Skip Description and Usage
177 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178
179 Skip the description and usage sections for the target command when filtering to a single command:
180
181 .. code-block:: rst
182
183 .. cyclopts:: mypackage.cli:app
184 :commands: deploy
185 :skip-preamble:
186
187 When you filter to a single command using ``:commands:`` and provide your own section heading in the RST, you may not want the directive to generate the command's description and usage block. Adding ``:skip-preamble:`` suppresses these sections while still generating the command's parameters and subcommands.
188
189 This is useful when you want to write your own introduction for a command section:
190
191 .. code-block:: rst
192
193 Deployment
194 ==========
195
196 Deploy your application to production with these commands.
197
198 .. cyclopts:: mypackage.cli:app
199 :commands: deploy
200 :skip-preamble:
201
202 Without ``:skip-preamble:``, the output would include both your introduction and the command's docstring description, which can be redundant.
203
204 ``:usage-name:`` - Override the Command Shown in Usage Lines
205 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
206
207 Replace the app name shown in ``Usage:`` lines of the generated documentation with a custom invocation string:
208
209 .. code-block:: rst
210
211 .. cyclopts:: mypackage.cli:app
212 :usage-name: uv run cli
213
214 This is useful when the documented invocation differs from the app's configured name. For example, an ``App(name="cli", ...)`` installed as a project entry point might typically be invoked as ``uv run cli``; setting ``:usage-name: uv run cli`` renders that in every ``Usage:`` block while section headings, anchors, and the table of contents continue to reference the plain ``cli`` name.
215
216 Automatic Reference Labels
217 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
218
219 The Sphinx directive automatically generates RST reference labels for all commands, enabling cross-referencing throughout your documentation. The anchor format is ``cyclopts-{app-name}-{command-path}``, which prevents naming conflicts when documenting multiple CLIs.
220
221 For example:
222 - Root application: ``cyclopts-myapp``
223 - Subcommand: ``cyclopts-myapp-deploy``
224 - Nested subcommand: ``cyclopts-myapp-deploy-production``
225
226 You can reference these commands elsewhere in your documentation using ``:ref:`cyclopts-myapp-deploy```.
227
228 Complete Example
229 ----------------
230
231 Here's a complete example showing a CLI application and its Sphinx documentation:
232
233 CLI Application (``myapp/cli.py``):
234 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
235
236 .. code-block:: python
237
238 from pathlib import Path
239 from typing import Optional
240 from cyclopts import App
241
242 app = App(
243 name="myapp",
244 help="My awesome CLI application",
245 version="1.0.0"
246 )
247
248 @app.command
249 def init(path: Path = Path("."), template: str = "default"):
250 """Initialize a new project.
251
252 Parameters
253 ----------
254 path : Path
255 Directory where the project will be created
256 template : str
257 Project template to use
258 """
259 print(f"Initializing project at {path}")
260
261 @app.command
262 def build(source: Path, output: Optional[Path] = None, *, minify: bool = False):
263 """Build the project.
264
265 Parameters
266 ----------
267 source : Path
268 Source directory
269 output : Path, optional
270 Output directory (defaults to source/dist)
271 minify : bool
272 Minify the output files
273 """
274 output = output or source / "dist"
275 print(f"Building from {source} to {output}")
276
277 if __name__ == "__main__":
278 app()
279
280 Sphinx Configuration (``docs/conf.py``):
281 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
282
283 .. code-block:: python
284
285 import sys
286 from pathlib import Path
287
288 # Add your package to the path
289 sys.path.insert(0, str(Path(__file__).parent.parent))
290
291 # Extensions
292 extensions = [
293 'cyclopts.sphinx_ext',
294 'sphinx.ext.autodoc', # For API docs
295 'sphinx.ext.napoleon', # For NumPy-style docstrings
296 ]
297
298 # Project info
299 project = 'MyApp'
300 author = 'Your Name'
301 version = '1.0.0'
302
303 # HTML theme
304 html_theme = 'sphinx_rtd_theme'
305
306 Documentation File (``docs/cli.rst``):
307 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
308
309 .. code-block:: rst
310
311 CLI Reference
312 =============
313
314 This section documents all available CLI commands.
315
316 .. cyclopts:: myapp.cli:app
317
318 The above directive will automatically generate documentation for all
319 commands, including their parameters, types, defaults, and help text.
320
321 Advanced Usage
322 --------------
323
324 Using Distinct Command Headings
325 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
326
327 When you want each command to have its own distinct heading for better navigation and referencing:
328
329 .. code-block:: rst
330
331 CLI Command Reference
332 =====================
333
334 .. cyclopts:: myapp.cli:app
335 :flatten-commands:
336 :code-block-title:
337
338 This generates:
339
340 - All commands at the same heading level (not nested)
341 - Command titles with monospace formatting
342 - Automatic reference labels for cross-linking
343
344 You can then reference specific commands:
345
346 See :ref:`cyclopts-myapp-deploy` for deployment options.
347 The :ref:`cyclopts-myapp-init` command sets up your project.
348
349 Selective Command Documentation
350 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
351
352 Split your CLI documentation across multiple sections or pages:
353
354 .. code-block:: rst
355
356 Database Commands
357 =================
358
359 The following commands manage database operations:
360
361 .. cyclopts:: myapp.cli:app
362 :commands: db
363
364 API Management
365 ==============
366
367 Commands for controlling the API server:
368
369 .. cyclopts:: myapp.cli:app
370 :commands: api
371
372 Development Tools
373 =================
374
375 Utilities for development (excluding internal debug commands):
376
377 .. cyclopts:: myapp.cli:app
378 :commands: dev
379 :exclude-commands: dev.debug, dev.internal
380
381 This approach allows you to:
382
383 - Organize large CLI applications into logical sections
384 - Document different command groups on separate pages
385 - Exclude internal or debug commands from user documentation
386 - Create targeted documentation for different audiences
387
388 Output Formats
389 --------------
390
391 While the Sphinx directive uses RST internally, you can also generate documentation programmatically in multiple formats:
392
393 .. code-block:: python
394
395 from myapp.cli import app
396
397 # Generate reStructuredText
398 rst_docs = app.generate_docs(output_format="rst")
399
400 # Generate Markdown
401 md_docs = app.generate_docs(output_format="markdown")
402
403 # Generate HTML
404 html_docs = app.generate_docs(output_format="html")
405
406 This is useful for generating documentation outside of Sphinx, such as for GitHub README files or other documentation systems.
407
408 See Also
409 --------
410
411 * :doc:`/help` - Customizing help output
412 * :doc:`/commands` - Creating commands and subcommands
413 * :doc:`/parameters` - Parameter types and validation
414 * `Sphinx Documentation <https://www.sphinx-doc.org/>`_ - Official Sphinx documentation