Files
TinyTorch/tinytorch/cli/core/config.py
Vijay Janapa Reddi 0cbcbf8a6e Refactor CLI to senior software engineer standards
BREAKING CHANGE: Major architectural refactoring of CLI system

New Professional Architecture:
- Clean separation of concerns with proper package structure
- Command pattern implementation with base classes
- Centralized configuration management
- Proper exception hierarchy and error handling
- Logging framework integration
- Type hints throughout
- Dependency injection pattern

Structure:
tinytorch/cli/
├── __init__.py              # Package initialization
├── main.py                  # Professional CLI entry point
├── core/                    # Core CLI functionality
│   ├── __init__.py
│   ├── config.py           # Configuration management
│   ├── console.py          # Centralized console output
│   └── exceptions.py       # Exception hierarchy
├── commands/               # Command implementations
│   ├── __init__.py
│   ├── base.py            # Base command class
│   └── notebooks.py       # Notebooks command
└── tools/                 # CLI tools
    ├── __init__.py
    └── py_to_notebook.py  # Conversion tool

Features Added:
- Proper entry points in pyproject.toml
- Professional logging with file output
- Environment validation with detailed error messages
- Dry-run mode for notebooks command
- Force rebuild option
- Timeout protection for subprocess calls
- Backward compatibility wrapper (bin/tito)
- Extensible command registration system

Benefits:
- Maintainable: Single responsibility per module
- Testable: Clean interfaces and dependency injection
- Extensible: Easy to add new commands
- Professional: Industry-standard patterns
- Robust: Proper error handling and validation
- Installable: Proper package structure with entry points
2025-07-10 22:05:10 -04:00

84 lines
2.7 KiB
Python

"""
Configuration management for TinyTorch CLI.
"""
import os
import sys
from pathlib import Path
from typing import Dict, Any, Optional
from dataclasses import dataclass
@dataclass
class CLIConfig:
"""Configuration for TinyTorch CLI."""
# Project paths
project_root: Path
modules_dir: Path
tinytorch_dir: Path
bin_dir: Path
# Environment settings
python_min_version: tuple = (3, 8)
required_packages: list = None
# CLI settings
verbose: bool = False
no_color: bool = False
def __post_init__(self):
"""Initialize default values."""
if self.required_packages is None:
self.required_packages = ['numpy', 'pytest', 'rich']
@classmethod
def from_project_root(cls, project_root: Optional[Path] = None) -> 'CLIConfig':
"""Create config from project root directory."""
if project_root is None:
# Auto-detect project root
current = Path.cwd()
while current != current.parent:
if (current / 'pyproject.toml').exists():
project_root = current
break
current = current.parent
else:
project_root = Path.cwd()
return cls(
project_root=project_root,
modules_dir=project_root / 'modules',
tinytorch_dir=project_root / 'tinytorch',
bin_dir=project_root / 'bin'
)
def validate(self) -> list[str]:
"""Validate the configuration and return any issues."""
issues = []
# Check Python version
if sys.version_info < self.python_min_version:
issues.append(f"Python {'.'.join(map(str, self.python_min_version))}+ required, "
f"found {sys.version_info.major}.{sys.version_info.minor}")
# Check virtual environment
in_venv = (hasattr(sys, 'real_prefix') or
(hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
if not in_venv:
issues.append("Virtual environment not activated. Run: source .venv/bin/activate")
# Check required directories
if not self.modules_dir.exists():
issues.append(f"Modules directory not found: {self.modules_dir}")
if not self.tinytorch_dir.exists():
issues.append(f"TinyTorch package not found: {self.tinytorch_dir}")
# Check required packages
for package in self.required_packages:
try:
__import__(package)
except ImportError:
issues.append(f"Missing dependency: {package}. Run: pip install -r requirements.txt")
return issues