diff --git a/.cursor/rules/cli-patterns.mdc b/.cursor/rules/cli-patterns.mdc new file mode 100644 index 00000000..f28d7114 --- /dev/null +++ b/.cursor/rules/cli-patterns.mdc @@ -0,0 +1,168 @@ +# 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 +description: +globs: +alwaysApply: false +--- diff --git a/.cursor/rules/git-workflow.mdc b/.cursor/rules/git-workflow.mdc index a571b065..115567f6 100644 --- a/.cursor/rules/git-workflow.mdc +++ b/.cursor/rules/git-workflow.mdc @@ -2,7 +2,7 @@ ## 🎯 **Philosophy: Incremental Commits for Easy Reverts** -The goal is to make commits that are: +Make commits that are: - **Small enough** to revert safely - **Focused enough** to understand what changed - **Frequent enough** to avoid losing work @@ -15,7 +15,6 @@ TYPE: Brief description - Bullet point of what changed - Another change if needed -- Reference to issue/feature if applicable Examples: - RESTORE: Complete CLI functionality in new architecture @@ -69,45 +68,6 @@ git checkout main git merge feature/cli-restore ``` -### **Quick Development Flow** -```bash -# For small, focused changes (most common) -git add . -git commit -m "FIX: Missing Union import in tensor.py" -git push - -# For larger changes, use feature branch -git checkout -b feature/new-command -# ... work ... -git commit -m "FEAT: Add doctor command with environment checks" -git push origin feature/new-command -``` - -## 🎯 **Practical Guidelines for Ad-hoc Development** - -### **1. Commit Size Guidelines** -- **Small**: 1-3 files changed, single concern -- **Medium**: 5-10 files, related functionality -- **Large**: 10+ files, major feature (consider breaking up) - -### **2. Before Committing Checklist** -- [ ] Code runs without errors -- [ ] Tests pass (if applicable) -- [ ] Changes are focused and related -- [ ] Commit message explains what and why - -### **3. Revert-Friendly Commits** -```bash -# If you need to revert the last commit -git revert HEAD - -# If you need to revert to a specific commit -git revert - -# If you need to undo uncommitted changes -git checkout -- -``` - ## 🚀 **Common Workflows** ### **Quick Fix Workflow** @@ -131,85 +91,6 @@ git commit -m "TEST: Add tests for new command" # Complete feature git push origin feature/new-command -# Create PR or merge directly -``` - -### **Emergency Fix Workflow** -```bash -# Hot fix on main -git checkout main -# Make fix -git add . -git commit -m "HOTFIX: Fix critical CLI error" -git push -``` - -## 📋 **Commit Message Examples** - -### **Good Examples:** -``` -RESTORE: Complete CLI functionality in new architecture - -- Ported all commands from bin/tito.py to new tito/ CLI architecture -- Added InfoCommand with system info and module status -- Added TestCommand with pytest integration -- All commands now work with 'tito' command in shell -``` - -``` -FIX: Missing imports in tensor module - -- Added Union, List, Optional, Tuple imports -- Resolves NameError in tensor operations -- Required for CLI info command to work properly -``` - -``` -FEAT: Add doctor command for environment diagnosis - -- Comprehensive environment validation -- Dependency checking -- Module structure verification -- Rich terminal output with tables -``` - -### **Avoid:** -``` -- "Fixed stuff" -- "Updated things" -- "More changes" -- "WIP" -``` - -## 🔧 **Git Configuration Tips** - -### **Set up helpful aliases:** -```bash -# Add to ~/.gitconfig -[alias] - st = status - co = checkout - br = branch - ci = commit - unstage = reset HEAD -- - last = log -1 HEAD - visual = !gitk -``` - -### **Useful commands:** -```bash -# See what you're about to commit -git diff --cached - -# See recent commits -git log --oneline -10 - -# See what files changed -git diff --name-only HEAD~1 - -# Stash work in progress -git stash -git stash pop ``` ## 🎯 **For This Project Specifically** @@ -266,7 +147,3 @@ git commit -m "Second part of changes" 5. **Commit frequently** to avoid losing work **Remember:** It's better to have many small commits than one large commit that's hard to revert or understand. -description: -globs: -alwaysApply: false ----