:mod:`cloup` ============ .. py:module:: cloup .. autoapi-nested-parse:: Top-level package for cloup. Subpackages ----------- .. toctree:: :titlesonly: :maxdepth: 2 constraints/index.rst Submodules ---------- .. toctree:: :titlesonly: :maxdepth: 1 formatting/index.rst styling/index.rst warnings/index.rst Classes ------- .. autosummary:: ~cloup.HelpTheme ~cloup.Style ~cloup.Color ~cloup.HelpFormatter ~cloup.Context ~cloup.GroupedOption ~cloup.OptionGroup ~cloup.OptionGroupMixin ~cloup.Section ~cloup.SectionMixin ~cloup.BaseCommand ~cloup.Command ~cloup.Group ~cloup.ConstraintMixin Functions --------- .. autosummary:: ~cloup.option ~cloup.option_group ~cloup.command ~cloup.group ~cloup.constraint Attributes ---------- .. autoapisummary:: cloup.__author__ cloup.__email__ cloup.__version__ cloup.__version_tuple__ Contents -------- .. data:: __author__ :annotation: = Gianluca Gippetto .. data:: __email__ :annotation: = gianluca.gippetto@gmail.com .. data:: __version__ .. data:: __version_tuple__ .. class:: HelpTheme Bases: :py:obj:`NamedTuple` A collection of styles for several elements of the help page. A "style" is just a function or a callable that takes a string and returns a styled version of it. This means you can use your favorite styling/color library (like rich, colorful etc). Nonetheless, given that Click has some basic styling functionality built-in, Cloup provides the :class:`Style` class, which is a wrapper of the ``click.style`` function. :param invoked_command: Style of the invoked command name (in Usage). :param command_help: Style of the invoked command description (below Usage). :param heading: Style of help section headings. :param constraint: Style of an option group constraint description. :param section_help: Style of the help text of a section (the optional paragraph below the heading). :param col1: Style of the first column of a definition list (options and command names). :param col2: Style of the second column of a definition list (help text). :param epilog: Style of the epilog. .. attribute:: invoked_command :annotation: :IStyle Style of the invoked command name (in Usage). .. attribute:: command_help :annotation: :IStyle Style of the invoked command description (below Usage). .. attribute:: heading :annotation: :IStyle Style of help section headings. .. attribute:: constraint :annotation: :IStyle Style of an option group constraint description. .. attribute:: section_help :annotation: :IStyle Style of the help text of a section (the optional paragraph below the heading). .. attribute:: col1 :annotation: :IStyle Style of the first column of a definition list (options and command names). .. attribute:: col2 :annotation: :IStyle Style of the second column of a definition list (help text). .. attribute:: epilog :annotation: :IStyle Style of the epilog. .. method:: with_(self, invoked_command = None, command_help = None, heading = None, constraint = None, section_help = None, col1 = None, col2 = None, epilog = None) .. method:: dark() :staticmethod: A theme assuming a dark terminal background color. .. method:: light() :staticmethod: A theme assuming a light terminal background color. .. class:: Style Wraps :func:`click.style` for a better integration with :class:`HelpTheme`. Available colors are defined as static constants in :class:`Color`. Arguments are set to ``None`` by default. Passing ``False`` to boolean args or ``Color.reset`` as color causes a reset code to be inserted. With respect to :func:`click.style`, this class: - has an argument less, ``reset``, which is always ``True`` - add the ``text_transform``. .. warning:: The arguments ``overline``, ``italic`` and ``strikethrough`` are only supported in Click 8 and will be ignored if you are using Click 7. :param fg: foreground color :param bg: background color :param bold: :param dim: :param underline: :param overline: :param italic: :param blink: :param reverse: :param strikethrough: :param text_transform: a generic string transformation; useful to apply functions like ``str.upper`` .. versionadded:: 0.8.0 .. attribute:: fg :annotation: :Optional[str] .. attribute:: bg :annotation: :Optional[str] .. attribute:: bold :annotation: :Optional[bool] .. attribute:: dim :annotation: :Optional[bool] .. attribute:: underline :annotation: :Optional[bool] .. attribute:: overline :annotation: :Optional[bool] .. attribute:: italic :annotation: :Optional[bool] .. attribute:: blink :annotation: :Optional[bool] .. attribute:: reverse :annotation: :Optional[bool] .. attribute:: strikethrough :annotation: :Optional[bool] .. attribute:: text_transform :annotation: :Optional[IStyle] .. method:: __call__(self, text) .. class:: Color Bases: :py:obj:`cloup._util.FrozenSpace` Colors accepted by :class:`Style` and :func:`click.style`. .. attribute:: black :annotation: = black .. attribute:: red :annotation: = red .. attribute:: green :annotation: = green .. attribute:: yellow :annotation: = yellow .. attribute:: blue :annotation: = blue .. attribute:: magenta :annotation: = magenta .. attribute:: cyan :annotation: = cyan .. attribute:: white :annotation: = white .. attribute:: reset :annotation: = reset .. attribute:: bright_black :annotation: = bright_black .. attribute:: bright_red :annotation: = bright_red .. attribute:: bright_green :annotation: = bright_green .. attribute:: bright_yellow :annotation: = bright_yellow .. attribute:: bright_blue :annotation: = bright_blue .. attribute:: bright_magenta :annotation: = bright_magenta .. attribute:: bright_cyan :annotation: = bright_cyan .. attribute:: bright_white :annotation: = bright_white .. class:: HelpFormatter(indent_increment = 2, width = None, max_width = None, col1_max_width = 30, col2_min_width = 35, col_spacing = 2, row_sep = '', theme = HelpTheme()) Bases: :py:obj:`click.HelpFormatter` A custom help formatter. Features include: - more attributes for controlling the output of the formatter - a ``col1_width`` parameter in :meth:`write_dl` that allows Cloup to align multiple definition lists without resorting to hacks - a "linear layout" for definition lists that kicks in when the available terminal width is not enough for the standard 2-column layout (see argument ``col2_min_width``) - the first column width, when not explicitly given in ``write_dl`` is computed excluding the rows that exceed ``col1_max_width`` (called ``col_max`` in ``write_dl`` for compatibility with Click). .. versionadded:: 0.8.0 :param indent_increment: width of each indentation increment. :param width: content line width; by default it's initialized to ``min(terminal_width - 1, max_width)`` where ``max_width`` is another argument. :param max_width: maximum content line width (equivalent to ``Context.max_content_width``). Used to compute ``width`` when it is not provided, ignored otherwise. :param col1_max_width: the maximum width of the first column of a definition list; as in Click, if the text of a row exceeds this threshold, the 2nd column is printed on a new line. :param col2_min_width: the minimum width for the second column of a definition list; if the available space is less than this value, the formatter switches from the standard 2-column layout to the "linear layout" (that this decision is taken for each definition list). If you want to always use the linear layout, you can set this argument to a very high number (or ``math.inf``). If you never want it (not recommended), you can set this argument to zero. :param col_spacing: the number of spaces between the column boundaries of a definition list. :param row_sep: a string printed after each row of a definition list (including the last). :param theme: an :class:`~cloup.HelpTheme` instance specifying how to style the various elements of the help page. .. method:: settings(*, width = None, max_width = None, indent_increment = None, col1_max_width = None, col2_min_width = None, col_spacing = None, row_sep = None, theme = None) :staticmethod: A utility method for creating a ``formatter_settings`` dictionary to pass as context settings or command attribute. This method exists for one only reason: it enables auto-complete for formatter options, thus improving the developer experience. Parameters are pretty self-explanatory. Refer to :class:`HelpFormatter` in case of doubts. .. method:: available_width(self) :property: .. method:: write(self, *strings) Writes a unicode string into the internal buffer. .. method:: write_usage(self, prog, args = '', prefix = 'Usage:') Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: The prefix for the first line. Defaults to ``"Usage: "``. .. method:: write_command_help_text(self, cmd) .. method:: write_heading(self, heading, newline = True) Writes a heading into the buffer. .. method:: write_many_sections(self, sections, aligned = True) .. method:: write_aligned_sections(self, sections) Writes multiple aligned definition lists. .. method:: write_section(self, s, col1_width = None) .. method:: write_text(self, text, style = identity) Writes re-indented text into the buffer. This rewraps and preserves paragraphs. .. method:: compute_col1_width(self, rows, max_width) .. method:: write_dl(self, rows, col_max = None, col_spacing = None, col1_width = None) Writes a definition list into the buffer. This is how options and commands are usually formatted. If there's enough space, definition lists are rendered as a 2-column pseudo-table: if the first column text of a row doesn't fit in the provided/computed ``col1_width``, the 2nd column is printed on the following line. If the available space for the 2nd column is below ``self.col2_min_width``, the 2nd "column" is always printed below the 1st, indented with a minimum of 3 spaces (or one ``indent_increment`` if that's greater than 3). :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width for the 1st column of a definition list; this argument is here to not break compatibility with Click; if provided, it overrides the attribute ``self.col1_max_width``. :param col_spacing: number of spaces between the first and second column; this argument is here to not break compatibility with Click; if provided, it overrides ``self.col_spacing``. :param col1_width: the width to use for the first column; if not provided, it's computed as the length of the longest string under ``self.col1_max_width``; useful when you need to align multiple definition lists. .. method:: write_tabular_dl(self, rows, col1_width, col_spacing, col2_width) Formats a definition list as a 2-column "pseudo-table". If the first column of a row exceeds ``col1_width``, the 2nd column is written on the subsequent line. This is the standard way of formatting definition lists and it's the default if there's enough space. .. method:: write_linear_dl(self, dl) Formats a definition list as a "linear list". This is the default when the available width for the definitions (2nd column) is below ``self.col2_min_width``. .. method:: write_epilog(self, epilog) .. method:: __repr__(self) Return repr(self). .. class:: Context(*ctx_args, align_option_groups = None, align_sections = None, show_constraints = None, formatter_settings = {}, **ctx_kwargs) Bases: :py:obj:`click.Context` A custom context for Cloup. Look up :class:`click.Context` for the list of all arguments. .. versionadded:: 0.8.0 :param ctx_args: arguments forwarded to :class:`click.Context`. :param ctx_kwargs: keyword arguments forwarded to :class:`click.Context`. :param align_option_groups: if True, align the definition lists of all option groups of a command. You can override this by setting the corresponding argument of ``Command`` (but you probably shouldn't: be consistent). :param align_sections: if True, align the definition lists of all subcommands of a group. You can override this by setting the corresponding argument of ``Group`` (but you probably shouldn't: be consistent). :param show_constraints: whether to include a "Constraint" section in the command help (if at least one constraint is defined). :param formatter_settings: keyword arguments forwarded to :class:`HelpFormatter` in ``make_formatter``. This args are merged with those of the (eventual) parent context and then merged again (being overridden) by those of the command. **Tip**: use the static method :meth:`HelpFormatter.opts` to create this dictionary, so that you can be guided by your IDE. .. attribute:: formatter_class :annotation: :Type[cloup.formatting.HelpFormatter] .. method:: get_formatter_settings(self) .. method:: make_formatter(self) Creates the :class:`~click.HelpFormatter` for the help and usage output. To quickly customize the formatter class used without overriding this method, set the :attr:`formatter_class` attribute. .. versionchanged:: 8.0 Added the :attr:`formatter_class` attribute. .. method:: settings(*, auto_envvar_prefix = None, default_map = None, terminal_width = None, max_content_width = None, resilient_parsing = None, allow_extra_args = None, allow_interspersed_args = None, ignore_unknown_options = None, help_option_names = None, token_normalize_func = None, color = None, show_default = None, align_option_groups = None, align_sections = None, show_constraints = None, formatter_settings = None) :staticmethod: Utility method for creating a ``context_settings`` dictionary. :param auto_envvar_prefix: the prefix to use for automatic environment variables. If this is `None` then reading from environment variables is disabled. This does not affect manually set environment variables which are always read. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right. :param resilient_parsing: if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support. :param allow_extra_args: if this is set to `True` then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. :param show_default: Show defaults for all options. If not set, defaults to the value from a parent context. Overrides an option's ``show_default`` argument. :param align_option_groups: if True, align the definition lists of all option groups of a command. You can override this by setting the corresponding argument of ``Command`` (but you probably shouldn't: be consistent). :param align_sections: if True, align the definition lists of all subcommands of a group. You can override this by setting the corresponding argument of ``Group`` (but you probably shouldn't: be consistent). :param show_constraints: whether to include a "Constraint" section in the command help (if at least one constraint is defined). :param formatter_settings: keyword arguments forwarded to :class:`HelpFormatter` in ``make_formatter``. This args are merged with those of the (eventual) parent context and then merged again (being overridden) by those of the command. **Tip**: use the static method :meth:`HelpFormatter.opts` to create this dictionary, so that you can be guided by your IDE. .. class:: GroupedOption(*args, group = None, **attrs) Bases: :py:obj:`click.Option` A click.Option with an extra field ``group`` of type OptionGroup .. class:: OptionGroup(name, help = None, constraint = None, hidden = False) .. method:: options(self) :property: .. method:: get_help_records(self, ctx) .. method:: option(self, *param_decls, **attrs) .. method:: __iter__(self) .. method:: __getitem__(self, i) .. method:: __len__(self) .. method:: __repr__(self) Return repr(self). .. method:: __str__(self) Return str(self). .. class:: OptionGroupMixin(*args, align_option_groups = None, **kwargs) Implements support to option groups. .. versionchanged:: 0.8.0 This mixin now relies on ``cloup.HelpFormatter`` to align help sections. If a ``click.HelpFormatter`` is used with a ``TypeError`` is raised. .. versionchanged:: 0.8.0 Removed ``format_option_group``. Added ``get_default_option_group`` and ``make_option_group_help_section``. .. versionadded:: 0.5.0 .. important:: In order to check the constraints defined on the option groups, a command must inherits from :class:`cloup.ConstraintMixin` too! .. method:: get_ungrouped_options(self, ctx) .. method:: make_option_group_help_section(self, group, ctx) Returns a HelpSection for an OptionGroup, i.e. an object containing the title, the optional description and the options' definitions for this option group. .. versionadded:: 0.8.0 .. method:: must_align_option_groups(self, ctx, default=True) .. versionadded:: 0.8.0 .. method:: get_default_option_group(self, ctx) .. versionadded:: 0.8.0 .. method:: format_options(self, ctx, formatter) .. function:: option(*param_decls, group = None, cls = GroupedOption, **attrs) .. function:: option_group(name: str, help: str, *options: OptionAdder, constraint: Optional[cloup.constraints.Constraint] = None, hidden: bool = False) -> OptionGroupAdder option_group(name: str, *options: OptionAdder, help: Optional[str] = None, constraint: Optional[cloup.constraints.Constraint] = None, hidden: bool = False) -> OptionGroupAdder Returns a decorator that annotates a function with an option group. The ``help`` is an optional description and can be provided either as keyword argument or as 2nd positional argument after the ``name`` of the group:: # help as keyword argument @option_group(name, *options, help=None, ...) # help as 2nd positional argument @option_group(name, help, *options, ...) :param name: this is shown as heading of the help section describing the option group. :param help: an optional description shown below the name; can be provided as keyword argument or 2nd positional argument. :param options: an arbitrary number of decorators like `click.option`, which annotate the input function with one ``Option``. :param constraint: an optional instance of :class:`~cloup.constraints.Constraint` (see :doc:`constraints` for more info); a description of the constraint will be shown between squared brackets aside the option group title (or below it if too long). :param hidden: if ``True``, the option group and all its options are hidden from the help page (all contained options will have their ``hidden`` attribute set to ``True``). .. class:: Section(title, commands = (), sorted = False) A group of (sub)commands to show in the same help section of a ``MultiCommand``. You can use sections with any `Command` that inherits from :class:`SectionMixin`. .. versionchanged:: 0.6.0 Removed the deprecated old name ``GroupSection``. .. versionchanged:: 0.5.0 Introduced the new name ``Section`` and deprecated the old ``GroupSection``. .. method:: sorted(cls, title, commands = ()) :classmethod: .. method:: add_command(self, cmd, name = None) .. method:: list_commands(self) .. method:: __len__(self) .. method:: __repr__(self) Return repr(self). .. class:: SectionMixin(*args, commands = None, sections = (), align_sections = None, **kwargs) Adds to a click.MultiCommand the possibility to organize its subcommands in multiple help sections. Sections can be specified in the following ways: #. passing a list of :class:`Section` objects to the constructor setting the argument ``sections`` #. using :meth:`add_section` to add a single section #. using :meth:`add_command` with the argument `section` set Commands not assigned to any user-defined section are added to the "default section", whose title is "Commands" or "Other commands" depending on whether it is the only section or not. The default section is the last shown section in the help and its commands are listed in lexicographic order. .. versionchanged:: 0.8.0 This mixin now relies on ``cloup.HelpFormatter`` to align help sections. If a ``click.HelpFormatter`` is used with a ``TypeError`` is raised. .. versionchanged:: 0.8.0 Removed ``format_section``. Added ``make_commands_help_section``. .. versionadded:: 0.5.0 .. method:: add_section(self, section) Adds a :class:`Section` to this group. You can add the same section object a single time. .. method:: section(self, title, *commands, **attrs) Creates a new :class:`Section`, adds it to this group and returns it. .. method:: add_command(self, cmd, name = None, section = None) Adds a new command. If ``section`` is None, the command is added to the default section. .. method:: list_sections(self, ctx, include_default_section = True) Returns the list of all sections in the "correct order". if ``include_default_section=True`` and the default section is non-empty, it will be included at the end of the list. .. method:: make_commands_help_section(self, section) .. method:: must_align_sections(self, ctx, default = True) .. method:: format_commands(self, ctx, formatter) .. class:: BaseCommand(*args, formatter_settings = {}, **kwargs) Bases: :py:obj:`click.Command` Base class for cloup commands. * It back-ports a feature from Click v8.0-a1, i.e. the ``context_class`` class attribute, which is set to ``cloup.Context``. * It adds a ``formatter_settings`` instance attribute. .. versionadded:: 0.8.0 .. attribute:: context_class :annotation: :Type[cloup._context.Context] .. method:: make_context(self, info_name, args, parent=None, **extra) This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. To quickly customize the context class used without overriding this method, set the :attr:`context_class` attribute. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the command. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. .. versionchanged:: 8.0 Added the :attr:`context_class` attribute. .. method:: format_epilog(self, ctx, formatter) Writes the epilog into the formatter if it exists. .. method:: format_help_text(self, ctx, formatter) Writes the help text to the formatter if it exists. .. class:: Command(*click_args, formatter_settings = {}, constraints = (), show_constraints = False, align_option_groups = None, **click_kwargs) Bases: :py:obj:`cloup.constraints.ConstraintMixin`, :py:obj:`cloup._option_groups.OptionGroupMixin`, :py:obj:`BaseCommand` A ``click.Command`` supporting option groups and constraints. .. versionchanged:: 0.8.0 This class now inherits from :class:`cloup.BaseCommand`. .. class:: Group(name = None, commands = None, sections = (), align_sections = None, formatter_settings = {}, **attrs) Bases: :py:obj:`cloup._sections.SectionMixin`, :py:obj:`BaseCommand`, :py:obj:`click.Group` A ``click.Group`` that allows to organize its subcommands in multiple help sections and and whose subcommands are, by default, of type :class:`cloup.Command`. This class is just a :class:`click.Group` mixed with :class:`SectionMixin` that overrides the decorators :meth:`command` and :meth:`group` so that a ``section`` for the created subcommand can be specified. See the docstring of the two superclasses for more details. .. versionchanged:: 0.8.0 This class now inherits from :class:`cloup.BaseCommand`. .. method:: command(self, name = None, cls = None, section = None, **kwargs) Creates a new command and adds it to this group. .. method:: group(self, name = None, cls = None, section = None, **kwargs) A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` and immediately registers the created group with this group by calling :meth:`add_command`. To customize the group class used, set the :attr:`group_class` attribute. .. versionchanged:: 8.0 Added the :attr:`group_class` attribute. .. function:: command(name = None, cls = Command, **attrs) Decorator that creates a new command using the wrapped function as callback. The only differences with respect to ``click.commands`` are: - this decorator creates a ``cloup.Command`` by default; - this decorator supports ``@constraint``. :param name: name of the command :param cls: type of click.Command :param attrs: any argument you can pass to :func:`click.command` .. function:: group(name = None, cls = Group, **attrs) Decorator for creating a new :class:`Group`. .. note:: If you use static type checking, note that the ``cls`` optional argument of this function must be of type ``cloup.Group``, not ``click.Group``. :param name: name of the command :param cls: type of ``cloup.Group`` :param attrs: any argument you can pass to :func:`click.group` .. class:: ConstraintMixin(*args, constraints = (), show_constraints = None, **kwargs) Provides support to constraints. .. method:: parse_args(self, ctx, args) .. method:: get_param_by_name(self, name) .. method:: get_params_by_name(self, names) .. method:: format_constraints(self, ctx, formatter) .. method:: format_help(self, ctx, formatter) .. function:: constraint(constr, params) Registers a constraint.