-
Notifications
You must be signed in to change notification settings - Fork 57
Description
Overview
The file pkg/cli/add_command.go has grown to 1,218 lines, making it difficult to maintain and test. This task involves refactoring it into smaller, focused files with improved test coverage.
Current State
- File:
pkg/cli/add_command.go - Size: 1,218 lines
- Test Coverage: 206 test lines (17% ratio) - primarily structural tests, missing core logic coverage
- Complexity: High - contains 17 functions handling command setup, workflow resolution, repository operations, PR creation, and file operations
- Primary Issue: The
addWorkflowWithTracking()function alone is 262 lines with high cyclomatic complexity
Full File Analysis
Detailed Breakdown
Functional Areas:
-
Command Definition & Configuration (Lines 61-203)
NewAddCommand()- 142 lines- Flag registration (11+ flags)
- Help text and usage examples
- Interactive mode decision logic
-
Workflow Resolution (Lines 208-337)
ResolveWorkflows()- 130 lines- Workflow spec parsing and validation
- Repository installation coordination
- Wildcard expansion
- Metadata extraction from frontmatter
-
Workflow Addition Logic (Lines 338-407)
AddWorkflows()- orchestrator functionAddResolvedWorkflows()- 49 lines- Routing between normal and PR flows
-
Repository Listing & Interactive Selection (Lines 408-557)
handleRepoOnlySpec()- 67 linesshowInteractiveWorkflowSelection()- 32 linesdisplayAvailableWorkflows()- 48 lines- Table rendering and user interaction
-
Normal Workflow Addition (Lines 558-658)
addWorkflowsNormal()- 101 lines- File creation and compilation
- Git operations and staging
- Push handling with confirmation
-
PR Creation Flow (Lines 661-765)
addWorkflowsWithPR()- 105 lines- Branch creation (with random suffix)
- PR creation via GitHub API
- Branch cleanup and restoration
-
Single Workflow Addition (Lines 766-1027)
⚠️ COMPLEXITY HOTSPOTaddWorkflowWithTracking()- 262 lines- File copying and path resolution
- Version management and source tracking
- Content manipulation (append, title updates)
- Compilation orchestration
- Multiple error handling paths
- Git staging integration
-
Utility Functions (Lines 1028-1218)
updateWorkflowTitle()- 12 linescompileWorkflow()and 3 variants - 115 lines totaladdSourceToWorkflow()- 8 linesexpandWildcardWorkflows()- 36 linescheckWorkflowHasDispatch()- 46 lines
Complexity Hotspots:
⚠️ addWorkflowWithTracking()(262 lines) - handles file operations, version tracking, source metadata, compilation⚠️ NewAddCommand()(142 lines) - massive flag configuration with complex help text⚠️ ResolveWorkflows()(130 lines) - orchestrates multiple subsystems (parsing, installation, expansion)⚠️ compileWorkflowWithTrackingAndRefresh()- complex compilation flow with file tracking
Coupling Issues:
The file has heavy coupling with:
workflowpackage (compilation)parserpackage (spec parsing)consolepackage (UI rendering)- Git operations (inline throughout)
- File I/O operations scattered across functions
Duplication Patterns:
- Multiple
compileWorkflow*()function variants with similar logic - Repeated git staging patterns in multiple functions
- Similar error handling and verbose flag checking
- Repeated file existence checks and path operations
Refactoring Strategy
Proposed File Splits
Split the file into 6 focused modules organized by responsibility:
1. add_command.go (Command Definition)
- Functions:
NewAddCommand(),AddWorkflows(),AddResolvedWorkflows() - Responsibility: Command registration, flag configuration, high-level orchestration
- Estimated LOC: ~250 lines
- Rationale: Keep command definition and flag setup together, delegate implementation to specialized modules
2. add_workflow_resolution.go (Workflow Resolution)
- Functions:
ResolveWorkflows(),expandWildcardWorkflows(),checkWorkflowHasDispatch() - Types:
ResolvedWorkflow,ResolvedWorkflows - Responsibility: Workflow spec parsing, repository installation, wildcard expansion, metadata extraction
- Estimated LOC: ~200 lines
- Rationale: Isolated workflow resolution logic with clear input/output contracts
3. add_workflow_repository.go (Repository Operations)
- Functions:
handleRepoOnlySpec(),showInteractiveWorkflowSelection(),displayAvailableWorkflows() - Responsibility: Repository listing, interactive workflow selection, workflow discovery
- Estimated LOC: ~150 lines
- Rationale: Repository-centric operations separate from workflow addition
4. add_workflow_operations.go (Core Addition Logic)
- Functions:
addWorkflowsNormal(),addWorkflowWithTracking() - Responsibility: Single workflow addition, file operations, source tracking, compilation
- Estimated LOC: ~400 lines (includes the large 262-line function)
- Rationale: Core file manipulation logic isolated for easier testing
- Note: The
addWorkflowWithTracking()function should be further broken down into smaller helpers:resolveWorkflowDestination()- path calculationcopyWorkflowFile()- file copying with error handlingapplyWorkflowTransformations()- content manipulation (append, title update, source metadata)compileAndTrackWorkflow()- compilation + tracking
5. add_workflow_pr.go (Pull Request Flow)
- Functions:
addWorkflowsWithPR() - Responsibility: PR creation, branch management, cleanup
- Estimated LOC: ~110 lines
- Rationale: PR-specific workflow isolated from normal addition flow
6. add_workflow_compilation.go (Compilation Helpers)
- Functions:
compileWorkflow(),compileWorkflowWithRefresh(),compileWorkflowWithTracking(),compileWorkflowWithTrackingAndRefresh(),updateWorkflowTitle(),addSourceToWorkflow() - Responsibility: Workflow compilation orchestration, title updates, source metadata
- Estimated LOC: ~150 lines
- Rationale: Compilation-related utilities grouped together, reduce duplication
- Improvement: Consolidate the 4 compile variants into a single function with options struct
Shared Utilities
Extract common patterns into helper functions:
- Git staging helpers: Consolidate repeated staging logic
- File existence checks: Centralized file/directory validation
- Verbose logging: Consistent logging pattern wrapper
- Error wrapping: Standard error context helpers
Interface Abstractions
Consider introducing interfaces to reduce coupling:
WorkflowInstallerinterface: Abstract repository installation and workflow fetchingCompilationOrchestratorinterface: Decouple compilation from addition logicGitOperationsinterface: Abstract git operations for testing
Test Coverage Plan
Add comprehensive tests for each new file targeting ≥80% coverage:
1. add_command_test.go
- Existing: Command structure validation (keep current tests)
- Add: Flag validation tests, interactive mode decision logic tests
- Target: >80% coverage of command setup
2. add_workflow_resolution_test.go
- Test workflow spec parsing (valid, invalid, edge cases)
- Test wildcard expansion (single, multiple, none found)
- Test repository installation coordination
- Test metadata extraction from frontmatter
- Test conflicting version detection
- Target: >90% coverage (critical path)
3. add_workflow_repository_test.go
- Test repository listing with metadata
- Test interactive selection (mocked console input)
- Test workflow display formatting
- Test empty repository handling
- Target: >80% coverage
4. add_workflow_operations_test.go
- Test normal workflow addition (create, overwrite, skip)
- Test file path resolution and destination calculation
- Test workflow content transformations (append, title update)
- Test source metadata addition
- Test compilation integration
- Test file tracking and rollback
- Test verbose output modes
- Target: >85% coverage (core logic)
5. add_workflow_pr_test.go
- Test PR creation flow (mocked GitHub API)
- Test branch creation and cleanup
- Test rollback on error
- Test branch restoration
- Target: >80% coverage
6. add_workflow_compilation_test.go
- Test compilation variants (with/without tracking, with/without refresh)
- Test gitattributes update
- Test compilation error handling
- Test file tracking integration
- Target: >80% coverage
Implementation Guidelines
- Preserve Behavior: Ensure all existing functionality works identically
- Maintain Exports: Keep public API unchanged (
AddWorkflows,ResolveWorkflows, exported types) - Add Tests First: Write tests for each new file before refactoring (test-driven refactoring)
- Incremental Changes: Split one module at a time in this order:
- Start with utilities (compilation, repository operations)
- Then workflow resolution
- Then PR flow
- Then core operations
- Finally, slim down command definition
- Run Tests Frequently: Verify
make test-unitpasses after each split - Update Imports: Ensure all import paths are correct
- Document Changes: Add comments explaining module boundaries and responsibilities
- Refactor
addWorkflowWithTracking(): Break down the 262-line function into smaller, testable helpers
Acceptance Criteria
- Original file is split into 6 focused files
- Each new file is under 500 lines
- All tests pass (
make test-unit) - Test coverage is ≥80% for new files (verify with coverage reports)
- No breaking changes to public API (
AddWorkflows,ResolveWorkflows,NewAddCommand) - Code passes linting (
make lint) - Build succeeds (
make build) -
addWorkflowWithTracking()is refactored into smaller helper functions - Duplicate compilation logic is consolidated
- Git operations are centralized in helper functions
Additional Context
- Repository Guidelines: Follow patterns in
AGENTS.mdandspecs/cli-command-patterns.md - Code Organization: Prefer many small files grouped by functionality
- Testing: Match existing test patterns in
pkg/cli/*_test.go - Naming Convention: Use
add_workflow_*prefix for all new files - Logger Updates: Update logger namespaces to match new filenames (e.g.,
logger.New("cli:add_workflow_resolution"))
Related Files to Review:
pkg/cli/compile_command.go- Similar command pattern, smaller implementationpkg/cli/pr_command.go(814 lines) - Could benefit from similar refactoringpkg/cli/logs_orchestrator.go(855 lines) - Another candidate for future refactoring
Priority: Medium
Effort: Large (1,218 lines → 6 files, comprehensive test coverage needed)
Expected Impact: Significantly improved maintainability, easier testing, reduced complexity, better separation of concerns
AI generated by Daily File Diet