|
| 1 | +# Git-X Architecture Documentation |
| 2 | + |
| 3 | +This document describes the layered architecture of the git-x CLI tool, designed for maintainability, testability, and extensibility. |
| 4 | + |
| 5 | +## Architecture Overview |
| 6 | + |
| 7 | +The git-x codebase is organized into distinct layers with clear responsibilities: |
| 8 | + |
| 9 | +``` |
| 10 | +┌─────────────────────┐ |
| 11 | +│ CLI Layer │ ← User interaction, argument parsing (cli.rs) |
| 12 | +├─────────────────────┤ |
| 13 | +│ Command Layer │ ← Command implementations (commands/) |
| 14 | +├─────────────────────┤ |
| 15 | +│ Adapter Layer │ ← Output formatting & CLI handling (adapters/) |
| 16 | +├─────────────────────┤ |
| 17 | +│ Domain Layer │ ← Business logic, workflows (domain/) |
| 18 | +├─────────────────────┤ |
| 19 | +│ Core Layer │ ← Git operations, utilities (core/) |
| 20 | +└─────────────────────┘ |
| 21 | +``` |
| 22 | + |
| 23 | +## Layer Descriptions |
| 24 | + |
| 25 | +### 1. Core Layer (`src/core/`) |
| 26 | + |
| 27 | +**Purpose**: Low-level utilities and abstractions for git operations. |
| 28 | + |
| 29 | +**Modules**: |
| 30 | +- `traits.rs` - Common trait abstractions (`Command`, `GitRepository`, `Destructive`) |
| 31 | +- `git.rs` - Git operation wrappers and safe command execution |
| 32 | +- `output.rs` - Output formatting, buffering utilities, and progress indicators |
| 33 | +- `validation.rs` - Input validation with security focus (shell injection prevention) |
| 34 | +- `interactive.rs` - Interactive UI utilities with fuzzy search and confirmations |
| 35 | +- `safety.rs` - Safety mechanisms for destructive operations |
| 36 | + |
| 37 | +**Responsibilities**: |
| 38 | +- Execute git commands safely with proper error handling |
| 39 | +- Provide interactive prompts and fuzzy search functionality |
| 40 | +- Validate user input to prevent security issues |
| 41 | +- Implement safety checks for destructive operations |
| 42 | +- Format and buffer output efficiently |
| 43 | + |
| 44 | +### 2. Domain Layer (`src/domain/`) |
| 45 | + |
| 46 | +**Purpose**: Business logic and domain-specific workflows. |
| 47 | + |
| 48 | +**Current Modules**: |
| 49 | +- `git_repository.rs` - Repository-level operations and state management |
| 50 | +- `branch_manager.rs` - Branch lifecycle management and operations |
| 51 | + |
| 52 | +**Responsibilities**: |
| 53 | +- Implement domain-specific business rules |
| 54 | +- Coordinate complex multi-step workflows |
| 55 | +- Provide type-safe APIs for repository operations |
| 56 | +- Handle domain-specific validation and constraints |
| 57 | +- Manage operation state and context |
| 58 | + |
| 59 | +**Key Concepts**: |
| 60 | +- **Domain Services**: High-level operation coordinators (e.g., `BranchManager`) |
| 61 | +- **Repository Abstraction**: Clean interface for git operations |
| 62 | +- **Business Rules**: Domain-specific validation and logic |
| 63 | + |
| 64 | +### 3. Adapter Layer (`src/adapters/`) |
| 65 | + |
| 66 | +**Purpose**: Bridge between CLI and domain layers, handling output formatting. |
| 67 | + |
| 68 | +**Modules**: |
| 69 | +- `cli_handlers.rs` - CLI command handlers and workflow coordination |
| 70 | +- `formatters.rs` - Rich output formatting with colors, emojis, and tables |
| 71 | + |
| 72 | +**Responsibilities**: |
| 73 | +- Convert CLI arguments to domain operations |
| 74 | +- Handle CLI-specific concerns (interactive vs non-interactive mode) |
| 75 | +- Format command output with consistent styling |
| 76 | +- Provide reusable formatting utilities (tables, progress bars) |
| 77 | +- Manage CLI workflow coordination and error presentation |
| 78 | + |
| 79 | +### 4. Command Layer (`src/commands/`) |
| 80 | + |
| 81 | +**Purpose**: Organized command implementations by functional area. |
| 82 | + |
| 83 | +**Modules**: |
| 84 | +- `branch.rs` - Branch management commands (clean, prune, rename, switch-recent, stash-branch) |
| 85 | +- `commit.rs` - Commit operations (fixup, undo, bisect) |
| 86 | +- `repository.rs` - Repository-level commands (info, health, sync, upstream, new) |
| 87 | +- `analysis.rs` - Analysis and reporting (summary, graph, contributors, technical-debt, large-files, since, what) |
| 88 | +- `stash.rs` - Stash operations (stash-branch) |
| 89 | + |
| 90 | +**Command Count**: 21 total commands across 6 functional categories |
| 91 | + |
| 92 | +**Key Features**: |
| 93 | +- Each command implements the `Command` trait for consistency |
| 94 | +- Commands are organized by domain area for maintainability |
| 95 | +- Standardized error handling and output formatting |
| 96 | +- Support for both interactive and non-interactive modes |
| 97 | + |
| 98 | +### 5. CLI Layer (`src/cli.rs` + `src/main.rs`) |
| 99 | + |
| 100 | +**Purpose**: Command-line interface definition, argument parsing, and application entry point. |
| 101 | + |
| 102 | +**Key Files**: |
| 103 | +- `cli.rs` - CLI structure definition with clap derive macros |
| 104 | +- `main.rs` - Application entry point and command dispatch |
| 105 | + |
| 106 | +**Responsibilities**: |
| 107 | +- Define CLI structure with nested subcommands using clap |
| 108 | +- Parse command-line arguments with validation |
| 109 | +- Route commands to appropriate implementations |
| 110 | +- Handle global CLI concerns (help, version, shell completions) |
| 111 | +- Generate shell completions for bash, zsh, fish, PowerShell, and Elvish |
| 112 | + |
| 113 | +## Design Patterns Used |
| 114 | + |
| 115 | +### 1. Command Pattern |
| 116 | +All commands implement the `Command` trait with standardized execution methods: |
| 117 | + |
| 118 | +```rust |
| 119 | +pub trait Command { |
| 120 | + fn execute(&self) -> Result<String>; |
| 121 | + fn name(&self) -> &'static str; |
| 122 | + fn description(&self) -> &'static str; |
| 123 | +} |
| 124 | +``` |
| 125 | + |
| 126 | +### 2. Trait-Based Architecture |
| 127 | +Core functionality is built around traits for flexibility and testability: |
| 128 | + |
| 129 | +```rust |
| 130 | +pub trait GitRepository { |
| 131 | + fn current_branch(&self) -> Result<String>; |
| 132 | + fn branch_exists(&self) -> Result<bool>; |
| 133 | + // ... other git operations |
| 134 | +} |
| 135 | + |
| 136 | +pub trait Destructive { |
| 137 | + fn safety_checks(&self) -> Result<()>; |
| 138 | + fn requires_confirmation(&self) -> bool; |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | +### 3. Module Organization Pattern |
| 143 | +Commands are grouped by functional domain: |
| 144 | +- **Repository Operations**: Info, health, sync, upstream management |
| 145 | +- **Branch Management**: Create, clean, prune, rename, switch |
| 146 | +- **Commit Operations**: Fixup, undo, bisect workflows |
| 147 | +- **Analysis & Reporting**: Statistics, graphs, technical debt analysis |
| 148 | + |
| 149 | +### 4. Safety-First Design |
| 150 | +Destructive operations implement safety mechanisms: |
| 151 | +- Confirmation prompts for destructive actions |
| 152 | +- Non-interactive mode support for CI/CD |
| 153 | +- Validation of git repository state before operations |
| 154 | +- Clear error messages with recovery suggestions |
| 155 | + |
| 156 | +## Benefits of This Architecture |
| 157 | + |
| 158 | +### 1. **Clear Separation of Concerns** |
| 159 | +- CLI parsing separated from command logic |
| 160 | +- Git operations isolated in core layer |
| 161 | +- Output formatting centralized in adapters |
| 162 | +- Domain logic encapsulated in dedicated layer |
| 163 | + |
| 164 | +### 2. **Enhanced Testability** |
| 165 | +- Each command can be unit tested independently |
| 166 | +- Core git operations mockable through traits |
| 167 | +- Domain logic testable without CLI dependencies |
| 168 | +- Integration tests validate end-to-end workflows |
| 169 | + |
| 170 | +### 3. **Improved Maintainability** |
| 171 | +- Commands organized by functional domain |
| 172 | +- Consistent patterns across all implementations |
| 173 | +- Clear module boundaries and responsibilities |
| 174 | +- Reduced code duplication through shared utilities |
| 175 | + |
| 176 | +### 4. **Type Safety & Reliability** |
| 177 | +- Rust's type system prevents common errors |
| 178 | +- Comprehensive error handling with `Result<T>` |
| 179 | +- Input validation prevents security vulnerabilities |
| 180 | +- Compile-time guarantees for data flow |
| 181 | + |
| 182 | +### 5. **User Experience Focus** |
| 183 | +- Rich output formatting with colors and emojis |
| 184 | +- Interactive prompts with fuzzy search |
| 185 | +- Consistent help system and error messages |
| 186 | +- Shell completion support across platforms |
| 187 | + |
| 188 | +### 6. **Extensibility** |
| 189 | +- New commands follow established patterns |
| 190 | +- Plugin architecture possible through trait system |
| 191 | +- Alternative interfaces can reuse core and domain layers |
| 192 | +- Easy to add new git workflow automations |
| 193 | + |
| 194 | +## Current Implementation Status |
| 195 | + |
| 196 | +### ✅ Completed Components |
| 197 | +1. **Core Layer**: Complete with traits, git operations, validation, and safety |
| 198 | +2. **Command Layer**: 21 commands implemented across 6 functional areas |
| 199 | +3. **CLI Layer**: Full clap-based CLI with shell completion support |
| 200 | +4. **Output System**: Rich formatting with colors, emojis, and interactive elements |
| 201 | +5. **Testing**: Comprehensive test suite with integration and unit tests |
| 202 | + |
| 203 | +### 🚧 Partial Implementation |
| 204 | +1. **Domain Layer**: Basic branch manager implemented, extensible for more complex workflows |
| 205 | +2. **Adapter Layer**: Output formatting complete, CLI handlers can be expanded |
| 206 | + |
| 207 | +### 📋 Future Enhancements |
| 208 | +1. **Enhanced Domain Services**: More sophisticated workflow coordination |
| 209 | +2. **Configuration Management**: User preferences and project-specific settings |
| 210 | +3. **Plugin System**: External command integration |
| 211 | +4. **Performance Optimizations**: Parallel git operations and caching |
| 212 | + |
| 213 | +## Implementation Examples |
| 214 | + |
| 215 | +### Command Implementation Pattern |
| 216 | + |
| 217 | +All commands follow this consistent pattern: |
| 218 | + |
| 219 | +```rust |
| 220 | +use crate::core::traits::Command; |
| 221 | +use crate::core::git::GitOperations; |
| 222 | + |
| 223 | +pub struct ExampleCommand { |
| 224 | + param: String, |
| 225 | +} |
| 226 | + |
| 227 | +impl ExampleCommand { |
| 228 | + pub fn new(param: String) -> Self { |
| 229 | + Self { param } |
| 230 | + } |
| 231 | +} |
| 232 | + |
| 233 | +impl Command for ExampleCommand { |
| 234 | + fn execute(&self) -> Result<String> { |
| 235 | + // 1. Validate input |
| 236 | + // 2. Perform git operations |
| 237 | + // 3. Format output |
| 238 | + Ok("Command completed successfully".to_string()) |
| 239 | + } |
| 240 | + |
| 241 | + fn name(&self) -> &'static str { |
| 242 | + "example" |
| 243 | + } |
| 244 | + |
| 245 | + fn description(&self) -> &'static str { |
| 246 | + "Example command description" |
| 247 | + } |
| 248 | +} |
| 249 | +``` |
| 250 | + |
| 251 | +### Adding a New Command |
| 252 | + |
| 253 | +1. **Create command struct** in appropriate `commands/` module |
| 254 | +2. **Implement `Command` trait** with execute logic |
| 255 | +3. **Add to CLI enum** in `cli.rs` |
| 256 | +4. **Add dispatch logic** in `main.rs` |
| 257 | +5. **Write integration tests** following existing patterns |
| 258 | + |
| 259 | +### Testing Strategy |
| 260 | + |
| 261 | +The project uses comprehensive testing across all layers: |
| 262 | + |
| 263 | +#### Unit Tests |
| 264 | +```rust |
| 265 | +#[test] |
| 266 | +fn test_command_execution() { |
| 267 | + let repo = common::basic_repo(); |
| 268 | + let original_dir = std::env::current_dir().unwrap(); |
| 269 | + |
| 270 | + std::env::set_current_dir(repo.path()).unwrap(); |
| 271 | + |
| 272 | + let cmd = ExampleCommand::new("test".to_string()); |
| 273 | + let result = cmd.execute(); |
| 274 | + |
| 275 | + assert!(result.is_ok()); |
| 276 | + let _ = std::env::set_current_dir(&original_dir); |
| 277 | +} |
| 278 | +``` |
| 279 | + |
| 280 | +#### Integration Tests |
| 281 | +```rust |
| 282 | +#[test] |
| 283 | +fn test_cli_integration() { |
| 284 | + let repo = common::basic_repo(); |
| 285 | + |
| 286 | + repo.run_git_x(&["example", "test"]) |
| 287 | + .success() |
| 288 | + .stdout(contains("Expected output")); |
| 289 | +} |
| 290 | +``` |
| 291 | + |
| 292 | +## Code Quality & Security Features |
| 293 | + |
| 294 | +### Error Handling |
| 295 | +- Consistent `Result<String>` return types across all commands |
| 296 | +- Descriptive error messages with recovery suggestions |
| 297 | +- Graceful degradation in non-git directories |
| 298 | +- Proper error propagation through all layers |
| 299 | + |
| 300 | +### Security & Safety |
| 301 | +- **Input Validation**: Prevents shell injection in git commands |
| 302 | +- **Destructive Operation Guards**: Confirmation prompts for dangerous actions |
| 303 | +- **Non-Interactive Mode**: Safe CI/CD execution with `GIT_X_NON_INTERACTIVE` |
| 304 | +- **Branch Name Validation**: Prevents invalid git branch names |
| 305 | +- **Working Directory Checks**: Validates git repository state before operations |
| 306 | + |
| 307 | +### Performance Optimizations |
| 308 | +- **Output Buffering**: Efficient terminal output with `BufferedOutput` |
| 309 | +- **Optimized Git Commands**: Minimal git calls with proper argument handling |
| 310 | +- **Interactive Search**: Fast fuzzy search for branch/commit selection |
| 311 | +- **Parallel Test Execution**: Test suite optimized for CI/CD environments |
| 312 | + |
| 313 | +### User Experience |
| 314 | +- **Rich Output**: Colors, emojis, and formatted tables |
| 315 | +- **Progress Indicators**: Visual feedback for long-running operations |
| 316 | +- **Help System**: Comprehensive help text with examples |
| 317 | +- **Shell Completions**: Auto-complete support for all major shells |
| 318 | + |
| 319 | + |
| 320 | +## Summary |
| 321 | + |
| 322 | +The git-x architecture demonstrates a mature, production-ready CLI tool with: |
| 323 | + |
| 324 | +- **21 git workflow commands** organized across 6 functional domains |
| 325 | +- **Layered architecture** with clear separation of concerns |
| 326 | +- **Comprehensive testing** with 300+ tests ensuring reliability |
| 327 | +- **Security-first design** with input validation and safety guards |
| 328 | +- **Rich user experience** with interactive prompts and formatted output |
| 329 | +- **Cross-platform support** including shell completions |
| 330 | + |
| 331 | +This architecture provides a solid foundation for continued development while maintaining the tool's core focus: simplifying and enhancing git workflows for developers. |
| 332 | + |
| 333 | +### Key Metrics |
| 334 | +- **Commands**: 21 total across 6 categories |
| 335 | +- **Test Coverage**: 300+ tests with comprehensive scenarios |
| 336 | +- **File Organization**: ~50 source files in logical modules |
| 337 | +- **Safety Features**: Confirmation prompts, validation, non-interactive mode |
| 338 | +- **Platform Support**: Linux, macOS, Windows with shell completions |
0 commit comments