Modern, extensible Python project management tool with comprehensive environment and build system support
—
Central application controller that manages project state, configuration, environments, and command execution. Provides the main coordination layer for all hatch operations.
Main application controller that orchestrates all hatch operations including environment management, configuration handling, and command execution.
class Application:
"""
Main application controller managing project state and operations.
Inherits from Terminal class to provide output formatting and display capabilities.
"""
def __init__(self, exit_func, *args, **kwargs):
"""
Initialize application instance.
Args:
exit_func: Function to call on application exit
*args: Additional positional arguments passed to Terminal
**kwargs: Additional keyword arguments passed to Terminal
"""
@property
def config(self):
"""
Root configuration object.
Returns:
RootConfig: Application configuration
"""
@property
def plugins(self):
"""
Plugin manager instance.
Returns:
PluginManager: Plugin manager for discovering and loading plugins
"""
@property
def project(self):
"""
Current project instance.
Returns:
Project: Current project or None
"""
@project.setter
def project(self, value):
"""Set current project."""
@property
def data_dir(self) -> Path:
"""
Application data directory.
Returns:
Path to data directory
"""
@property
def cache_dir(self) -> Path:
"""
Application cache directory.
Returns:
Path to cache directory
"""
@property
def config_file(self):
"""
Configuration file handler.
Returns:
ConfigFile: Configuration file manager
"""
def get_environment(self, env_name: str | None = None):
"""
Get environment interface for specified environment.
Args:
env_name (str, optional): Environment name, defaults to current environment
Returns:
EnvironmentInterface: Environment instance
"""
def prepare_environment(self, environment):
"""
Prepare environment for execution including dependency installation.
Args:
environment: Environment interface to prepare
"""
def run_shell_commands(self, context):
"""
Execute shell commands in prepared environment.
Args:
context: Execution context with commands and environment
"""
def ensure_environment_plugin_dependencies(self) -> None:
"""Ensure environment plugin dependencies are installed."""
def get_python_manager(self, directory: str | None = None):
"""
Get Python installation manager.
Args:
directory (str, optional): Directory for Python installations
Returns:
PythonManager: Python installation manager
"""
def abort(self, text: str = '', code: int = 1, **kwargs):
"""
Abort application with error message and exit code.
Args:
text (str): Error message to display
code (int): Exit code
**kwargs: Additional formatting arguments
"""
def display_info(self, text: str, **kwargs):
"""
Display informational message.
Args:
text (str): Message to display
**kwargs: Formatting arguments
"""
def display_success(self, text: str, **kwargs):
"""
Display success message.
Args:
text (str): Success message
**kwargs: Formatting arguments
"""
def display_warning(self, text: str, **kwargs):
"""
Display warning message.
Args:
text (str): Warning message
**kwargs: Formatting arguments
"""
def display_error(self, text: str, **kwargs):
"""
Display error message.
Args:
text (str): Error message
**kwargs: Formatting arguments
"""
def display_waiting(self, text: str, **kwargs):
"""
Display waiting/progress message.
Args:
text (str): Progress message
**kwargs: Formatting arguments
"""Context object for managing command execution including environment settings, command sequences, and output handling.
class ExecutionContext:
"""
Context for command execution with environment and command management.
Args:
environment: Environment interface for execution
shell_commands (list[str], optional): Commands to execute
env_vars (dict, optional): Additional environment variables
force_continue (bool): Whether to continue on command failure
show_code_on_error (bool): Whether to show exit codes on error
hide_commands (bool): Whether to hide command output
source (str): Source identifier for commands
"""
def __init__(
self,
environment,
*,
shell_commands: list[str] | None = None,
env_vars: dict[str, str] | None = None,
force_continue: bool = False,
show_code_on_error: bool = False,
hide_commands: bool = False,
source: str = 'cmd'
):
"""Initialize execution context."""
@property
def env(self):
"""Environment for command execution."""
@property
def shell_commands(self) -> list[str]:
"""Commands to execute."""
@property
def env_vars(self) -> dict[str, str]:
"""Environment variables for execution."""
@property
def force_continue(self) -> bool:
"""Whether to continue on command failure."""
@property
def show_code_on_error(self) -> bool:
"""Whether to show exit codes on error."""
@property
def hide_commands(self) -> bool:
"""Whether to hide command output."""
@property
def source(self) -> str:
"""Source identifier for commands."""
def add_shell_command(self, command: str | list[str]) -> None:
"""
Add shell command to execution context.
Args:
command (str | list[str]): Command to add (string or argument list)
"""Configuration management for application-level settings including directories, verbosity, color output, and plugin configuration.
class ApplicationConfig:
"""Application-level configuration settings."""
@property
def verbosity(self) -> int:
"""Verbosity level (-2 to 2)."""
@property
def quiet(self) -> bool:
"""Whether quiet mode is enabled."""
@property
def enable_color(self) -> bool:
"""Whether colored output is enabled."""
@property
def interactive(self) -> bool:
"""Whether interactive features are enabled."""
@property
def data_dir(self) -> Path:
"""Application data directory."""
@property
def cache_dir(self) -> Path:
"""Application cache directory."""
@property
def config_file_path(self) -> Path:
"""Configuration file path."""Environment discovery, validation, and selection logic for determining which environment to use for operations.
def resolve_environment_name(
app: Application,
env_name: str | None = None,
command_env: str | None = None
) -> str:
"""
Resolve environment name from various sources.
Args:
app (Application): Application instance
env_name (str, optional): Explicitly specified environment
command_env (str, optional): Environment from command specification
Returns:
Resolved environment name
"""
def validate_environment_name(app: Application, env_name: str) -> bool:
"""
Validate that environment name exists in configuration.
Args:
app (Application): Application instance
env_name (str): Environment name to validate
Returns:
True if environment exists
"""
def get_available_environments(app: Application) -> list[str]:
"""
Get list of available environment names.
Args:
app (Application): Application instance
Returns:
List of available environment names
"""Command parsing, validation, and execution pipeline for processing user commands and script definitions.
def parse_command_string(command: str) -> tuple[str | None, str]:
"""
Parse command string to extract environment and command.
Args:
command (str): Command string potentially prefixed with "env:"
Returns:
Tuple of (environment_name, command)
"""
def validate_command(app: Application, command: str) -> bool:
"""
Validate command syntax and availability.
Args:
app (Application): Application instance
command (str): Command to validate
Returns:
True if command is valid
"""
def prepare_command_environment(
app: Application,
env_name: str,
commands: list[str]
) -> ExecutionContext:
"""
Prepare execution context for command execution.
Args:
app (Application): Application instance
env_name (str): Environment name
commands (list[str]): Commands to execute
Returns:
Prepared execution context
"""from hatch.cli.application import Application
from hatch.project.core import Project
from pathlib import Path
# Create application instance
app = Application(
exit_func=lambda code: exit(code),
verbosity=1,
enable_color=True,
interactive=True
)
# Set project
app.project = Project(Path.cwd())
# Access configuration
config = app.config
print(f"Mode: {config.mode}")
print(f"Data dir: {app.data_dir}")from hatch.cli.application import Application
app = Application(lambda code: exit(code))
# Get environment
env = app.get_environment("test")
# Check if environment exists
if not env.exists():
print("Creating environment...")
env.create()
# Prepare environment
app.prepare_environment(env)
# Run commands
context = ExecutionContext(
environment=env,
shell_commands=["python --version"]
)
app.run_shell_commands(context)from hatch.cli.application import Application
app = Application(lambda code: exit(code))
# Load configuration
app.config_file.load()
# Access configuration values
config = app.config
print(f"Default shell: {config.shell}")
print(f"Project mode: {config.mode}")
# Access project settings
if config.project:
print(f"Default project: {config.project}")
# Access plugin configuration
plugins = app.plugins
print(f"Available plugins: {list(plugins.list_name_plugin())}")from hatch.cli.application import Application
from hatch.errors import HatchError
app = Application(lambda code: exit(code))
try:
# Attempt operation
env = app.get_environment("nonexistent")
env.create()
except HatchError as e:
app.display_error(f"Operation failed: {e}")
app.abort(code=1)
except Exception as e:
app.display_error(f"Unexpected error: {e}")
app.abort(code=2)from hatch.cli.application import Application
app = Application(lambda code: exit(code))
# Initialize plugins
app.plugins.initialize()
# Get plugin manager
plugins = app.plugins
# Register plugins
env_plugins = plugins.hatch_register_environment()
publisher_plugins = plugins.hatch_register_publisher()
print(f"Environment plugins: {list(env_plugins.keys())}")
print(f"Publisher plugins: {list(publisher_plugins.keys())}")Install with Tessl CLI
npx tessl i tessl/pypi-hatch