Skip to content

kaptive.db.cli

Command-line interface commands for managing and querying Kaptive reference databases.

This module provides CLI command implementations for listing installed databases, downloading or adding new databases, updating installed databases, extracting FASTA sequences (loci, genes, proteins), printing database metadata, and resetting local database caches.

Classes:

Add

Add()

              flowchart TD
              kaptive.db.cli.Add[Add]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Add
                


              click kaptive.db.cli.Add href "" "kaptive.db.cli.Add"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

🔗 Add a custom reference database from a GitHub repository.

Fetches GenBank and TOML metadata files from any specified GitHub owner/repo/branch, compiles the database, and registers it in the local cache.

Methods:

  • __call__

    Executes retrieval, compilation, and registration of a custom GitHub database.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configures argument parser options for the add subcommand.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Executes retrieval, compilation, and registration of a custom GitHub database.

Parameters:

  • args

    (Namespace) –

    Parsed CLI arguments containing database, owner, repo_name, and optional branch.

See Also

DatabaseManager.add

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Executes retrieval, compilation, and registration of a custom GitHub database.

    Args:
        args (argparse.Namespace): Parsed CLI arguments containing `database`, `owner`,
            `repo_name`, and optional `branch`.

    See Also:
        [`DatabaseManager.add`][kaptive.db.manager.DatabaseManager.add]
    """
    from kaptive.db import DatabaseManager

    self.cli.msg(f"⤵️ Adding {args.database} from {args.owner}/{args.repo_name}/{args.branch}")  # type: ignore
    if db := DatabaseManager.add(args.owner, args.repo_name, args.database, args.branch):
        self.cli.msg(f"✅ Added {db.metadata.name} v{db.metadata.version} successfully!")  # type: ignore
    else:
        self.cli.msg("❌ Failed to add database! Is it already installed?")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configures argument parser options for the add subcommand.

Source code in src/kaptive/db/cli.py
def setup_arguments(self) -> None:
    r"""Configures argument parser options for the `add` subcommand."""
    opts = self.parser.add_argument_group("📥 Inputs")  # type: ignore
    opts.add_argument("database", help="Name for the new database")

    opts = self.parser.add_argument_group(Colors.wrap("🌐 GitHub Details", Colors.BOLD))  # type: ignore
    opts.add_argument("owner", help="GitHub repository owner")
    opts.add_argument("repo_name", help="GitHub repository name")
    opts.add_argument(
        "-b",
        "--branch",
        help="GitHub repository branch (default: main)",
        default="main",
        nargs="?",
    )

Available

Available()

              flowchart TD
              kaptive.db.cli.Available[Available]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Available
                


              click kaptive.db.cli.Available href "" "kaptive.db.cli.Available"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

🌐 List all available official databases for installation.

Displays the keywords of all officially supported databases curated in GitHub repositories that can be installed via kaptive db install <keyword>.

Aliases

avail

Methods:

  • __call__

    Executes the available command to print known database keywords.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Executes the available command to print known database keywords.

Parameters:

  • args

    (Namespace) –

    Parsed command-line arguments.

See Also

DatabaseManager.known

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Executes the `available` command to print known database keywords.

    Args:
        args (argparse.Namespace): Parsed command-line arguments.

    See Also:
        [`DatabaseManager.known`][kaptive.db.manager.DatabaseManager.known]
    """
    from kaptive.db import DatabaseManager

    if known := DatabaseManager.known():
        print("\n".join(known))
    else:
        self.cli.msg("❌ No available databases found")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Database

Database()

              flowchart TD
              kaptive.db.cli.Database[Database]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Database
                


              click kaptive.db.cli.Database href "" "kaptive.db.cli.Database"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

📦 Manage local and remote Kaptive databases.

Aggregates subcommands for listing, installing, updating, resetting, adding, extracting, and displaying metadata for Kaptive databases.

Aliases

db

Methods:

  • __call__

    Execute command business logic for parsed arguments.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Registers subcommands for database management.

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Execute command business logic for parsed arguments.

Parameters:

  • args

    (Namespace) –

    Parsed command line argument namespace.

Source code in src/kaptive/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Execute command business logic for parsed arguments.

    Args:
        args (argparse.Namespace): Parsed command line argument namespace.
    """
    pass

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Registers subcommands for database management.

Source code in src/kaptive/db/cli.py
def register_subcommands(self) -> None:
    r"""Registers subcommands for database management."""
    self.subcommands = [
        List(),
        Available(),
        Add(),
        Install(),
        Update(),
        Reset(),
        Extract(),
        Metadata(),
    ]

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Extract

Extract()

              flowchart TD
              kaptive.db.cli.Extract[Extract]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Extract
                


              click kaptive.db.cli.Extract href "" "kaptive.db.cli.Extract"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

📤 Extract database records in FASTA format.

Aggregates subcommands for extracting locus nucleotide sequences (loci), gene coding sequences (genes), and translated amino acid sequences (proteins).

Methods:

  • __call__

    Execute command business logic for parsed arguments.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Creates shared parent parser containing common output arguments.

  • register_subcommands

    Registers extraction subcommands (Loci, Genes, Proteins).

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Execute command business logic for parsed arguments.

Parameters:

  • args

    (Namespace) –

    Parsed command line argument namespace.

Source code in src/kaptive/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Execute command business logic for parsed arguments.

    Args:
        args (argparse.Namespace): Parsed command line argument namespace.
    """
    pass

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser

Creates shared parent parser containing common output arguments.

Returns:

  • ArgumentParser

    argparse.ArgumentParser: Parser configured with --out and --use-indices flags.

Source code in src/kaptive/db/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser:
    r"""Creates shared parent parser containing common output arguments.

    Returns:
        argparse.ArgumentParser: Parser configured with `--out` and `--use-indices` flags.
    """
    parser = argparse.ArgumentParser(add_help=False)

    opts = parser.add_argument_group("📥 Inputs")
    opts.add_argument("database", help="Database path or keyword (see: `kaptive db list`)")

    opts = parser.add_argument_group("📤 Outputs")
    opts.add_argument(
        "-o",
        "--out",
        default="-",
        metavar="FILE",
        help="Output file to write fasta to (default: stdout)",
    )
    opts.add_argument(
        "--use-indices",
        action="store_true",
        help="Use numeric indices instead of string IDs for fasta headers",
    )
    return parser

register_subcommands

register_subcommands() -> None

Registers extraction subcommands (Loci, Genes, Proteins).

Source code in src/kaptive/db/cli.py
def register_subcommands(self) -> None:
    r"""Registers extraction subcommands (`Loci`, `Genes`, `Proteins`)."""
    self.subcommands = [Loci(), Genes(), Proteins()]

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Genes

Genes()

              flowchart TD
              kaptive.db.cli.Genes[Genes]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Genes
                


              click kaptive.db.cli.Genes href "" "kaptive.db.cli.Genes"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

🧩 Extract gene coding sequences in FASTA format.

Methods:

  • __call__

    Extracts gene nucleotide FASTA sequences to output stream.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Extracts gene nucleotide FASTA sequences to output stream.

Parameters:

  • args

    (Namespace) –

    Parsed CLI arguments containing database, out, and use_indices.

See Also

Database.load

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Extracts gene nucleotide FASTA sequences to output stream.

    Args:
        args (argparse.Namespace): Parsed CLI arguments containing `database`, `out`,
            and `use_indices`.

    See Also:
        [`Database.load`][kaptive.db.core.Database.load]
    """
    self.cli.msg(f"💽 Loading database {args.database}...")  # type: ignore
    from kaptive.db import DatabaseManager

    db = DatabaseManager.get(args.database)
    out_handle = self.cli.open_file(args.out, "wb")  # type: ignore
    self.cli.msg("📤 Extracting genes...")  # type: ignore
    out_handle.write(db.genes.to_fasta(args.use_indices))
    self.cli.msg(f"✅ Written gene sequences to {args.out}.")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Install

Install()

              flowchart TD
              kaptive.db.cli.Install[Install]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Install
                


              click kaptive.db.cli.Install href "" "kaptive.db.cli.Install"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

📦 Install known reference databases via keyword.

Downloads GenBank and TOML definition files from official repositories, compiles them into vectorized Database objects, and caches them locally.

Methods:

  • __call__

    Executes database installation for a specific keyword or 'all'.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configures argument parser options for the install subcommand.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Executes database installation for a specific keyword or 'all'.

Parameters:

  • args

    (Namespace) –

    Parsed CLI arguments containing database.

Raises:

  • DatabaseError

    If the specified keyword is not a known database.

See Also

DatabaseManager.install, DatabaseError

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Executes database installation for a specific keyword or 'all'.

    Args:
        args (argparse.Namespace): Parsed CLI arguments containing `database`.

    Raises:
        DatabaseError: If the specified keyword is not a known database.

    See Also:
        [`DatabaseManager.install`][kaptive.db.manager.DatabaseManager.install],
        [`DatabaseError`][kaptive.db.models.DatabaseError]
    """
    if args.database == "all":
        self.cli.msg("📥 Installing all known databases concurrently...")  # type: ignore
    else:
        self.cli.msg(f"📥 Installing database '{args.database}'...")  # type: ignore

    from kaptive.db import DatabaseManager

    DatabaseManager.install(args.database)

    if args.database == "all":
        self.cli.msg("✅ Successfully installed all known databases.")  # type: ignore
    else:
        self.cli.msg(f"✅ Successfully installed '{args.database}'.")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configures argument parser options for the install subcommand.

Source code in src/kaptive/db/cli.py
def setup_arguments(self) -> None:
    r"""Configures argument parser options for the `install` subcommand."""
    opts = self.parser.add_argument_group("📥 Inputs")  # type: ignore
    opts.add_argument("database", help="Database keyword (see: `kaptive db avail`) or 'all'")

List

List()

              flowchart TD
              kaptive.db.cli.List[List]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.List
                


              click kaptive.db.cli.List href "" "kaptive.db.cli.List"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

📋 List all currently installed local databases.

Displays the keywords of all compiled .pkl databases found in the user's local Kaptive directory (~/.kaptive).

Aliases

ls

Methods:

  • __call__

    Executes the list command to print installed database keywords.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Executes the list command to print installed database keywords.

Parameters:

  • args

    (Namespace) –

    Parsed command-line arguments.

See Also

DatabaseManager.installed

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Executes the `list` command to print installed database keywords.

    Args:
        args (argparse.Namespace): Parsed command-line arguments.

    See Also:
        [`DatabaseManager.installed`][kaptive.db.manager.DatabaseManager.installed]
    """
    from kaptive.db import DatabaseManager

    if installed := DatabaseManager.installed():
        print("\n".join(installed))
    else:
        self.cli.msg("❌ No databases installed")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Loci

Loci()

              flowchart TD
              kaptive.db.cli.Loci[Loci]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Loci
                


              click kaptive.db.cli.Loci href "" "kaptive.db.cli.Loci"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

🧬 Extract locus nucleotide sequences in FASTA format.

Methods:

  • __call__

    Extracts locus FASTA sequences to specified output file or stdout.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Extracts locus FASTA sequences to specified output file or stdout.

Parameters:

  • args

    (Namespace) –

    Parsed CLI arguments containing database, out, and use_indices.

See Also

Database.load

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Extracts locus FASTA sequences to specified output file or stdout.

    Args:
        args (argparse.Namespace): Parsed CLI arguments containing `database`, `out`,
            and `use_indices`.

    See Also:
        [`Database.load`][kaptive.db.core.Database.load]
    """
    self.cli.msg(f"💽 Loading database {args.database}...")  # type: ignore
    from kaptive.db import DatabaseManager

    db = DatabaseManager.get(args.database)
    out_handle = self.cli.open_file(args.out, "wb")  # type: ignore
    self.cli.msg("📤 Extracting loci...")  # type: ignore
    out_handle.write(db.loci.to_fasta(args.use_indices))
    self.cli.msg(f"✅ Written locus sequences to {args.out}.")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Metadata

Metadata()

              flowchart TD
              kaptive.db.cli.Metadata[Metadata]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Metadata
                


              click kaptive.db.cli.Metadata href "" "kaptive.db.cli.Metadata"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

📊 Print detailed metadata of a Kaptive database.

Displays summary information including organism, taxon ID, antigen type, synthesis pathway, version, identity threshold, GenBank filename, DOIs, repository URL, and curator contacts.

Aliases

info

Methods:

  • __call__

    Loads database and prints formatted metadata table to standard output.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configures argument parser options for the metadata subcommand.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Loads database and prints formatted metadata table to standard output.

Parameters:

  • args

    (Namespace) –

    Parsed CLI arguments containing database.

Raises:

See Also

Database.load

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Loads database and prints formatted metadata table to standard output.

    Args:
        args (argparse.Namespace): Parsed CLI arguments containing `database`.

    Raises:
        DatabaseError: If the specified database cannot be loaded.

    See Also:
        [`Database.load`][kaptive.db.core.Database.load]
    """
    from kaptive.db import DatabaseManager

    db = DatabaseManager.get(args.database)
    meta = db.metadata
    fields = [
        ("Organism", meta.organism),
        ("Taxon", str(meta.taxon)),
        ("Antigen", meta.antigen),
        ("Pathway", meta.pathway),
        ("Version", meta.version),
        ("Keyword", meta.keyword),
        ("Threshold", f"{meta.id_threshold}%"),
        ("GenBank", meta.genbank),
        ("DOIs", ", ".join(meta.doi) if meta.doi else "None"),
        ("Repository", f"https://github.com/{meta.owner}/{meta.repo}/tree/{meta.branch}"),
        ("Contact", ", ".join(f"{k} <{v}>" for k, v in meta.contact.items())),
    ]

    max_len = max(len(k) for k, v in fields)
    print(
        Colors.wrap(f"\n📊 Metadata for {meta.name}\n", Colors.BOLD_CYAN)
        + "\n".join(f"  {Colors.wrap(k.ljust(max_len), Colors.BOLD)}  {v}" for k, v in fields)
        + "\n"
    )

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configures argument parser options for the metadata subcommand.

Source code in src/kaptive/db/cli.py
def setup_arguments(self) -> None:
    r"""Configures argument parser options for the `metadata` subcommand."""
    opts = self.parser.add_argument_group("📥 Inputs")  # type: ignore
    opts.add_argument("database", help="Database path or keyword (see: `kaptive db list`)")

Proteins

Proteins()

              flowchart TD
              kaptive.db.cli.Proteins[Proteins]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Proteins
                


              click kaptive.db.cli.Proteins href "" "kaptive.db.cli.Proteins"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

🧶 Extract translated protein sequences in FASTA format.

Methods:

  • __call__

    Extracts translated protein FASTA sequences to output stream.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Extracts translated protein FASTA sequences to output stream.

Parameters:

  • args

    (Namespace) –

    Parsed CLI arguments containing database, out, and use_indices.

See Also

Database.load

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Extracts translated protein FASTA sequences to output stream.

    Args:
        args (argparse.Namespace): Parsed CLI arguments containing `database`, `out`,
            and `use_indices`.

    See Also:
        [`Database.load`][kaptive.db.core.Database.load]
    """
    self.cli.msg(f"💽 Loading database {args.database}...")  # type: ignore
    from kaptive.db import DatabaseManager

    db = DatabaseManager.get(args.database)
    out_handle = self.cli.open_file(args.out, "wb")  # type: ignore
    self.cli.msg("📤 Extracting proteins...")  # type: ignore
    out_handle.write(db.translations.to_fasta(args.use_indices))
    self.cli.msg(f"✅ Written protein sequences to {args.out}.")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Reset

Reset()

              flowchart TD
              kaptive.db.cli.Reset[Reset]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Reset
                


              click kaptive.db.cli.Reset href "" "kaptive.db.cli.Reset"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

🧹 Uninstall all local databases and reset local cache.

Deletes all compiled .pkl and metadata .json files from the local Kaptive cache directory.

Methods:

  • __call__

    Executes local cache reset and database removal.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Executes local cache reset and database removal.

Parameters:

  • args

    (Namespace) –

    Parsed command-line arguments.

See Also

DatabaseManager.reset

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Executes local cache reset and database removal.

    Args:
        args (argparse.Namespace): Parsed command-line arguments.

    See Also:
        [`DatabaseManager.reset`][kaptive.db.manager.DatabaseManager.reset]
    """
    self.cli.msg("🧹 Uninstalling all local databases...")  # type: ignore
    from kaptive.db import DatabaseManager

    DatabaseManager.reset()
    self.cli.msg("✅ All local databases have been uninstalled and reset.")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configure argument flags and positional parameters on self.parser.

Source code in src/kaptive/cli.py
def setup_arguments(self) -> None:
    r"""Configure argument flags and positional parameters on `self.parser`."""
    pass

Update

Update()

              flowchart TD
              kaptive.db.cli.Update[Update]
              kaptive.cli.Command[Command]

                              kaptive.cli.Command --> kaptive.db.cli.Update
                


              click kaptive.db.cli.Update href "" "kaptive.db.cli.Update"
              click kaptive.cli.Command href "" "kaptive.cli.Command"
            

🔄 Update installed local databases from remote repositories.

Checks installed databases against their source GitHub repositories for newer versions defined in TOML metadata and re-compiles modified databases.

Methods:

  • __call__

    Executes database updates for a specific keyword or 'all' installed databases.

  • add_output_arguments

    Add standard report and FASTA file output options to argument group.

  • build

    Wire command parser and subcommands into parent argparse hierarchy.

  • get_shared_parser

    Return shared parent parser containing options passed to subcommands.

  • register_subcommands

    Register child subcommand instances into subcommands list.

  • setup_arguments

    Configures argument parser options for the update subcommand.

Source code in src/kaptive/cli.py
def __init__(self) -> None:
    r"""Initialize command instance and populate metadata attributes."""
    self.parser: argparse.ArgumentParser | None = None
    self.subcommands: list[Command] = []
    self.cli: Cli | None = None

    # Auto-populate name from the class name
    if not self.name:
        self.name = type(self).__name__.lower()

    # Auto-populate description from class docstring
    if not self.description:
        if type(self).__doc__ and type(self).__doc__ != Command.__doc__:
            self.description = type(self).__doc__  # type: ignore

    # Auto-populate short help text from the first line of the description
    if not self.help_text and self.description:
        self.help_text = self.description.strip().split("\n")[0]

    self.register_subcommands()

__call__

__call__(args: Namespace) -> None

Executes database updates for a specific keyword or 'all' installed databases.

Parameters:

  • args

    (Namespace) –

    Parsed CLI arguments containing database.

See Also

DatabaseManager.update

Source code in src/kaptive/db/cli.py
def __call__(self, args: argparse.Namespace) -> None:
    r"""Executes database updates for a specific keyword or 'all' installed databases.

    Args:
        args (argparse.Namespace): Parsed CLI arguments containing `database`.

    See Also:
        [`DatabaseManager.update`][kaptive.db.manager.DatabaseManager.update]
    """
    if args.database == "all":
        self.cli.msg("🔄 Checking all installed databases for updates concurrently...")  # type: ignore
    else:
        self.cli.msg(f"🔄 Checking '{args.database}' for updates...")  # type: ignore

    from kaptive.db import DatabaseManager

    updated = False
    for db in DatabaseManager.update(args.database):
        self.cli.msg(f"✅ Updated {db.metadata.name} to version {db.metadata.version}")  # type: ignore
        updated = True

    if not updated:
        self.cli.msg("🎉 All databases are already up to date.")  # type: ignore

add_output_arguments

add_output_arguments(opts: _ArgumentGroup, tsv_flags: tuple[str, str] = ('-o', '--out'), include_json: bool = True) -> None

Add standard report and FASTA file output options to argument group.

Parameters:

  • opts

    (_ArgumentGroup) –

    Target argument group to populate.

  • tsv_flags

    (tuple[str, str], default: ('-o', '--out') ) –

    Short and long flag options for TSV report output. Defaults to ("-o", "--out").

  • include_json

    (bool, default: True ) –

    Flag indicating whether to include --json argument option. Defaults to True.

Source code in src/kaptive/cli.py
def add_output_arguments(
    self,
    opts: argparse._ArgumentGroup,
    tsv_flags: tuple[str, str] = ("-o", "--out"),
    include_json: bool = True,
) -> None:
    r"""Add standard report and FASTA file output options to argument group.

    Args:
        opts (argparse._ArgumentGroup): Target argument group to populate.
        tsv_flags (tuple[str, str]): Short and long flag options for TSV report output.
            Defaults to `("-o", "--out")`.
        include_json (bool): Flag indicating whether to include `--json` argument option.
            Defaults to `True`.
    """
    help_msg = (
        "Write serotyping results as a TSV report to a file (default: %(default)s)"
        if tsv_flags[0] == "-o"
        else "Write serotyping results as a TSV report to a file (default: %(const)s)"
    )
    opts.add_argument(
        tsv_flags[0],
        tsv_flags[1],
        metavar="FILE",
        nargs="?" if tsv_flags[0] == "-t" else None,
        default="stdout" if tsv_flags[0] == "-o" else None,
        const="stdout" if tsv_flags[0] == "-t" else None,
        help=help_msg,
    )
    opts.add_argument(
        "-l",
        "--loci",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write locus nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-g",
        "--genes",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write gene nucleotide fasta files to a directory (default: %(const)s)",
    )
    opts.add_argument(
        "-p",
        "--proteins",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Write translation amino-acid fasta files to a directory (default: %(const)s)",
    )
    if include_json:
        opts.add_argument(
            "-j",
            "--json",
            metavar="FILE",
            nargs="?",
            const="kaptive_results.jsonl",
            help="Write serialised results to a newline-delimited JSON (default: %(const)s)",
        )
    opts.add_argument(
        "--pha4ge",
        metavar="FILE",
        nargs="?",
        const="kaptive_results.pha4ge",
        type=Path,
        help="Write PHA4GE-compliant serotyping report to a TSV file (default: %(const)s)",
    )
    opts.add_argument(
        "--plots",
        metavar="DIR",
        nargs="?",
        const="./",
        type=Path,
        help="Generate interactive locus plots to a directory (default: %(const)s)",
    )

build

build(subparsers: _SubParsersAction, parent_parsers: list[ArgumentParser] | None = None) -> None

Wire command parser and subcommands into parent argparse hierarchy.

Parameters:

  • subparsers

    (_SubParsersAction) –

    Target subparser action registry.

  • parent_parsers

    (list[ArgumentParser] | None, default: None ) –

    Parent shared parsers to inherit.

Source code in src/kaptive/cli.py
def build(
    self,
    subparsers: argparse._SubParsersAction,  # type: ignore
    parent_parsers: list[argparse.ArgumentParser] | None = None,
) -> None:
    r"""Wire command parser and subcommands into parent argparse hierarchy.

    Args:
        subparsers (argparse._SubParsersAction): Target subparser action registry.
        parent_parsers (list[argparse.ArgumentParser] | None): Parent shared parsers to inherit.
    """
    parents = parent_parsers or []

    self.parser = subparsers.add_parser(
        name=self.name,
        aliases=self.aliases,
        description=Colors.wrap(self.description, Colors.BOLD),
        help=self.help_text or self.description,
        parents=parents,
        formatter_class=KaptiveHelpFormatter,
    )

    # 1. Add specific arguments for this command
    self.setup_arguments()

    # Rename the default options group and move it to the bottom of the help menu
    if hasattr(self.parser, "_optionals"):
        self.parser._optionals.title = Colors.wrap("🌎 Global options", Colors.BOLD)
        # Pop the group out of the internal list and append it to the end
        groups = self.parser._action_groups
        if self.parser._optionals in groups:
            groups.append(groups.pop(groups.index(self.parser._optionals)))

    # 2. Bind the execution function (only if __call__ was actually overridden)
    if type(self).__call__ != Command.__call__:
        self.parser.set_defaults(func=self.__call__)

    # 3. Process subcommands (if any)
    if self.subcommands:
        # If this command doesn't do anything itself, it MUST require a subcommand
        is_required = type(self).__call__ == Command.__call__
        sub_action = self.parser.add_subparsers(
            title=Colors.wrap(f"'{self.name}' subcommands", Colors.BOLD),
            dest=f"{self.name}_subcommand",
            required=is_required,
        )

        # Collect shared arguments to pass down
        child_parents = parents.copy()
        if shared := self.get_shared_parser():
            child_parents.append(shared)

        for cmd in self.subcommands:
            cmd.cli = self.cli
            cmd.build(sub_action, parent_parsers=child_parents)

get_shared_parser

get_shared_parser() -> ArgumentParser | None

Return shared parent parser containing options passed to subcommands.

Returns:

  • ArgumentParser | None

    argparse.ArgumentParser | None: Shared non-help argument parser or None.

Source code in src/kaptive/cli.py
def get_shared_parser(self) -> argparse.ArgumentParser | None:
    r"""Return shared parent parser containing options passed to subcommands.

    Returns:
        argparse.ArgumentParser | None: Shared non-help argument parser or `None`.
    """
    return None

register_subcommands

register_subcommands() -> None

Register child subcommand instances into subcommands list.

Source code in src/kaptive/cli.py
def register_subcommands(self) -> None:
    r"""Register child subcommand instances into `subcommands` list."""
    pass

setup_arguments

setup_arguments() -> None

Configures argument parser options for the update subcommand.

Source code in src/kaptive/db/cli.py
def setup_arguments(self) -> None:
    r"""Configures argument parser options for the `update` subcommand."""
    opts = self.parser.add_argument_group("📥 Inputs")  # type: ignore
    opts.add_argument(
        "database",
        nargs="?",
        default="all",
        help="Database keyword (see: `kaptive db list`) or 'all' (default: all)",
    )