click_extra.command_doc module¶

        classDiagram
  ExtraOption <|-- HelpFormatOption
  ExtraOption <|-- ManOption
  StrEnum <|-- HelpFormat
    

Extract a Click command into a structured document and render it.

extract_command_doc() walks a command (and, through iter_command_contexts(), its whole tree) into a CommandDoc: one extraction carrying the man-pages(7) sections documented in Man-page (NAME, SYNOPSIS, DESCRIPTION, OPTIONS, COMMANDS, ENVIRONMENT, FILES and EXIT STATUS). The model then renders to any of the HelpFormat backends: roff (CommandDoc.to_roff()), Markdown (CommandDoc.to_markdown()) and JSON (CommandDoc.to_dict() / CommandDoc.to_json()), with the Carapace completion spec delegated to click_extra.carapace.

The roff backend is Click Extra’s answer to the unmaintained click-man package. It improves on it by:

  • working on a command object via click.Command.make_context(), so it needs no console_scripts entry point;

  • discovering subcommands dynamically through click.Group.list_commands() / click.Group.get_command() with a live context;

  • honoring Click’s \b no-rewrap marker (rendered as roff .nf / .fi);

  • rendering boolean flags (--foo / --no-foo) and skipping hidden commands and options;

  • mirroring Cloup option groups as .SS subsections of OPTIONS (ungrouped options fall under an Other options heading), matching the help screen;

  • emitting ENVIRONMENT (from auto-generated env vars), FILES (from the --config search pattern) and EXIT STATUS sections that click-man never grew.

Font selection follows the man typographic convention encoded by click_extra.theme.LITERAL_STYLES / REPLACEABLE_STYLES: literal tokens (command and option names) render bold (\fB), replaceable tokens (metavars, operands) render italic (\fI).

click_extra.command_doc.MAN_SECTION = '1'¶

Default man page section. Section 1 is for executable programs and shell commands, which is what a Click CLI is.

click_extra.command_doc.DEFAULT_EXIT_STATUS: tuple[tuple[str, str], ...] = (('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.'))¶

Conventional exit codes shared by every Click Extra CLI.

Mirrors the EXIT STATUS table in Man-page. Click returns 2 for usage errors (UsageError), 1 for aborts, and 0 on success. A real Ctrl+C ends the process by SIGINT instead, which a shell reports as 130.

click_extra.command_doc.normalize_examples(examples)[source]¶

Validate and freeze a command’s examples into (description, command) pairs.

Accepts any sequence of two-item sequences, so a list of tuples and a list of lists (what a configuration file or a JSON payload would produce) are both fine. None and an empty sequence both yield an empty tuple.

Raises:

TypeError – when an entry is not a pair of strings, naming the offending entry. Raised at command construction, so a malformed example surfaces on import rather than on the first --help a user runs.

Return type:

tuple[tuple[str, str], ...]

class click_extra.command_doc.DocOptionItem(names, metavar, help, required, optional_value=False, choices=())[source]¶

Bases: object

A single OPTIONS entry, extracted from a Click option.

names: tuple[str, ...]¶

All literal spellings: primary opts followed by secondary_opts (so --foo / --no-foo boolean flags render both).

metavar: str | None¶

The rendered metavar, or None when the option takes no value (boolean flags and counters).

help: str | None¶

The option’s help text, possibly carrying a \b no-rewrap marker.

required: bool¶

Whether the option is mandatory.

optional_value: bool = False¶

Whether the option’s value is optional (a bare flag is allowed). Rendered as the attached [=METAVAR] form instead of a space-separated metavar.

choices: tuple[str, ...] = ()¶

Every value the option accepts, for an option whose type enumerates them.

Recorded whatever the metavar shows, so a JSON consumer never has to parse [a|b|c] back out of it. See unlisted_choices for the rendered subset.

property unlisted_choices: tuple[str, ...]¶

The choices the metavar does not already spell out.

A Choice renders as [a|b|c] by default, putting every value on screen already, and repeating them below the help would say the same thing twice. An option overriding that with a short placeholder (--table-format FORMAT) hides them instead, and this is what the man page and the Markdown render add back.

property attached_value: str¶

The [=METAVAR] form of an optional value.

An optional value renders attached and bracketed (--color[=auto|always|never]), the man convention for a flag usable bare. The metavar’s own outer brackets, if any, are stripped so a Choice does not double up.

to_roff()[source]¶

Render this option as a roff tagged paragraph (.TP).

Return type:

list[str]

property spec: str¶

The option’s spelling and value placeholder, as one plain string.

to_markdown()[source]¶

Render this option as a Markdown list item.

A \b no-rewrap region in the help becomes a fenced block indented under the item, rather than being folded into the sentence: the author aligned it on purpose, and a list item can carry a block as well as a paragraph can.

Return type:

list[str]

to_dict()[source]¶

Render this option as a JSON-serializable mapping.

Return type:

dict[str, Any]

class click_extra.command_doc.DocSubcommand(name, short_help, aliases=())[source]¶

Bases: object

One COMMANDS entry: a subcommand as its parent lists it.

name: str¶

The name the subcommand is invoked under.

short_help: str¶

Its one-line description, from full_short_help().

aliases: tuple[str, ...] = ()¶

The other names it answers to, a Cloup feature.

Drawn in parentheses after the name, the way the help screen and --tree draw them: a reader of a generated page learns the short spelling from the same place they learn the command exists.

label(render)[source]¶

The name, then the aliases in parentheses, each passed through render.

Return type:

str

class click_extra.command_doc.DocOptionGroup(options, title=None, help=None)[source]¶

Bases: object

A titled cluster of OPTIONS entries, mirroring a Cloup option group.

A plain Click command, or a Cloup command with no explicit @option_group, yields a single group with title=None: it renders as a flat OPTIONS list with no .SS subsection heading, identical to a man page that never grouped its options.

options: tuple[DocOptionItem, ...]¶

The option entries in this group.

title: str | None = None¶

The subsection heading, rendered as a roff .SS. None for the implicit single group of an ungrouped command (no heading emitted).

help: str | None = None¶

Optional group description, rendered as prose under the heading.

to_roff()[source]¶

Render an optional .SS heading, group help, then the options.

Return type:

list[str]

to_markdown(level=3)[source]¶

Render an optional heading, group help, then the options.

Return type:

list[str]

to_dict()[source]¶

Render this group as a JSON-serializable mapping.

Return type:

dict[str, Any]

class click_extra.command_doc.CommandDoc(name, short_help='', section='1', synopsis_pieces=(), description='', operands=(), option_groups=(), subcommands=(), environment=(), files=(), exit_status=(('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.')), examples=(), version=None, date='', manual=None, authors=None, copyright=None)[source]¶

Bases: object

A whole man page in structured form, ready to render to roff.

One CommandDoc maps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it with extract_command_doc() and serialize with to_roff().

name: str¶

Full command path, space-joined (like weather forecast).

short_help: str = ''¶

One-line description for the NAME section.

section: str = '1'¶

Man section number.

synopsis_pieces: tuple[str, ...] = ()¶

Usage metavars after the command name ([OPTIONS], CITY, …).

description: str = ''¶

The command’s full help text / docstring for the DESCRIPTION section.

operands: tuple[tuple[str, str], ...] = ()¶

Positional arguments as (metavar, help) pairs.

option_groups: tuple[DocOptionGroup, ...] = ()¶

The OPTIONS entries, partitioned into one or more groups. A command without explicit option groups carries a single untitled group.

subcommands: tuple[DocSubcommand, ...] = ()¶

For groups: the COMMANDS section entries, in listing order.

environment: tuple[tuple[str, str], ...] = ()¶

ENVIRONMENT entries as (variable_name, help) pairs.

files: tuple[str, ...] = ()¶

FILES entries (configuration search patterns).

exit_status: tuple[tuple[str, str], ...] = (('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.'))¶

EXIT STATUS entries as (code, meaning) pairs.

examples: tuple[tuple[str, str], ...] = ()¶

EXAMPLES entries as (description, command_line) pairs.

Collected from the command’s own examples attribute (see click_extra.commands.Command.examples). Empty for a command that declares none, in which case every backend omits the section entirely.

version: str | None = None¶

Version string for the .TH header.

date: str = ''¶

Date for the .TH header (YYYY-MM-DD).

manual: str | None = None¶

Manual name for the .TH header (the centered footer title).

authors: str | None = None¶

AUTHORS section content, or None to omit the section.

copyright: str | None = None¶

COPYRIGHT section content, or None to omit the section.

property title: str¶

The .TH page title: the command path, hyphen-joined and upper-cased.

to_roff()[source]¶

Render the full man page as a roff/troff string.

Return type:

str

to_markdown()[source]¶

Render the whole document as Markdown.

Same sections as to_roff(), in the same order, minus the roff .TH header, whose date, section number and manual name describe a man page rather than the command. The version survives, as a line under the title.

Return type:

str

to_dict()[source]¶

Render the whole document as a JSON-serializable mapping.

Subcommands are listed by name and one-line description only, never recursively: a consumer walking a deep tree asks for the child it cares about instead of paying for the whole tree at once. render_help() exposes the recursive variant separately, for the consumers that do want everything.

Return type:

dict[str, Any]

to_json(indent=2)[source]¶

Serialize to_dict() to a JSON string.

Return type:

str

click_extra.command_doc.extract_command_doc(command, ctx, *, version=None, date=None, manual=None, authors=None, copyright=None)[source]¶

Build a CommandDoc from a Click command and its context.

The context must have been created for command (for example via click.Command.make_context() with resilient_parsing=True), so that auto-generated environment-variable prefixes resolve correctly.

A version, date or authors left at None is resolved from the distribution metadata and the build moment, see _fill_overrides.

Return type:

CommandDoc

click_extra.command_doc.iter_command_contexts(command, prog_name=None)[source]¶

Walk a command tree, yielding (path, command, context) for each visible one.

Subcommands are discovered dynamically, through iter_subcommand_contexts(), so dynamically-registered commands are included, each under the name its parent registered it with rather than its own name. Hidden commands are skipped. Each context is built with resilient_parsing=True to avoid triggering required-argument errors, prompts, or eager-option side effects.

Return type:

Iterator[tuple[tuple[str, ...], Command, Context]]

click_extra.command_doc.iter_command_docs(command, prog_name=None, **overrides)[source]¶

Extract every visible command of a tree, yielding (path, doc) pairs.

Walks the tree with iter_command_contexts() and extracts each command into a CommandDoc. The header fields the keyword overrides leave unset (version, date, authors) are resolved once, from the root context, and shared by every page: the pages of one tree name the same program, so they look the same distribution up.

Return type:

Iterator[tuple[tuple[str, ...], CommandDoc]]

click_extra.command_doc.render_manpage(command, prog_name=None, ctx=None, **overrides)[source]¶

Render a single command’s man page as a roff string.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. Keyword overrides (version, date, manual, authors, copyright) are passed through to extract_command_doc().

Return type:

str

click_extra.command_doc.render_manpages(command, prog_name=None, **overrides)[source]¶

Render the whole command tree, one man page per (sub)command.

Returns an ordered mapping of {filename: roff} where each filename is the command path joined by hyphens plus the section suffix (like weather-forecast.1).

Return type:

dict[str, str]

click_extra.command_doc.write_manpages(command, target_dir, prog_name=None, **overrides)[source]¶

Render the command tree and write each man page into target_dir.

Creates target_dir if missing. Returns the list of written paths.

Return type:

list[Path]

click_extra.command_doc.install_manpages(command, prog_name=None, **overrides)[source]¶

Write the command tree’s man pages where man can find them.

Targets $XDG_DATA_HOME/man/man1 when that variable is set, else ~/.local/share/man/man1, expanded against the HOME in force at the call. Returns the written paths.

The environment is read here rather than at import time, through xdg_dir(), so a caller that sets XDG_DATA_HOME or HOME for one invocation (a test, a packaging script staging into a build root) is honored. This mirrors install_carapace_spec(), whose spec directory resolves the same way.

Return type:

list[Path]

class click_extra.command_doc.HelpFormat(*values)[source]¶

Bases: StrEnum

The formats render_help() renders.

The value is the spelling --help-format takes. Members are ordered alphabetically, which is also the order --help-format advertises them in. Adding a format is a member here, a description in HELP_FORMATS and a branch in render_help(): no new flag, no wider help screen. See Man-page for what each one is good for.

A member prints, compares, hashes and sorts as its value, so a plain string keeps working wherever a format is expected.

CARAPACE = 'carapace'¶
JSON = 'json'¶
JSON_FULL = 'json-full'¶
MAN = 'man'¶
MARKDOWN = 'markdown'¶
MARKDOWN_FULL = 'markdown-full'¶
click_extra.command_doc.HELP_FORMATS: dict[HelpFormat, str] = {HelpFormat.CARAPACE: 'Carapace completion spec (YAML). Doubles as a command-and-flag tree, and is the shape `carapace` itself consumes. Needs the `carapace` extra.', HelpFormat.JSON: 'This command as a JSON object: usage, description, arguments, options grouped as the help screen groups them, environment variables, files, exit codes, and its direct subcommands by name.', HelpFormat.JSON_FULL: 'Every command of the tree as JSON, under a `commands` array, each entry in the `json` shape.', HelpFormat.MAN: 'This command as a man page: the roff source a packager installs, which `--man` typesets for reading.', HelpFormat.MARKDOWN: 'This command as a Markdown document, one section per topic.', HelpFormat.MARKDOWN_FULL: 'Every command of the tree as one Markdown document, in tree order.'}¶

Each HelpFormat, mapped to its one-line description.

Note

The distinction the plain and -full variants draw is progressive disclosure. A plain render describes one command and names its children, so a reader (a tool or an agent, typically) descends one level at a time instead of pulling a whole tree into a context window to answer a question about one leaf. The -full variants exist for the opposite job: generating documentation, or diffing a CLI’s whole surface between two releases.

click_extra.command_doc.INSTALLABLE_FORMATS: frozenset[HelpFormat] = frozenset({HelpFormat.CARAPACE, HelpFormat.MAN})¶

The formats with a canonical place on disk their consumer reads them from.

A man page under a man directory, a Carapace spec under Carapace’s. These are the two renderings that are installed rather than read, which is what lets click-extra wrap offer them a destination (--output-dir, --install) and refuse one to the others. A JSON or Markdown document has no such place: nothing goes looking for it, so stdout and a shell redirection are the whole story.

click_extra.command_doc.render_help(command, help_format, prog_name=None, ctx=None, **overrides)[source]¶

Render command in one of the HelpFormat formats.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True, exactly like render_manpage(). Keyword overrides are passed through to extract_command_doc(), and ignored by the carapace format, which carries no version or authorship of its own.

Raises:

ValueError – on an unknown format, listing the known ones.

Return type:

str

click_extra.command_doc.MAN_TYPESETTERS: dict[str, tuple[tuple[str, ...], ...]] = {'html': (('mandoc', '-Thtml'), ('groff', '-Thtml', '-mandoc')), 'terminal': (('groff', '-man', '-Tutf8', '-rLL={width}n', '-P-c'), ('mandoc', '-Tutf8', '-Owidth={width}'))}¶

The programs typesetting roff, keyed by what they render it to, best first.

Each entry is a command line: the program, then its arguments, where :width: stands for the line length in columns. Both modes run the same two programs. groff is the GNU implementation found nearly everywhere a man page is; mandoc covers the BSDs and Alpine, which ship it instead.

  • terminal: the text format_manpage() sends to the pager for --man, read on stdin.

  • html: the page click_extra.sphinx.manpages publishes beside each man page, read from a file. mandoc comes first there: its HTML gives every section and option a semantic id anchor (#NAME, #SYNOPSIS, #config…), which prose can deep-link to.

Note

-P-c hands -c down to grotty, groff’s terminal driver, pinning the emphasis it produces to the character-backspace pairs strip_overstrike() removes, and read_manpage() with it under --accessible. Left to its own default a grotty recent enough writes SGR escape sequences instead, which that function cannot see: the manual then reaches a screen reader with its emphasis intact, and loses it altogether once the output is not a terminal and the codes are stripped as color. mandoc needs no counterpart: it overstrikes already.

Note

The man binary is deliberately not in this list, even though it is the tool being imitated. Reading roff from stdin is where the implementations diverge: GNU man takes -l -, while the BSD one wants a real file path. Driving the typesetter directly sidesteps a portability problem that buys nothing, since paging is handled here anyway.

click_extra.command_doc.find_typesetters(mode, **fields)[source]¶

Yield the command line of each typesetter installed for mode, best first.

Probes PATH for each program of MAN_TYPESETTERS and skips the absent ones. Each command line starts with the program’s resolved path, and its arguments are filled from fields, like width.

Parameters:

mode (str) – the MAN_TYPESETTERS key naming the output, terminal or html.

Return type:

Iterator[list[str]]

click_extra.command_doc.run_typesetter(argv, roff=None, *, timeout=None)[source]¶

Run a typesetter and return what it wrote to stdout.

The output is read as UTF-8, the encoding groff and mandoc write in whatever the locale of the platform.

Parameters:
  • argv (Sequence[str]) – the command line, as find_typesetters() yields it.

  • roff (str | None) – the man page source, sent on stdin. None sends nothing, for a command line naming the file to read.

  • timeout (float | None) – seconds the typesetter gets before it is stopped.

Raises:
Return type:

str

click_extra.command_doc.format_manpage(roff, width=None)[source]¶

Typeset roff into readable terminal text, or None if nothing can.

Tries each terminal typesetter of MAN_TYPESETTERS in turn and returns the output of the first that succeeds. Returns None when none of them is installed, which the caller is expected to degrade on rather than fail: a CLI that cannot find a typesetter is a CLI running somewhere that never had man pages to begin with (Windows, a slim container), and that is no reason for --man to error.

Parameters:
  • roff (str) – the man page source, as CommandDoc.to_roff() renders it.

  • width (int | None) – line length in columns. Defaults to the terminal’s own, so the result matches what man would have produced in the same window.

Return type:

str | None

click_extra.command_doc.strip_overstrike(text)[source]¶

Remove the character-backspace pairs a roff typesetter emits for emphasis.

A bold N is written N\x08N and an underlined one _\x08N, a convention inherited from line printers that a pager still renders as bold and underline today. Dropping the pair’s first half leaves the plain character.

The terminal-text counterpart of strip_ansi().

Return type:

str

click_extra.command_doc.read_manpage(command, ctx=None)[source]¶

Typeset a command’s manual and send it to the pager.

The reading counterpart of --help-format man, which emits the roff source a packager installs. Falls back to printing that source, with a warning naming what to install, when no typesetter is available: something on screen beats an error, and the source still carries every word of the manual.

Under --accessible the emphasis is stripped and the pager bypassed (echo_via_pager() streams instead). Both matter to the same reader: a pager is a cursor-driven takeover, and overstrike is worse than the ANSI codes accessible mode already removes, since a screen reader voices N\x08NA\x08AM\x08ME\x08E rather than skipping it.

Return type:

None

class click_extra.command_doc.ManOption(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help="Read the command's manual page and exit.", **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --man flag that typesets the command’s manual, pages it, and exits.

Eager and value-less, like ShowParamsOption. Part of the default option set injected by default_params(), so every @command and @group exposes it. Use @man_option to add it to a plain Click CLI.

Note

The flag is named --man, not --show-man or --man-page.

In the POSIX, GNU and BSD traditions a program does not emit its own man page through a flag: the page is a separate file read with man <prog>, either hand-written (BSD mdoc) or generated at build time from --help output (GNU help2man). Click Extra already covers that build-time path with write_manpages(), its help2man equivalent.

The one ecosystem that exposes a runtime flag is Perl’s Pod::Usage, whose convention is --help for the brief usage and bare --man for the full manual. --man also lines up with the neighbouring --help and --version informational flags, which use bare nouns with no show- prefix. --show-man and --man-page have no precedent outside Click Extra.

Note

That Perl convention is about reading a manual, so the flag typesets the page and sends it to the pager, the way man itself does. The roff source a build step ships is --help-format man, beside every other artifact this module renders. The two are one question apart: do you want to read the manual, or to ship it?

print_man(ctx, param, value)[source]¶

Typeset the invoked command’s manual, page it, then exit.

Return type:

None

class click_extra.command_doc.HelpFormatOption(param_decls=None, *, expose_value=False, is_eager=True, help='Render the command in the given format and exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --help-format option printing the command in one of the HelpFormat formats and exiting.

Eager and value-taking, unlike its --man neighbour. That bare flag typesets the same page and sends it to the pager, where --help-format man prints its roff source. It stays a flag of its own because a runtime manual flag has its own tradition (see ManOption).

Note

One option carrying a format, rather than one flag per format. A CLI’s option list is the most expensive real estate in its help screen, and every reader pays for it whether or not they will ever export anything: a family of --help-json, --help-markdown and --help-carapace flags would widen the label column of every screen, forever, one line per format anyone ever adds. Here a new format costs a HelpFormat member and nothing on screen.

Note

The rendered output is deliberately colorless whatever --color says. Every format here is meant to be piped into something (a file, a parser, a model), and ANSI escapes in a JSON string or a Markdown fence are noise to all of them. --help remains the colorized human view.

print_help_format(ctx, param, value)[source]¶

Render the invoked command in the requested format, then exit.

Return type:

None