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 noconsole_scriptsentry point;discovering subcommands dynamically through
click.Group.list_commands()/click.Group.get_command()with a live context;honoring Click’s
\bno-rewrap marker (rendered as roff.nf/.fi);rendering boolean flags (
--foo/--no-foo) and skipping hidden commands and options;mirroring Cloup option groups as
.SSsubsections of OPTIONS (ungrouped options fall under anOther optionsheading), matching the help screen;emitting ENVIRONMENT (from auto-generated env vars), FILES (from the
--configsearch 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
2for usage errors (UsageError),1for aborts, and0on success. A real Ctrl+C ends the process bySIGINTinstead, which a shell reports as130.
- click_extra.command_doc.normalize_examples(examples)[source]¶
Validate and freeze a command’s
examplesinto(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.
Noneand an empty sequence both yield an empty tuple.
- class click_extra.command_doc.DocOptionItem(names, metavar, help, required, optional_value=False, choices=())[source]¶
Bases:
objectA single OPTIONS entry, extracted from a Click option.
- names: tuple[str, ...]¶
All literal spellings: primary
optsfollowed bysecondary_opts(so--foo/--no-fooboolean flags render both).
- metavar: str | None¶
The rendered metavar, or
Nonewhen the option takes no value (boolean flags and counters).
- 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. Seeunlisted_choicesfor the rendered subset.
- property unlisted_choices: tuple[str, ...]¶
The choices the metavar does not already spell out.
A
Choicerenders 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.
- class click_extra.command_doc.DocSubcommand(name, short_help, aliases=())[source]¶
Bases:
objectOne COMMANDS entry: a subcommand as its parent lists it.
- short_help: str¶
Its one-line description, from
full_short_help().
- class click_extra.command_doc.DocOptionGroup(options, title=None, help=None)[source]¶
Bases:
objectA 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 withtitle=None: it renders as a flat OPTIONS list with no.SSsubsection 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.Nonefor the implicit single group of an ungrouped command (no heading emitted).
- 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:
objectA whole man page in structured form, ready to render to roff.
One
CommandDocmaps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it withextract_command_doc()and serialize withto_roff().- synopsis_pieces: tuple[str, ...] = ()¶
Usage metavars after the command name (
[OPTIONS],CITY, …).
- 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.
- 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
examplesattribute (seeclick_extra.commands.Command.examples). Empty for a command that declares none, in which case every backend omits the section entirely.
- to_markdown()[source]¶
Render the whole document as Markdown.
Same sections as
to_roff(), in the same order, minus the roff.THheader, 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:
- 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.
- click_extra.command_doc.extract_command_doc(command, ctx, *, version=None, date=None, manual=None, authors=None, copyright=None)[source]¶
Build a
CommandDocfrom a Click command and its context.The context must have been created for
command(for example viaclick.Command.make_context()withresilient_parsing=True), so that auto-generated environment-variable prefixes resolve correctly.A
version,dateorauthorsleft atNoneis resolved from the distribution metadata and the build moment, see_fill_overrides.- Return type:
- 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 ownname. Hidden commands are skipped. Each context is built withresilient_parsing=Trueto avoid triggering required-argument errors, prompts, or eager-option side effects.
- 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 aCommandDoc. 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.
- 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
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True. Keyword overrides (version,date,manual,authors,copyright) are passed through toextract_command_doc().- Return type:
- 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 (likeweather-forecast.1).
- 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_dirif missing. Returns the list of written paths.
- click_extra.command_doc.install_manpages(command, prog_name=None, **overrides)[source]¶
Write the command tree’s man pages where
mancan find them.Targets
$XDG_DATA_HOME/man/man1when that variable is set, else~/.local/share/man/man1, expanded against theHOMEin 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 setsXDG_DATA_HOMEorHOMEfor one invocation (a test, a packaging script staging into a build root) is honored. This mirrorsinstall_carapace_spec(), whose spec directory resolves the same way.
- class click_extra.command_doc.HelpFormat(*values)[source]¶
Bases:
StrEnumThe formats
render_help()renders.The value is the spelling
--help-formattakes. Members are ordered alphabetically, which is also the order--help-formatadvertises them in. Adding a format is a member here, a description inHELP_FORMATSand a branch inrender_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
-fullvariants 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-fullvariants 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
mandirectory, a Carapace spec under Carapace’s. These are the two renderings that are installed rather than read, which is what letsclick-extra wrapoffer 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
HelpFormatformats.Reuses
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True, exactly likerender_manpage(). Keyword overrides are passed through toextract_command_doc(), and ignored by thecarapaceformat, which carries no version or authorship of its own.- Raises:
ValueError – on an unknown format, listing the known ones.
- Return type:
- 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.groffis the GNU implementation found nearly everywhere a man page is;mandoccovers the BSDs and Alpine, which ship it instead.terminal: the textformat_manpage()sends to the pager for--man, read on stdin.html: the pageclick_extra.sphinx.manpagespublishes beside each man page, read from a file.mandoccomes first there: its HTML gives every section and option a semanticidanchor (#NAME,#SYNOPSIS,#config…), which prose can deep-link to.
Note
-P-chands-cdown togrotty, groff’s terminal driver, pinning the emphasis it produces to the character-backspace pairsstrip_overstrike()removes, andread_manpage()with it under--accessible. Left to its own default agrottyrecent 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.mandocneeds no counterpart: it overstrikes already.Note
The
manbinary is deliberately not in this list, even though it is the tool being imitated. Reading roff from stdin is where the implementations diverge: GNUmantakes-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
PATHfor each program ofMAN_TYPESETTERSand skips the absent ones. Each command line starts with the program’s resolved path, and its arguments are filled fromfields, likewidth.- Parameters:
mode (
str) – theMAN_TYPESETTERSkey naming the output,terminalorhtml.- Return type:
- 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
groffandmandocwrite in whatever the locale of the platform.- Parameters:
- Raises:
subprocess.SubprocessError – the typesetter exits with an error or outlives
timeout.OSError – the typesetter cannot start.
- Return type:
- click_extra.command_doc.format_manpage(roff, width=None)[source]¶
Typeset roff into readable terminal text, or
Noneif nothing can.Tries each
terminaltypesetter ofMAN_TYPESETTERSin turn and returns the output of the first that succeeds. ReturnsNonewhen 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--manto error.
- click_extra.command_doc.strip_overstrike(text)[source]¶
Remove the character-backspace pairs a roff typesetter emits for emphasis.
A bold
Nis writtenN\x08Nand 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:
- 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
--accessiblethe 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 voicesN\x08NA\x08AM\x08ME\x08Erather than skipping it.- Return type:
- 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:
ExtraOptionA pre-configured
--manflag that typesets the command’s manual, pages it, and exits.Eager and value-less, like
ShowParamsOption. Part of the default option set injected bydefault_params(), so every@commandand@groupexposes it. Use@man_optionto add it to a plain Click CLI.Note
The flag is named
--man, not--show-manor--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 (BSDmdoc) or generated at build time from--helpoutput (GNUhelp2man). Click Extra already covers that build-time path withwrite_manpages(), itshelp2manequivalent.The one ecosystem that exposes a runtime flag is Perl’s
Pod::Usage, whose convention is--helpfor the brief usage and bare--manfor the full manual.--manalso lines up with the neighbouring--helpand--versioninformational flags, which use bare nouns with noshow-prefix.--show-manand--man-pagehave 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
manitself 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?
- 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:
ExtraOptionA pre-configured
--help-formatoption printing the command in one of theHelpFormatformats and exiting.Eager and value-taking, unlike its
--manneighbour. That bare flag typesets the same page and sends it to the pager, where--help-format manprints its roff source. It stays a flag of its own because a runtime manual flag has its own tradition (seeManOption).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-markdownand--help-carapaceflags would widen the label column of every screen, forever, one line per format anyone ever adds. Here a new format costs aHelpFormatmember and nothing on screen.Note
The rendered output is deliberately colorless whatever
--colorsays. 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.--helpremains the colorized human view.