File: renderer.py

package info (click to toggle)
tmuxp 1.64.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,500 kB
  • sloc: python: 17,788; sh: 22; makefile: 6
file content (586 lines) | stat: -rw-r--r-- 17,790 bytes parent folder | download
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
"""Renderer - convert ParserInfo to docutils nodes.

This module provides the ArgparseRenderer class that transforms
structured parser information into docutils nodes for documentation.
"""

from __future__ import annotations

import dataclasses
import typing as t

from docutils import nodes
from docutils.statemachine import StringList
from sphinx_argparse_neo.nodes import (
    argparse_argument,
    argparse_group,
    argparse_program,
    argparse_subcommand,
    argparse_subcommands,
    argparse_usage,
)
from sphinx_argparse_neo.parser import (
    ArgumentGroup,
    ArgumentInfo,
    MutuallyExclusiveGroup,
    ParserInfo,
    SubcommandInfo,
)
from sphinx_argparse_neo.utils import escape_rst_emphasis

if t.TYPE_CHECKING:
    from docutils.parsers.rst.states import RSTState
    from sphinx.config import Config


@dataclasses.dataclass
class RenderConfig:
    """Configuration for the renderer.

    Examples
    --------
    >>> config = RenderConfig()
    >>> config.show_defaults
    True
    >>> config.group_title_prefix
    ''
    """

    group_title_prefix: str = ""
    show_defaults: bool = True
    show_choices: bool = True
    show_types: bool = True

    @classmethod
    def from_sphinx_config(cls, config: Config) -> RenderConfig:
        """Create RenderConfig from Sphinx configuration.

        Parameters
        ----------
        config : Config
            Sphinx configuration object.

        Returns
        -------
        RenderConfig
            Render configuration based on Sphinx config values.
        """
        return cls(
            group_title_prefix=getattr(config, "argparse_group_title_prefix", ""),
            show_defaults=getattr(config, "argparse_show_defaults", True),
            show_choices=getattr(config, "argparse_show_choices", True),
            show_types=getattr(config, "argparse_show_types", True),
        )


class ArgparseRenderer:
    """Render ParserInfo to docutils nodes.

    This class can be subclassed to customize rendering behavior.
    Override individual methods to change how specific elements are rendered.

    Parameters
    ----------
    config : RenderConfig
        Rendering configuration.
    state : RSTState | None
        RST state for parsing nested RST content.

    Examples
    --------
    >>> from sphinx_argparse_neo.parser import ParserInfo
    >>> config = RenderConfig()
    >>> renderer = ArgparseRenderer(config)
    >>> info = ParserInfo(
    ...     prog="myapp",
    ...     usage=None,
    ...     bare_usage="myapp [-h]",
    ...     description="My app",
    ...     epilog=None,
    ...     argument_groups=[],
    ...     subcommands=None,
    ...     subcommand_dest=None,
    ... )
    >>> result = renderer.render(info)
    >>> isinstance(result, list)
    True
    """

    def __init__(
        self,
        config: RenderConfig | None = None,
        state: RSTState | None = None,
    ) -> None:
        """Initialize the renderer."""
        self.config = config or RenderConfig()
        self.state = state

    @staticmethod
    def _extract_id_prefix(prog: str) -> str:
        """Extract subcommand from prog for unique section IDs.

        Parameters
        ----------
        prog : str
            The program name, potentially with subcommand (e.g., "tmuxp load").

        Returns
        -------
        str
            The subcommand part for use as ID prefix, or empty string if none.

        Examples
        --------
        >>> ArgparseRenderer._extract_id_prefix("tmuxp load")
        'load'
        >>> ArgparseRenderer._extract_id_prefix("tmuxp")
        ''
        >>> ArgparseRenderer._extract_id_prefix("vcspull sync")
        'sync'
        >>> ArgparseRenderer._extract_id_prefix("myapp sub cmd")
        'sub-cmd'
        """
        parts = prog.split()
        if len(parts) <= 1:
            return ""
        # Join remaining parts with hyphen for multi-level subcommands
        return "-".join(parts[1:])

    def render(self, parser_info: ParserInfo) -> list[nodes.Node]:
        """Render a complete parser to docutils nodes.

        Parameters
        ----------
        parser_info : ParserInfo
            The parsed parser information.

        Returns
        -------
        list[nodes.Node]
            List of docutils nodes representing the documentation.

        Note
        ----
        Sections for Usage and argument groups are emitted as siblings of
        argparse_program rather than children. This allows Sphinx's
        TocTreeCollector to discover them for inclusion in the table of
        contents.

        The rendered structure is:

        - argparse_program (description only, no "examples:" part)
        - section#usage (h3 "Usage" with usage block)
        - section#positional-arguments (h3)
        - section#options (h3)

        The "examples:" definition list in descriptions is left for
        argparse_exemplar.py to transform into a proper Examples section.
        """
        result: list[nodes.Node] = []

        # Create program container for description only
        program_node = argparse_program()
        program_node["prog"] = parser_info.prog

        # Add description (may contain "examples:" definition list for later
        # transformation by argparse_exemplar.py)
        if parser_info.description:
            desc_nodes = self._parse_text(parser_info.description)
            program_node.extend(desc_nodes)

        result.append(program_node)

        # Extract ID prefix from prog for unique section IDs
        # e.g., "tmuxp load" -> "load", "myapp" -> ""
        id_prefix = self._extract_id_prefix(parser_info.prog)

        # Add Usage section as sibling (for TOC visibility)
        usage_section = self.render_usage_section(parser_info, id_prefix=id_prefix)
        result.append(usage_section)

        # Add argument groups as sibling sections (for TOC visibility)
        for group in parser_info.argument_groups:
            group_section = self.render_group_section(group, id_prefix=id_prefix)
            result.append(group_section)

        # Add subcommands
        if parser_info.subcommands:
            subcommands_node = self.render_subcommands(parser_info.subcommands)
            result.append(subcommands_node)

        # Add epilog
        if parser_info.epilog:
            epilog_nodes = self._parse_text(parser_info.epilog)
            result.extend(epilog_nodes)

        return self.post_process(result)

    def render_usage(self, parser_info: ParserInfo) -> argparse_usage:
        """Render the usage block.

        Parameters
        ----------
        parser_info : ParserInfo
            The parser information.

        Returns
        -------
        argparse_usage
            Usage node.
        """
        usage_node = argparse_usage()
        usage_node["usage"] = parser_info.bare_usage
        return usage_node

    def render_usage_section(
        self, parser_info: ParserInfo, *, id_prefix: str = ""
    ) -> nodes.section:
        """Render usage as a section with heading for TOC visibility.

        Creates a proper section node with "Usage" heading containing the
        usage block. This structure allows Sphinx's TocTreeCollector to
        discover it for the table of contents.

        Parameters
        ----------
        parser_info : ParserInfo
            The parser information.
        id_prefix : str
            Optional prefix for the section ID (e.g., "load" -> "load-usage").
            Used to ensure unique IDs when multiple argparse directives exist
            on the same page.

        Returns
        -------
        nodes.section
            Section node containing the usage block with a "Usage" heading.

        Examples
        --------
        >>> from sphinx_argparse_neo.parser import ParserInfo
        >>> renderer = ArgparseRenderer()
        >>> info = ParserInfo(
        ...     prog="myapp",
        ...     usage=None,
        ...     bare_usage="myapp [-h] command",
        ...     description=None,
        ...     epilog=None,
        ...     argument_groups=[],
        ...     subcommands=None,
        ...     subcommand_dest=None,
        ... )
        >>> section = renderer.render_usage_section(info)
        >>> section["ids"]
        ['usage']

        With prefix for subcommand pages:

        >>> section = renderer.render_usage_section(info, id_prefix="load")
        >>> section["ids"]
        ['load-usage']
        >>> section.children[0].astext()
        'Usage'
        """
        section_id = f"{id_prefix}-usage" if id_prefix else "usage"
        section = nodes.section()
        section["ids"] = [section_id]
        section["names"] = [nodes.fully_normalize_name("Usage")]
        section += nodes.title("Usage", "Usage")

        usage_node = argparse_usage()
        usage_node["usage"] = parser_info.bare_usage
        section += usage_node

        return section

    def render_group_section(
        self, group: ArgumentGroup, *, id_prefix: str = ""
    ) -> nodes.section:
        """Render an argument group wrapped in a section for TOC visibility.

        Creates a proper section node with the group title as heading,
        containing the argparse_group node. This structure allows Sphinx's
        TocTreeCollector to discover it for the table of contents.

        Parameters
        ----------
        group : ArgumentGroup
            The argument group to render.
        id_prefix : str
            Optional prefix for the section ID (e.g., "load" -> "load-options").
            Used to ensure unique IDs when multiple argparse directives exist
            on the same page.

        Returns
        -------
        nodes.section
            Section node containing the group for TOC discovery.

        Examples
        --------
        >>> from sphinx_argparse_neo.parser import ArgumentGroup
        >>> renderer = ArgparseRenderer()
        >>> group = ArgumentGroup(
        ...     title="positional arguments",
        ...     description=None,
        ...     arguments=[],
        ...     mutually_exclusive=[],
        ... )
        >>> section = renderer.render_group_section(group)
        >>> section["ids"]
        ['positional-arguments']

        With prefix for subcommand pages:

        >>> section = renderer.render_group_section(group, id_prefix="load")
        >>> section["ids"]
        ['load-positional-arguments']
        >>> section.children[0].astext()
        'Positional Arguments'
        """
        # Title case the group title for proper display
        raw_title = group.title or "Arguments"
        title = raw_title.title()  # "positional arguments" -> "Positional Arguments"

        if self.config.group_title_prefix:
            title = f"{self.config.group_title_prefix}{title}"

        # Generate section ID from title (with optional prefix for uniqueness)
        base_id = title.lower().replace(" ", "-")
        section_id = f"{id_prefix}-{base_id}" if id_prefix else base_id

        # Create section wrapper for TOC discovery
        section = nodes.section()
        section["ids"] = [section_id]
        section["names"] = [nodes.fully_normalize_name(title)]

        # Add title for TOC - Sphinx's TocTreeCollector looks for this
        section += nodes.title(title, title)

        # Create the styled group container (with empty title - section provides it)
        group_node = self.render_group(group, include_title=False)
        section += group_node

        return section

    def render_group(
        self, group: ArgumentGroup, include_title: bool = True
    ) -> argparse_group:
        """Render an argument group.

        Parameters
        ----------
        group : ArgumentGroup
            The argument group to render.
        include_title : bool
            Whether to include the title in the group node. When False,
            the title is assumed to come from a parent section node.
            Default is True for backwards compatibility.

        Returns
        -------
        argparse_group
            Group node containing argument nodes.
        """
        group_node = argparse_group()

        if include_title:
            title = group.title
            if self.config.group_title_prefix:
                title = f"{self.config.group_title_prefix}{title}"
            group_node["title"] = title
        else:
            # Title provided by parent section
            group_node["title"] = ""

        group_node["description"] = group.description

        # Add individual arguments
        for arg in group.arguments:
            arg_node = self.render_argument(arg)
            group_node.append(arg_node)

        # Add mutually exclusive groups
        for mutex in group.mutually_exclusive:
            mutex_nodes = self.render_mutex_group(mutex)
            group_node.extend(mutex_nodes)

        return group_node

    def render_argument(self, arg: ArgumentInfo) -> argparse_argument:
        """Render a single argument.

        Parameters
        ----------
        arg : ArgumentInfo
            The argument to render.

        Returns
        -------
        argparse_argument
            Argument node.
        """
        arg_node = argparse_argument()
        arg_node["names"] = arg.names
        arg_node["help"] = arg.help
        arg_node["metavar"] = arg.metavar
        arg_node["required"] = arg.required

        if self.config.show_defaults:
            arg_node["default_string"] = arg.default_string

        if self.config.show_choices:
            arg_node["choices"] = arg.choices

        if self.config.show_types:
            arg_node["type_name"] = arg.type_name

        return arg_node

    def render_mutex_group(
        self, mutex: MutuallyExclusiveGroup
    ) -> list[argparse_argument]:
        """Render a mutually exclusive group.

        Parameters
        ----------
        mutex : MutuallyExclusiveGroup
            The mutually exclusive group.

        Returns
        -------
        list[argparse_argument]
            List of argument nodes with mutex indicator.
        """
        result: list[argparse_argument] = []
        for arg in mutex.arguments:
            arg_node = self.render_argument(arg)
            # Mark as part of mutex group
            arg_node["mutex"] = True
            arg_node["mutex_required"] = mutex.required
            result.append(arg_node)
        return result

    def render_subcommands(
        self, subcommands: list[SubcommandInfo]
    ) -> argparse_subcommands:
        """Render subcommands section.

        Parameters
        ----------
        subcommands : list[SubcommandInfo]
            List of subcommand information.

        Returns
        -------
        argparse_subcommands
            Subcommands container node.
        """
        container = argparse_subcommands()
        container["title"] = "Sub-commands"

        for subcmd in subcommands:
            subcmd_node = self.render_subcommand(subcmd)
            container.append(subcmd_node)

        return container

    def render_subcommand(self, subcmd: SubcommandInfo) -> argparse_subcommand:
        """Render a single subcommand.

        Parameters
        ----------
        subcmd : SubcommandInfo
            The subcommand information.

        Returns
        -------
        argparse_subcommand
            Subcommand node, potentially containing nested parser content.
        """
        subcmd_node = argparse_subcommand()
        subcmd_node["name"] = subcmd.name
        subcmd_node["aliases"] = subcmd.aliases
        subcmd_node["help"] = subcmd.help

        # Recursively render the subcommand's parser
        if subcmd.parser:
            nested_nodes = self.render(subcmd.parser)
            subcmd_node.extend(nested_nodes)

        return subcmd_node

    def post_process(self, result_nodes: list[nodes.Node]) -> list[nodes.Node]:
        """Post-process the rendered nodes.

        Override this method to apply transformations after rendering.

        Parameters
        ----------
        result_nodes : list[nodes.Node]
            The rendered nodes.

        Returns
        -------
        list[nodes.Node]
            Post-processed nodes.
        """
        return result_nodes

    def _parse_text(self, text: str) -> list[nodes.Node]:
        """Parse text as RST or MyST content.

        Parameters
        ----------
        text : str
            Text to parse.

        Returns
        -------
        list[nodes.Node]
            Parsed docutils nodes.
        """
        if not text:
            return []

        # Escape RST emphasis patterns before parsing (e.g., "django-*" -> "django-\*")
        text = escape_rst_emphasis(text)

        if self.state is None:
            # No state machine available, return as paragraph
            para = nodes.paragraph(text=text)
            return [para]

        # Use the state machine to parse RST
        container = nodes.container()
        self.state.nested_parse(
            StringList(text.split("\n")),
            0,
            container,
        )
        return list(container.children)


def create_renderer(
    config: RenderConfig | None = None,
    state: RSTState | None = None,
    renderer_class: type[ArgparseRenderer] | None = None,
) -> ArgparseRenderer:
    """Create a renderer instance.

    Parameters
    ----------
    config : RenderConfig | None
        Rendering configuration.
    state : RSTState | None
        RST state for parsing.
    renderer_class : type[ArgparseRenderer] | None
        Custom renderer class to use.

    Returns
    -------
    ArgparseRenderer
        Configured renderer instance.
    """
    cls = renderer_class or ArgparseRenderer
    return cls(config=config, state=state)