Skip to content

Entry Point Module

The entry point module (__main__.py) serves as the routing layer for the Hatch CLI, handling argument parsing and command delegation.

Overview

This module provides:

  • Command-line argument parsing using argparse
  • Custom HatchArgumentParser with formatted error messages
  • Manager initialization (HatchEnvironmentManager, MCPHostConfigurationManager)
  • Command routing to appropriate handler modules

Module Reference

hatch.cli.__main__

Entry point for Hatch CLI.

This module provides the main entry point for the Hatch package manager CLI. It handles argument parsing and routes commands to appropriate handler modules.

Architecture

This module implements the routing layer of the CLI architecture: 1. Parses command-line arguments using argparse 2. Initializes shared managers (HatchEnvironmentManager, MCPHostConfigurationManager) 3. Attaches managers to the args namespace for handler access 4. Routes commands to appropriate handler modules

Command Structure

hatch create - Create package template (cli_system) hatch validate - Validate package (cli_system) hatch env - Environment management (cli_env) hatch package - Package management (cli_package) hatch mcp - MCP host configuration (cli_mcp)

Entry Points
  • python -m hatch.cli: Module execution via main.py
  • hatch: Console script defined in pyproject.toml
Handler Signature

All handlers follow: (args: Namespace) -> int - args.env_manager: HatchEnvironmentManager instance - args.mcp_manager: MCPHostConfigurationManager instance - Returns: Exit code (0 for success, non-zero for errors)

Example

$ hatch --version $ hatch env list $ hatch mcp configure claude-desktop my-server --command python

Classes

HatchArgumentParser

Bases: ArgumentParser

Custom ArgumentParser with formatted error messages.

Overrides the error() method to format argparse errors with [ERROR] prefix and bright red color (when colors enabled).

Reference: R13 §4.2.1 (13-error_message_formatting_v0.md)

Output format

[ERROR]

Example

parser = HatchArgumentParser(description="Test CLI") parser.parse_args(['--invalid']) [ERROR] unrecognized arguments: --invalid

Source code in hatch/cli/__main__.py
class HatchArgumentParser(argparse.ArgumentParser):
    """Custom ArgumentParser with formatted error messages.

    Overrides the error() method to format argparse errors with
    [ERROR] prefix and bright red color (when colors enabled).

    Reference: R13 §4.2.1 (13-error_message_formatting_v0.md)

    Output format:
        [ERROR] <message>

    Example:
        >>> parser = HatchArgumentParser(description="Test CLI")
        >>> parser.parse_args(['--invalid'])
        [ERROR] unrecognized arguments: --invalid
    """

    def error(self, message: str) -> None:
        """Override to format errors with [ERROR] prefix and color.

        Args:
            message: Error message from argparse

        Note:
            Preserves exit code 2 (argparse convention).
        """
        if _colors_enabled():
            self.exit(2, f"{Color.RED.value}[ERROR]{Color.RESET.value} {message}\n")
        else:
            self.exit(2, f"[ERROR] {message}\n")
Functions
error(message)

Override to format errors with [ERROR] prefix and color.

Parameters:

Name Type Description Default
message str

Error message from argparse

required
Note

Preserves exit code 2 (argparse convention).

Source code in hatch/cli/__main__.py
def error(self, message: str) -> None:
    """Override to format errors with [ERROR] prefix and color.

    Args:
        message: Error message from argparse

    Note:
        Preserves exit code 2 (argparse convention).
    """
    if _colors_enabled():
        self.exit(2, f"{Color.RED.value}[ERROR]{Color.RESET.value} {message}\n")
    else:
        self.exit(2, f"[ERROR] {message}\n")

Functions

main()

Main entry point for Hatch CLI.

Parses command-line arguments and routes to appropriate handlers for: - Package template creation - Package validation - Environment management - Package management - MCP host configuration

Returns:

Name Type Description
int int

Exit code (0 for success, 1 for errors)

Source code in hatch/cli/__main__.py
def main() -> int:
    """Main entry point for Hatch CLI.

    Parses command-line arguments and routes to appropriate handlers for:
    - Package template creation
    - Package validation
    - Environment management
    - Package management
    - MCP host configuration

    Returns:
        int: Exit code (0 for success, 1 for errors)
    """
    # Configure logging
    logging.basicConfig(
        level=logging.WARNING,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )

    # Create argument parser
    parser = HatchArgumentParser(description="Hatch package manager CLI")

    # Add version argument
    parser.add_argument(
        "--version", action="version", version=f"%(prog)s {get_hatch_version()}"
    )

    subparsers = parser.add_subparsers(dest="command", help="Command to execute")

    # Set up command parsers
    _setup_create_command(subparsers)
    _setup_validate_command(subparsers)
    _setup_env_commands(subparsers)
    _setup_package_commands(subparsers)
    _setup_mcp_commands(subparsers)

    # General arguments for the environment manager
    parser.add_argument(
        "--envs-dir",
        default=Path.home() / ".hatch" / "envs",
        help="Directory to store environments",
    )
    parser.add_argument(
        "--cache-ttl",
        type=int,
        default=86400,
        help="Cache TTL in seconds (default: 86400 seconds --> 1 day)",
    )
    parser.add_argument(
        "--cache-dir",
        default=Path.home() / ".hatch" / "cache",
        help="Directory to store cached packages",
    )
    parser.add_argument(
        "--log-level",
        default="WARNING",
        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
        help="Log verbosity level (default: WARNING)",
    )

    args = parser.parse_args()
    logging.getLogger().setLevel(getattr(logging, args.log_level))

    # Initialize managers (lazy - only when needed)
    from hatch.environment_manager import HatchEnvironmentManager
    from hatch.mcp_host_config import MCPHostConfigurationManager

    env_manager = HatchEnvironmentManager(
        environments_dir=args.envs_dir,
        cache_ttl=args.cache_ttl,
        cache_dir=args.cache_dir,
    )
    mcp_manager = MCPHostConfigurationManager()

    # Attach managers to args for handler access
    args.env_manager = env_manager
    args.mcp_manager = mcp_manager

    # Route commands
    if args.command == "create":
        from hatch.cli.cli_system import handle_create

        return handle_create(args)

    elif args.command == "validate":
        from hatch.cli.cli_system import handle_validate

        return handle_validate(args)

    elif args.command == "env":
        return _route_env_command(args)

    elif args.command == "package":
        return _route_package_command(args)

    elif args.command == "mcp":
        return _route_mcp_command(args)

    else:
        parser.print_help()
        return 1