mirror of
https://github.com/MLSysBook/TinyTorch.git
synced 2026-05-02 10:56:07 -05:00
- Add brief descriptions to YAML frontmatter for all rule files - Descriptions explain the purpose and content of each rule - Follow consistent format matching ml-systems-course-context.mdc - Improve rule discoverability and understanding Files updated: - user-preferences.mdc: User preferences and development conventions - tinytorch-project-structure.mdc: Dual-structure architecture guide - testing-patterns.mdc: Testing standards with pytest and real data - nbdev-educational-pattern.mdc: Educational NBDev patterns - module-development-best-practices.mdc: Real Data, Real Systems principles - git-workflow.mdc: Git workflow guidelines for incremental commits - development-workflow.mdc: Complete development workflow with tito CLI - cli-patterns.mdc: CLI development patterns for tito tool
175 lines
4.3 KiB
Plaintext
175 lines
4.3 KiB
Plaintext
---
|
|
description: CLI Development Patterns for TinyTorch
|
|
globs:
|
|
alwaysApply: false
|
|
---
|
|
|
|
# CLI Development Patterns for TinyTorch
|
|
|
|
## Command Architecture
|
|
|
|
All CLI commands follow the `BaseCommand` pattern:
|
|
|
|
```python
|
|
from .base import BaseCommand
|
|
|
|
class NewCommand(BaseCommand):
|
|
@property
|
|
def name(self) -> str:
|
|
return "new-command"
|
|
|
|
@property
|
|
def description(self) -> str:
|
|
return "Description of what this command does"
|
|
|
|
def add_arguments(self, parser: ArgumentParser) -> None:
|
|
parser.add_argument("--option", help="Option description")
|
|
|
|
def run(self, args: Namespace) -> int:
|
|
# Command implementation
|
|
return 0 # 0 for success, 1 for error
|
|
```
|
|
|
|
## Command Registration
|
|
|
|
1. **Create command file**: `tito/commands/new_command.py`
|
|
2. **Add to imports**: Update `tito/commands/__init__.py`
|
|
3. **Register in CLI**: Add to `tito/main.py` commands dict
|
|
|
|
## Rich Output Patterns
|
|
|
|
### Panels for Command Headers
|
|
```python
|
|
console.print(Panel("Command Title",
|
|
title="Command Name",
|
|
border_style="bright_cyan"))
|
|
```
|
|
|
|
### Tables for Data Display
|
|
```python
|
|
table = Table(title="Data Title", show_header=True, header_style="bold blue")
|
|
table.add_column("Column", style="cyan", width=20)
|
|
table.add_column("Status", justify="left")
|
|
table.add_row("Item", "[green]✅ OK[/green]")
|
|
console.print(table)
|
|
```
|
|
|
|
### Progress Bars for Long Operations
|
|
```python
|
|
with Progress(
|
|
SpinnerColumn(),
|
|
TextColumn("[progress.description]{task.description}"),
|
|
BarColumn(),
|
|
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
|
|
console=console
|
|
) as progress:
|
|
task = progress.add_task("Operation...", total=total_items)
|
|
# ... work ...
|
|
progress.advance(task)
|
|
```
|
|
|
|
## Error Handling
|
|
|
|
### Validation Errors
|
|
```python
|
|
def validate_args(self, args: Namespace) -> None:
|
|
if not args.required_arg:
|
|
raise ValueError("Required argument missing")
|
|
```
|
|
|
|
### User-Friendly Error Messages
|
|
```python
|
|
console.print(Panel(f"[red]❌ Error: {error_message}[/red]",
|
|
title="Error", border_style="red"))
|
|
```
|
|
|
|
## Testing Commands
|
|
|
|
### Before Committing Checklist
|
|
- [ ] Command runs without errors
|
|
- [ ] Help text is clear and helpful
|
|
- [ ] Error messages are user-friendly
|
|
- [ ] Output is properly formatted with Rich
|
|
- [ ] Command integrates with other commands
|
|
|
|
### Test Command Integration
|
|
```python
|
|
# Test that command is registered
|
|
tito --help # Should show new command
|
|
|
|
# Test command functionality
|
|
tito new-command --help # Should show command help
|
|
tito new-command # Should run command
|
|
```
|
|
|
|
## Common Patterns
|
|
|
|
### Subprocess Integration
|
|
```python
|
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
if result.returncode == 0:
|
|
console.print("[green]✅ Success[/green]")
|
|
else:
|
|
console.print(f"[red]❌ Failed: {result.stderr}[/red]")
|
|
```
|
|
|
|
### File System Operations
|
|
```python
|
|
from pathlib import Path
|
|
|
|
# Check if file exists
|
|
if not Path(file_path).exists():
|
|
console.print(f"[red]❌ File not found: {file_path}[/red]")
|
|
return 1
|
|
```
|
|
|
|
### Environment Validation
|
|
```python
|
|
# Check virtual environment
|
|
in_venv = (
|
|
os.environ.get('VIRTUAL_ENV') is not None or
|
|
(hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
|
|
)
|
|
```
|
|
|
|
## Command Examples
|
|
|
|
### Info Command Pattern
|
|
- System information display
|
|
- Module status checking
|
|
- Rich tables and panels
|
|
- Optional flags for different views
|
|
|
|
### Test Command Pattern
|
|
- Pytest integration
|
|
- Progress bars for multiple tests
|
|
- Error reporting and summaries
|
|
- Support for single module or all modules
|
|
|
|
### Sync Command Pattern
|
|
- nbdev integration
|
|
- File export tracking
|
|
- Success/failure reporting
|
|
- Next steps guidance
|
|
|
|
### Doctor Command Pattern
|
|
- Environment validation
|
|
- Dependency checking
|
|
- Structure verification
|
|
- Comprehensive reporting
|
|
|
|
## Best Practices
|
|
|
|
1. **Use Rich for all output** - No plain print statements
|
|
2. **Provide helpful error messages** - Explain what went wrong and how to fix
|
|
3. **Include next steps** - Tell users what to do after command completes
|
|
4. **Test integration** - Ensure commands work together
|
|
5. **Follow existing patterns** - Maintain consistency across commands
|
|
6. **Handle edge cases** - Missing files, invalid arguments, etc.
|
|
7. **Provide progress feedback** - For long-running operations
|
|
8. **Use consistent styling** - Colors, borders, and formatting
|
|
|
|
globs:
|
|
alwaysApply: false
|
|
---
|