diff --git a/.cursor/commands/create-pr.md b/.cursor/commands/create-pr.md index f80757e..abb5913 100644 --- a/.cursor/commands/create-pr.md +++ b/.cursor/commands/create-pr.md @@ -31,32 +31,43 @@ When creating a pull request, follow these steps: git rebase main ``` -3. **Run pre-commit hooks and tests:** +3. **Ensure all changes are committed:** ```bash - # Ensure all checks pass - git status # Should show clean working directory + git status # Must show "nothing to commit, working tree clean" ``` -4. **Self-review your changes:** + - **All work must be committed before creating PR** + - No uncommitted changes allowed + - No untracked files that should be included + - See [git-commit.md](./git-commit.md) for commit guidelines + +4. **Run pre-commit hooks and tests:** + + ```bash + # All pre-commit hooks should have passed during commits + # Verify tests pass if applicable + ``` + +5. **Self-review your changes:** - Read through the diff - Check for console.logs, TODOs, or debug code - Verify all tests pass - - Run pre-commit hooks + - Confirm pre-commit hooks passed -5. **Push your branch:** +6. **Push your branch:** ```bash git push origin your-branch ``` -6. **Create the pull request:** +7. **Create the pull request:** ```bash gh pr create ``` -7. **Fill out the PR template** with: +8. **Fill out the PR template** with: - Clear, descriptive title - Detailed description of changes - Related issues (if applicable) @@ -176,6 +187,7 @@ Examples: Before creating PR, ensure: +- **All changes are committed** (clean working directory) - Branch follows naming convention - Commits follow conventional format - All pre-commit hooks pass diff --git a/.cursor/commands/solve-issue.md b/.cursor/commands/solve-issue.md new file mode 100644 index 0000000..1bce44a --- /dev/null +++ b/.cursor/commands/solve-issue.md @@ -0,0 +1,673 @@ +# Solve Issue Command + +This command provides a comprehensive workflow for solving GitHub issues with proper planning, implementation, and pull request submission. + +**Usage:** `/solve-issue ` + +For complete documentation on related workflows, see: + +**Related Documentation:** + +- **[Git Commit Guidelines](./git-commit.md)** +- **[Pull Request Guidelines](./create-pr.md)** +- **[Git Workflow](./../git-workflow.md)** +- **[PR Template](./../pr-template.md)** + +## ⚠️ CRITICAL: Methodical Approach Required + +This command emphasizes **careful planning, user feedback, and clean commits**. For an automated approach, see [yolo-issue.md](./yolo-issue.md). + +## Workflow + +### 1. Fetch and Analyze the Issue + +**Get issue details:** + +```bash +# Get current repo +REPO=$(gh repo view --json nameWithOwner --jq .nameWithOwner) + +# Fetch issue details +gh issue view --json number,title,body,labels,state,assignees +``` + +**Analyze:** +- Read the issue description carefully +- Identify the problem or feature request +- Note any acceptance criteria +- Check for related issues or dependencies +- Review any labels or assignees + +**Output to user:** +- Issue title and number +- Description summary +- Current state +- Your initial understanding of the task + +### 2. Check Repository State + +**⚠️ CRITICAL: Verify clean working directory** + +```bash +git status +``` + +**If NOT clean (uncommitted changes exist):** + +❌ **STOP IMMEDIATELY** and inform the user: + +```text +⚠️ Cannot proceed with issue resolution! + +Your working directory has uncommitted changes: +[list the modified/untracked files] + +You must commit or stash these changes before starting work on an issue. + +Options: +1. Commit changes: See git-commit.md for guidelines +2. Stash changes: git stash save "description" +3. Discard changes: git restore . (⚠️ destructive) + +After cleaning up, run this command again. +``` + +**If clean (working tree clean):** + +✅ Proceed to next step + +### 3. Create and Checkout Issue Branch + +**Check if branch exists:** + +```bash +# Check local branches +git branch --list "issue" + +# Check remote branches +git branch -r --list "origin/issue" +``` + +**Branch naming:** `issue` (e.g., `issue42`) + +**If branch doesn't exist:** + +```bash +# Ensure main is up to date +git checkout main +git pull origin main + +# Create new branch +git checkout -b issue +``` + +**If branch already exists locally:** + +```bash +# Checkout existing branch +git checkout issue + +# Update from remote if it exists +git pull origin issue 2>/dev/null || echo "No remote branch yet" + +# Rebase on latest main +git rebase main +``` + +**Confirm to user:** +- ✓ Branch: `issue` +- ✓ Based on latest `main` +- ✓ Ready for development + +### 4. Create Implementation Plan + +**Create `.cursor/plans/` directory if it doesn't exist:** + +```bash +mkdir -p .cursor/plans +``` + +**Generate comprehensive plan and save to:** `.cursor/plans/issue-.md` + +**Plan structure:** + +```markdown +# Issue #: + +## Problem Statement + +[Clear description of the issue/feature] + +## Analysis + +### Current State +- [What exists now] +- [Relevant code locations] +- [Dependencies/constraints] + +### Required Changes +- [What needs to change] +- [Files to modify] +- [New files to create] + +## Implementation Options + +### Option 1: [Approach Name] + +**Description:** [How this approach works] + +**Pros:** +- [Advantage 1] +- [Advantage 2] + +**Cons:** +- [Disadvantage 1] +- [Disadvantage 2] + +**Estimated Complexity:** Low/Medium/High + +**Files to modify:** +- `path/to/file1.py` +- `path/to/file2.py` + +### Option 2: [Alternative Approach] + +[Same structure as Option 1] + +### Option 3: [Another Alternative] + +[Same structure as Option 1] + +## Recommended Approach + +**Choice:** Option [X] + +**Rationale:** [Why this is the best approach] + +## Implementation Steps + +1. [Step 1 with file references] +2. [Step 2 with file references] +3. [Step 3 - Add tests] +4. [Step 4 - Update documentation] +5. [Step 5 - Update CHANGELOG.md] + +## Testing Strategy + +- [Unit tests to add] +- [Integration tests needed] +- [Manual testing steps] + +## Acceptance Criteria + +- [ ] [Criterion 1] +- [ ] [Criterion 2] +- [ ] [All tests pass] +- [ ] [Documentation updated] +- [ ] [CHANGELOG.md updated] + +## Related Issues/PRs + +- Related to #[X] +- Depends on #[Y] +``` + +**After creating the plan:** + +1. **Display the plan to the user** +2. **If multiple viable options exist, ASK FOR FEEDBACK:** + +```text +I've created an implementation plan with 3 approaches: + +Option 1 (Recommended): [Brief description] + Pros: [Key advantages] + Cons: [Key disadvantages] + +Option 2: [Brief description] + Pros: [Key advantages] + Cons: [Key disadvantages] + +Option 3: [Brief description] + Pros: [Key advantages] + Cons: [Key disadvantages] + +My recommendation is Option 1 because [rationale]. + +Would you like me to: +1. Proceed with Option 1 (recommended) +2. Use Option 2 +3. Use Option 3 +4. Modify the plan + +Please confirm or provide feedback. +``` + +**Wait for user confirmation before implementing** + +### 5. Implement the Solution + +**Follow these principles throughout implementation:** + +#### Commit Strategy (Critical) + +**Make regular, atomic commits** following [git-commit.md](./git-commit.md): + +**Commit frequency guidelines:** +- After each logical unit of work (every 30-60 mins of work) +- When a specific step in the plan is complete +- Before making risky changes +- When tests pass for a component + +**Commit structure examples:** + +```bash +# Step 1: Initial implementation +git add src/module.py +git commit -m "feat(module): implement core functionality for issue #42" + +# Step 2: Add tests +git add tests/test_module.py +git commit -m "test(module): add unit tests for issue #42" + +# Step 3: Documentation +git add docs/module.md +git commit -m "docs(module): document new functionality for issue #42" + +# Step 4: Update changelog +git add CHANGELOG.md +git commit -m "docs(changelog): add entry for issue #42" +``` + +**⚠️ ALWAYS reference issue number in commits:** +- In commit message body: `Fixes #42` or `Related to #42` +- In commit description for context + +#### Code Quality Standards + +**Follow these principles:** +- ✅ **SOLID principles** - Single responsibility, proper abstraction +- ✅ **DRY** - Don't repeat yourself, extract common logic +- ✅ **Clear naming** - Descriptive variable and function names +- ✅ **Proper error handling** - Handle edge cases gracefully +- ✅ **Type hints** - Use type annotations (Python/TypeScript) +- ✅ **Documentation** - Docstrings for functions/classes +- ✅ **No magic numbers** - Use named constants +- ✅ **Configuration over hardcoding** - Use config files/env vars + +#### Testing Requirements + +**Add tests for:** +- ✅ Core functionality (unit tests) +- ✅ Edge cases and error conditions +- ✅ Integration points +- ✅ Regression tests if fixing a bug + +**Test coverage:** +- Aim for high coverage of new/modified code +- Include both positive and negative test cases + +#### Pre-commit Hooks + +**All commits must pass pre-commit hooks** (see [git-commit.md](./git-commit.md)): +- If hooks fail, **FIX the issues** before committing +- **NEVER use `--no-verify`** without asking user first +- Common hook failures: linting errors, formatting issues, trailing whitespace + +#### Progress Updates + +**Keep user informed:** +- Show progress after each major step +- Explain what you're implementing +- Show test results +- Report any blockers or questions + +### 6. Final Verification + +**Before creating PR, verify:** + +```bash +# 1. All tests pass +[run test command based on project] + +# 2. Working directory is clean +git status # Should be clean + +# 3. Review all commits +git log --oneline origin/main..HEAD + +# 4. Check diff +git diff origin/main...HEAD +``` + +**Checklist:** +- [ ] All planned steps completed +- [ ] Tests added and passing +- [ ] Documentation updated +- [ ] CHANGELOG.md updated (if user-facing change) +- [ ] No debug code, console.logs, or TODOs left +- [ ] All commits follow conventional format +- [ ] Pre-commit hooks passed on all commits + +### 7. Create Pull Request + +**Push the branch:** + +```bash +git push origin issue<issue-number> +``` + +**Create PR using GitHub CLI:** + +```bash +gh pr create \ + --title "fix/feat: <description> (closes #<issue-number>)" \ + --body "## Description + +[Description of changes] + +## Changes + +- [Change 1] +- [Change 2] + +## Testing + +- [x] Unit tests added +- [x] All tests passing +- [x] Manual testing completed + +## Related Issues + +Closes #<issue-number> + +## Implementation Plan + +See: .cursor/plans/issue-<number>.md" \ + --draft +``` + +**PR title format:** +- Use conventional commit type: `fix:`, `feat:`, `docs:`, etc. +- Include brief description +- Reference issue: `(closes #42)` or `(fixes #42)` + +**Example titles:** +- `feat: add user authentication (closes #42)` +- `fix: resolve database connection timeout (fixes #123)` +- `docs: update API documentation (closes #67)` + +**After PR creation:** + +1. **Inform user:** + - ✓ PR created (show URL) + - ✓ Status: Draft + - ✓ Linked to issue #X + - ✓ Implementation plan included + +2. **Next steps:** + - Wait for CI checks + - Address any automated feedback + - Mark as "Ready for review" when ready + - Respond to review comments + +### 8. Mark PR Ready for Review + +**After CI passes and you're confident:** + +```bash +gh pr ready <pr-number> +``` + +**Inform user:** + +```text +✅ Issue #<number> solution complete! + +Summary: +- Branch: issue<number> +- Commits: <count> atomic commits +- Tests: All passing +- PR: #<pr-number> (ready for review) +- Plan: .cursor/plans/issue-<number>.md + +The PR is now ready for maintainer review. +``` + +## Best Practices + +### Planning Phase + +- **Thorough analysis** - Understand the issue completely before coding +- **Multiple options** - Consider different approaches +- **Get feedback** - Ask user for preference when there are trade-offs +- **Document plan** - Save plan for future reference + +### Implementation Phase + +- **Atomic commits** - Small, focused commits (review [git-commit.md](./git-commit.md)) +- **Test as you go** - Don't leave testing until the end +- **Follow style** - Match existing code style and patterns +- **Incremental progress** - Complete one step before moving to next + +### Quality Checklist + +Before committing any code: +- [ ] Follows project coding standards +- [ ] No hardcoded values (use constants/config) +- [ ] Proper error handling +- [ ] Type hints/annotations added +- [ ] Docstrings for new functions/classes +- [ ] No commented-out code +- [ ] No console.logs or debug prints +- [ ] Imports organized properly + +### Communication + +- **Be transparent** - Share your reasoning +- **Ask when uncertain** - Don't guess on ambiguous requirements +- **Explain trade-offs** - When there are multiple valid approaches +- **Show progress** - Keep user updated on long-running tasks + +## Common Scenarios + +### Scenario 1: Simple Bug Fix + +```bash +# 1. Fetch issue +gh issue view 42 + +# 2. Check clean +git status + +# 3. Create branch +git checkout -b issue42 + +# 4. Create simple plan +# (Can be brief for obvious bugs) + +# 5. Fix + test + commit +git commit -m "fix(api): resolve timeout in /users endpoint + +Increased connection timeout from 5s to 30s to handle +slow database queries during peak hours. + +Fixes #42" + +# 6. Update changelog +git commit -m "docs(changelog): add fix for issue #42" + +# 7. PR +gh pr create --title "fix: resolve API timeout (fixes #42)" +``` + +### Scenario 2: Complex Feature + +```bash +# 1. Fetch issue +gh issue view 67 + +# 2. Extensive analysis +# - Review related code +# - Identify dependencies +# - Consider architecture + +# 3. Create detailed plan with options +# - Save to .cursor/plans/issue-67.md +# - Present options to user +# - Wait for feedback + +# 4. Implement in phases +# Phase 1: Core logic (commit) +# Phase 2: Tests (commit) +# Phase 3: Integration (commit) +# Phase 4: Documentation (commit) +# Phase 5: Changelog (commit) + +# 5. Create PR with comprehensive description +``` + +### Scenario 3: Issue Requires Clarification + +```text +After analyzing issue #89, I have questions: + +The issue states "improve performance" but doesn't specify: +1. Which operation is slow? +2. What's the current performance baseline? +3. What's the target performance? + +I recommend: +- Commenting on the issue to ask for clarification +- OR making reasonable assumptions and documenting them + +How would you like to proceed? +``` + +## Troubleshooting + +### Working Directory Not Clean + +```text +⚠️ Cannot start: uncommitted changes detected + +Modified files: + M src/app.py + M tests/test_app.py + +Please commit these first: + git add src/app.py tests/test_app.py + git commit -m "feat(app): describe your changes" + +Or stash them: + git stash save "work in progress" + +Then run solve-issue again. +``` + +### Branch Already Exists + +```bash +# If local branch exists +git checkout issue42 +git rebase main # Update with latest + +# If you want to start fresh +git branch -D issue42 +git checkout -b issue42 +``` + +### Pre-commit Hooks Failing + +**DO NOT skip hooks!** + +```bash +# Fix the reported issues +# For Python linting +uv run ruff check --fix . + +# For shell scripts +shellcheck script.sh + +# Then commit +git commit -m "your message" +``` + +See [git-commit.md](./git-commit.md) for detailed pre-commit hook guidelines. + +### Issue is Complex or Blocked + +**Communicate with user:** + +```text +After analyzing issue #X, I've identified some concerns: + +Blockers: +- Depends on unmerged PR #Y +- Requires database schema changes +- Needs security review + +Recommendations: +1. Wait for PR #Y to merge +2. Create separate issue for schema migration +3. Implement feature flag for gradual rollout + +Should we proceed with a partial implementation or wait? +``` + +## Quick Reference + +### Command Sequence + +```bash +# 1. Fetch issue +gh issue view <number> + +# 2. Verify clean state +git status + +# 3. Create branch +git checkout main && git pull +git checkout -b issue<number> + +# 4. Create plan +mkdir -p .cursor/plans +# [Create plan file] + +# 5. Implement with regular commits +git commit -m "type(scope): description + +Related to #<number>" + +# 6. Push and PR +git push origin issue<number> +gh pr create --title "type: description (closes #<number>)" --draft +``` + +### Files to Update + +Common files that may need updating: +- **Source code** - Your implementation +- **Tests** - Unit/integration tests +- **Documentation** - README, docs/, docstrings +- **CHANGELOG.md** - User-facing changes +- **Configuration** - If adding new features + +### Commit Message Template + +```bash +git commit -m "type(scope): brief description + +Detailed explanation of what changed and why. +Include context that would help reviewers understand +the changes. + +Related to #<issue-number> +Fixes #<issue-number> # Use this in final commit" +``` + +--- + +**For an automated approach without user confirmations, see [yolo-issue.md](./yolo-issue.md).** + +**For detailed commit and PR guidelines, see [git-commit.md](./git-commit.md) and [create-pr.md](./create-pr.md).** diff --git a/.cursor/commands/yolo-issue.md b/.cursor/commands/yolo-issue.md new file mode 100644 index 0000000..ff19090 --- /dev/null +++ b/.cursor/commands/yolo-issue.md @@ -0,0 +1,892 @@ +# YOLO Issue Command 🚀 + +**⚠️ WARNING: AUTONOMOUS MODE - MINIMAL USER INTERVENTION** + +This command provides a **fully autonomous, aggressive approach** to solving GitHub issues. +The AI will make independent decisions, implement solutions following best practices, +and create a pull request without seeking approval at each step. + +**Usage:** `/yolo-issue <issue-number>` + +**When to use:** + +- ✅ You trust the AI's judgment completely +- ✅ Issue is well-defined with clear requirements +- ✅ You want a production-ready, fully-tested solution +- ✅ You're comfortable with the AI making architectural decisions + +**When NOT to use:** +- ❌ Issue has ambiguous requirements +- ❌ Major architectural decisions needed +- ❌ Breaking changes required +- ❌ You want to review the plan first + +**For a methodical approach with user input, see [solve-issue.md](./solve-issue.md).** + +## 🎯 Autonomous Workflow + +### Mode Characteristics + +**YOLO Mode means:** + +1. **Zero confirmation requests** - AI decides and acts +2. **Production quality** - SOLID, DRY, well-tested code +3. **Best practices enforced** - No shortcuts, no hardcoding +4. **Comprehensive testing** - Unit, integration, edge cases +5. **Complete documentation** - Code comments, docstrings, README updates +6. **Proactive commits** - Regular atomic commits throughout +7. **No half measures** - Solution is complete or nothing + +**AI will autonomously:** +- Choose the best implementation approach +- Refactor existing code if needed +- Add extensive tests +- Update all relevant documentation +- Make architectural improvements +- Ensure code quality and maintainability +- Create production-ready PR + +### 1. Issue Analysis & Repository State + +**Fetch issue without asking:** + +```bash +# Get repository +REPO=$(gh repo view --json nameWithOwner --jq .nameWithOwner) + +# Fetch issue +gh issue view <issue-number> --json number,title,body,labels,state,assignees +``` + +**Analyze deeply:** +- Parse requirements and acceptance criteria +- Identify all affected components +- Review related code and patterns +- Identify potential edge cases +- Determine optimal architecture + +**Check repository state:** + +```bash +git status +``` + +**⚠️ CRITICAL: Working Directory Check** + +**If NOT clean:** + +❌ **STOP IMMEDIATELY** - Cannot proceed in YOLO mode with uncommitted changes. + +```text +🛑 YOLO MODE ABORTED + +Cannot proceed: working directory has uncommitted changes. + +Modified files: +[list files] + +YOLO mode requires a clean working directory to ensure +no work is lost during autonomous operations. + +Action required: +1. Commit your changes (see git-commit.md) +2. Stash your changes: git stash save "wip" +3. Discard changes: git restore . (destructive) + +Then run yolo-issue again. +``` + +**If clean:** + +✅ **Proceed with full autonomy** + +### 2. Branch Creation & Setup + +**Execute without confirmation:** + +```bash +# Update main +git checkout main +git pull origin main + +# Create issue branch +git checkout -b issue<issue-number> +``` + +**Inform user (info only, no wait):** + +```text +🚀 YOLO MODE ACTIVATED for Issue #<number> + +Branch: issue<number> +Mode: Fully autonomous +Target: Production-ready solution + +Working... (this may take a while) +``` + +### 3. Implementation Plan (Internal) + +**Create plan automatically:** + +Create `.cursor/plans/issue-<number>.md` with comprehensive analysis: + +```markdown +# YOLO Implementation Plan - Issue #<number> + +## Autonomous Analysis + +**Issue:** [Title] +**Type:** Bug/Feature/Enhancement +**Complexity:** Low/Medium/High +**Estimated Changes:** <number> files + +## Chosen Approach + +**Decision:** [Approach selected] + +**Rationale:** +- [Reason 1 - performance/maintainability/scalability] +- [Reason 2 - follows existing patterns] +- [Reason 3 - minimal breaking changes] + +## Implementation Breakdown + +### Phase 1: Core Implementation +- [ ] [Specific task] +- [ ] [Specific task] + +### Phase 2: Testing +- [ ] Unit tests for all new functions +- [ ] Integration tests +- [ ] Edge case coverage +- [ ] Performance tests (if applicable) + +### Phase 3: Documentation +- [ ] Docstrings for all public APIs +- [ ] README updates +- [ ] Usage examples +- [ ] CHANGELOG entry + +### Phase 4: Code Quality +- [ ] Refactor for SOLID principles +- [ ] Remove code duplication (DRY) +- [ ] Extract magic numbers to constants +- [ ] Add type hints/annotations +- [ ] Ensure proper error handling + +## Quality Gates + +All must pass: +- ✅ All tests pass +- ✅ 100% of new code has tests +- ✅ No linting errors +- ✅ No hardcoded values +- ✅ All functions documented +- ✅ Follows project patterns +- ✅ No TODOs or debug code + +## Commit Strategy + +Planned commits: +1. `feat/fix(scope): implement core solution for #<n>` +2. `test(scope): add comprehensive tests for #<n>` +3. `refactor(scope): apply SOLID/DRY principles for #<n>` +4. `docs(scope): add documentation for #<n>` +5. `docs(changelog): update for #<n>` + +## Acceptance Criteria Met + +[List from issue, all checked off when complete] +``` + +**DO NOT show plan to user** - Execute immediately. + +### 4. Implementation (Full Autonomy) + +#### Code Quality Standards (Enforced) + +**SOLID Principles - Mandatory:** + +- **Single Responsibility** - Each function/class does ONE thing +- **Open/Closed** - Extend behavior without modifying existing code +- **Liskov Substitution** - Subtypes must be substitutable for base types +- **Interface Segregation** - Many specific interfaces > one general +- **Dependency Inversion** - Depend on abstractions, not concretions + +**DRY - Don't Repeat Yourself:** +- Extract duplicate code into functions +- Create reusable utilities +- Use inheritance/composition appropriately +- Centralize configuration + +**No Hardcoding - Zero Tolerance:** +- Use configuration files +- Use environment variables +- Use named constants +- Use dependency injection + +**Clean Code Requirements:** +- Descriptive variable names (no `x`, `temp`, `data`) +- Clear function names (verb + noun) +- Functions under 50 lines (ideally 20) +- Proper error handling with specific exceptions +- Type hints on all functions (Python/TypeScript) +- Comprehensive docstrings + +#### Implementation Process + +**Phase 1: Core Implementation** + +```bash +# Implement the solution +# - Follow existing code patterns +# - Use proper abstractions +# - Handle edge cases +# - Add logging where appropriate + +# Commit when logical unit complete +git add <relevant files> +git commit -m "feat/fix(scope): implement core functionality for #<n> + +[Detailed description of implementation] +[Explain key decisions] +[Note any trade-offs] + +Related to #<n>" +``` + +**Phase 2: Comprehensive Testing** + +```bash +# Add thorough tests +# - Unit tests for each function +# - Integration tests for workflows +# - Edge cases and error conditions +# - Performance tests if applicable + +git add tests/ +git commit -m "test(scope): add comprehensive test suite for #<n> + +Tests include: +- Unit tests for [components] +- Integration tests for [workflows] +- Edge cases: [scenarios] +- Error handling: [conditions] + +Coverage: aim for >90% of new code + +Related to #<n>" +``` + +**Phase 3: Refactoring for Quality** + +```bash +# Review and refactor +# - Apply SOLID principles +# - Remove duplication +# - Extract constants +# - Improve naming +# - Add type hints + +git add <files> +git commit -m "refactor(scope): enhance code quality for #<n> + +Applied SOLID principles: +- [Specific refactorings] + +Removed duplication: +- [Extracted functions/classes] + +Improved maintainability: +- [Type hints, constants, etc.] + +Related to #<n>" +``` + +**Phase 4: Documentation** + +```bash +# Add comprehensive documentation +# - Docstrings for all public APIs +# - Update README if needed +# - Add usage examples +# - Document configuration options + +git add docs/ README.md <source files> +git commit -m "docs(scope): document solution for #<n> + +Added: +- Docstrings for all public functions +- README section on [feature] +- Usage examples +- Configuration documentation + +Related to #<n>" +``` + +**Phase 5: Changelog** + +```bash +# Update CHANGELOG.md +git add CHANGELOG.md +git commit -m "docs(changelog): add entry for #<n> + +[Brief description of user-facing change] + +Fixes #<n>" +``` + +#### Quality Enforcement (Automated) + +**Before each commit, automatically:** + +**1. Run linters and fix issues:** + +```bash +# Python +uv run ruff check --fix . +uv run ruff format . + +# Shellcheck for scripts +shellcheck *.sh + +# Other project-specific linters +``` + +**2. Run tests:** + +```bash +# Project-specific test command +[run tests] +``` + +**3. Verify no hardcoding:** + +- Scan for magic numbers +- Check for hardcoded paths/URLs +- Verify config usage + +**4. Check documentation:** + +- Verify docstrings exist +- Check for TODO/FIXME comments +- Validate examples if present + +**If quality checks fail:** +- **FIX AUTOMATICALLY** - Don't ask user +- Commit fixes separately +- Continue implementation + +### 5. Testing Strategy (Rigorous) + +**Test Coverage Requirements:** + +**Unit Tests - Mandatory:** +- Test each function independently +- Mock external dependencies +- Test happy path +- Test error cases +- Test edge cases (empty, null, boundary values) + +**Integration Tests - Required:** +- Test component interactions +- Test database operations (if applicable) +- Test API endpoints (if applicable) +- Test user workflows + +**Edge Cases - Comprehensive:** +- Empty inputs +- Null/None values +- Boundary values (0, -1, max int) +- Invalid types +- Concurrent access (if applicable) +- Large datasets (performance) + +**Example Test Structure:** + +```python +def test_new_feature_happy_path(): + """Test normal operation.""" + assert function(valid_input) == expected_output + +def test_new_feature_empty_input(): + """Test with empty input.""" + with pytest.raises(ValueError): + function("") + +def test_new_feature_null_input(): + """Test with None.""" + assert function(None) == default_value + +def test_new_feature_boundary_values(): + """Test edge cases.""" + assert function(0) == expected_for_zero + assert function(-1) == expected_for_negative + assert function(sys.maxsize) == expected_for_large + +def test_new_feature_integration(): + """Test integration with other components.""" + result = full_workflow(input) + assert result.status == "success" +``` + +### 6. Pre-PR Verification (Automated) + +**Run full verification suite:** + +```bash +# 1. All tests pass +[run all tests] + +# 2. Linting clean +[run all linters] + +# 3. Type checking (if applicable) +[mypy, typescript, etc.] + +# 4. Working directory clean +git status + +# 5. Review commits +git log --oneline origin/main..HEAD +``` + +**Verification Checklist (All automated):** +- [x] All tests passing (100%) +- [x] No linting errors (0) +- [x] No type errors (if applicable) +- [x] All new code has tests +- [x] Documentation complete +- [x] No TODOs, FIXMEs, or debug code +- [x] No console.logs or print statements +- [x] No commented-out code +- [x] CHANGELOG updated +- [x] All commits follow conventional format +- [x] Working directory clean + +### 7. Pull Request Creation (Autonomous) + +**Push branch:** + +```bash +git push origin issue<issue-number> +``` + +**Create comprehensive PR:** + +```bash +gh pr create \ + --title "<type>: <description> (closes #<issue-number>)" \ + --body "## 🚀 YOLO Mode Implementation + +This PR was autonomously generated to resolve issue #<issue-number>. + +## Description + +[Comprehensive description of changes] + +## Implementation Approach + +[Explanation of chosen approach and rationale] + +See detailed plan: `.cursor/plans/issue-<issue-number>.md` + +## Changes + +### Core Implementation +- [Change 1 with file references] +- [Change 2 with file references] +- [Change 3 with file references] + +### Tests Added +- [Test suite 1 - coverage info] +- [Test suite 2 - coverage info] +- [Edge cases covered] + +### Documentation +- [Doc update 1] +- [Doc update 2] +- [CHANGELOG entry] + +## Code Quality + +This implementation follows: +- ✅ **SOLID Principles** - [specific examples] +- ✅ **DRY** - No code duplication +- ✅ **Clean Code** - Descriptive names, proper abstractions +- ✅ **Type Safety** - Full type hints/annotations +- ✅ **Error Handling** - Comprehensive error cases +- ✅ **No Hardcoding** - Configuration-driven + +## Testing + +### Test Coverage +- Unit tests: [X files, Y functions covered] +- Integration tests: [Z scenarios] +- Edge cases: [List key edge cases] +- All tests passing: ✅ + +### Test Results +\`\`\` +[Test output summary] +\`\`\` + +## Quality Checks + +- [x] All tests passing +- [x] No linting errors +- [x] No type errors +- [x] Documentation complete +- [x] CHANGELOG updated +- [x] No debug code +- [x] Follows project conventions +- [x] Pre-commit hooks passed + +## Commits + +This PR includes [N] atomic commits: +1. \`feat/fix(scope): core implementation\` +2. \`test(scope): comprehensive test suite\` +3. \`refactor(scope): code quality improvements\` +4. \`docs(scope): documentation\` +5. \`docs(changelog): changelog entry\` + +Each commit is independently reviewable and follows conventional commit format. + +## Related Issues + +Closes #<issue-number> +[Related to #X if applicable] + +## Reviewer Notes + +This was implemented in YOLO mode with: +- Autonomous decision-making +- Best practice enforcement +- Comprehensive testing +- Production-ready quality + +Please review for: +1. Alignment with project vision +2. Any missed edge cases +3. Documentation clarity +4. Architectural fit + +## Implementation Plan + +Detailed implementation plan available at: +\`.cursor/plans/issue-<issue-number>.md\`" \ + --draft +``` + +**Mark as ready for review:** + +```bash +gh pr ready +``` + +### 8. Completion Report + +**Report to user:** + +```text +✅ YOLO MODE COMPLETE - Issue #<number> + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +📊 Summary + +Issue: #<number> - <title> +Branch: issue<number> +Commits: <N> atomic commits +Files Changed: <count> +Tests Added: <count> +Test Coverage: >90% +Lines Changed: +<added> -<removed> + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +🎯 Implementation Highlights + +✅ Core solution implemented following SOLID principles +✅ Comprehensive test suite (unit + integration + edge cases) +✅ Zero hardcoding - all values configurable +✅ Full documentation with examples +✅ CHANGELOG updated +✅ All quality checks passed + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +📁 Key Changes + +Core Implementation: +- <file1>: <description> +- <file2>: <description> + +Tests: +- <test_file1>: <description> +- <test_file2>: <description> + +Documentation: +- <doc_file>: <description> +- CHANGELOG.md: Entry added + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +🔗 Pull Request + +PR: #<pr-number> +Status: Ready for Review +URL: <pr-url> + +Plan: .cursor/plans/issue-<number>.md + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +✨ Code Quality Metrics + +- SOLID: ✅ All principles applied +- DRY: ✅ No code duplication +- Type Safety: ✅ Full type hints +- Test Coverage: ✅ >90% +- Documentation: ✅ Complete +- Linting: ✅ 0 errors +- Pre-commit: ✅ All hooks passed + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +🚀 Ready for Review + +The solution is production-ready and awaiting maintainer review. + +All autonomous decisions documented in the implementation plan. +``` + +## YOLO Mode Principles + +### Decision-Making Authority + +**AI has full authority to:** +- Choose implementation approach +- Select libraries/dependencies +- Make architectural decisions +- Refactor existing code +- Add comprehensive tests +- Update documentation +- Make quality improvements +- Determine commit granularity + +**AI will NOT:** +- Make breaking changes without noting in PR +- Delete existing functionality +- Skip tests +- Compromise on code quality +- Use `--no-verify` on commits +- Leave TODOs or incomplete work + +### Quality Non-Negotiables + +**Every YOLO implementation must have:** + +1. **SOLID Architecture** + - Single Responsibility: Each component does one thing + - Open/Closed: Extensible without modification + - Proper abstraction layers + +2. **DRY Code** + - Zero duplication + - Extracted common logic + - Reusable utilities + +3. **No Hardcoding** + - Configuration files + - Environment variables + - Named constants + - Dependency injection + +4. **Comprehensive Tests** + - >90% coverage of new code + - Edge cases covered + - Error conditions tested + - Integration tests + +5. **Complete Documentation** + - Docstrings for all public APIs + - Usage examples + - README updates + - CHANGELOG entry + +6. **Clean Code** + - Descriptive naming + - Type hints/annotations + - Proper error handling + - No debug code + +### When YOLO Mode Should Abort + +**Stop and ask user if:** + +1. **Breaking changes required** - Major API changes need discussion +2. **Security implications** - Auth, encryption, data access changes +3. **Database migrations** - Schema changes need planning +4. **External dependencies** - New major dependencies need approval +5. **Performance trade-offs** - Speed vs memory vs complexity decisions +6. **Issue is ambiguous** - Requirements unclear or contradictory +7. **Architectural overhaul** - Major refactoring beyond issue scope + +**In these cases:** + +```text +⚠️ YOLO MODE PAUSED + +Issue #<number> requires human decision: + +Situation: +[Explain the blocker] + +Options: +1. [Option A - pros/cons] +2. [Option B - pros/cons] +3. [Option C - pros/cons] + +This decision impacts: +- [Impact area 1] +- [Impact area 2] + +Recommendation: [Your recommendation with rationale] + +Please confirm approach before proceeding. +``` + +## Comparison: solve-issue vs yolo-issue + +| Aspect | solve-issue | yolo-issue | +|--------|-------------|------------| +| **User Input** | Required at key points | Minimal (only if blocked) | +| **Planning** | Show plan, get feedback | Internal plan, execute | +| **Approach Selection** | User chooses | AI decides | +| **Code Quality** | Good practices | Enforced excellence | +| **Testing** | Tests added | Comprehensive suite | +| **Commits** | Regular | Highly organized | +| **Time** | Depends on feedback | Fast (no waiting) | +| **Autonomy** | Guided | Fully autonomous | +| **Best For** | Learning, oversight | Speed, trust | + +## Examples + +### Example 1: Bug Fix + +```text +User: /yolo-issue 42 + +AI: 🚀 YOLO MODE ACTIVATED for Issue #42 + +[5 minutes later] + +✅ YOLO MODE COMPLETE + +Issue: #42 - API timeout on /users endpoint +Solution: Increased timeout + added connection pooling +Commits: 4 atomic commits +Tests: 15 new tests (unit + integration + edge cases) +PR: #156 (ready for review) + +Key improvements: +- Fixed immediate timeout issue +- Refactored connection handling (DRY) +- Added retry logic with exponential backoff +- 100% test coverage of new code +- Updated API documentation +``` + +### Example 2: Feature Implementation + +```text +User: /yolo-issue 89 + +AI: 🚀 YOLO MODE ACTIVATED for Issue #89 + +[15 minutes later] + +✅ YOLO MODE COMPLETE + +Issue: #89 - Add user profile export feature +Solution: Complete export system with multiple formats +Commits: 7 atomic commits +Tests: 28 tests (unit + integration + edge cases) +PR: #157 (ready for review) + +Implemented: +- Export to JSON, CSV, PDF formats +- Async processing for large datasets +- Progress tracking UI +- Proper error handling +- Rate limiting +- Configurable output options + +SOLID principles applied: +- Strategy pattern for export formats +- Factory for format selection +- Dependency injection for services + +No hardcoding: +- All limits in config +- File paths from env vars +- Format options configurable +``` + +## Quick Reference + +### Command + +```bash +/yolo-issue <number> +``` + +### Requirements + +- Clean working directory (no uncommitted changes) +- GitHub CLI authenticated +- Issue exists and is accessible +- Pre-commit hooks configured + +### Workflow Summary + +```text +1. Fetch issue → 2. Verify clean state → 3. Create branch + ↓ +4. Analyze & plan (internal) → 5. Implement with quality + ↓ +6. Test comprehensively → 7. Document thoroughly + ↓ +8. Create PR → 9. Report completion +``` + +### After YOLO Completion + +```bash +# Review the commits +git log origin/main..HEAD + +# Review the changes +git diff origin/main...HEAD + +# Check the plan +cat .cursor/plans/issue-<number>.md + +# View PR +gh pr view +``` + +--- + +**⚠️ Use YOLO mode responsibly:** +- For well-defined issues +- When you trust AI judgment +- For production-quality solutions +- When speed matters + +**For more control, use [solve-issue.md](./solve-issue.md) instead.** + +**For commit and PR guidelines, see [git-commit.md](./git-commit.md) and [create-pr.md](./create-pr.md).** diff --git a/CHANGELOG.md b/CHANGELOG.md index eded21d..ee6bef0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,42 @@ All notable changes to this template will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.3.3] - 2025-11-10 + +### Added + +- **Version Management System** + - `scripts/get_version.py`: Extract version from pyproject.toml + - `scripts/bump_version.py`: Automated semantic version bumping + - Supports major, minor, patch version bumps + - Auto-updates CHANGELOG.md with version and date + - Dry-run mode for previewing changes + - Comprehensive error handling and validation + - Makefile targets for version management: + - `make version`: Display current version + - `make bump-patch`: Bump patch version (0.3.2 → 0.3.3) + - `make bump-minor`: Bump minor version (0.3.2 → 0.4.0) + - `make bump-major`: Bump major version (0.3.2 → 1.0.0) + - `docs/VERSION_MANAGEMENT.md`: Comprehensive documentation + - Single source of truth approach with pyproject.toml + - Release workflow guidelines + - Best practices for version management + - Troubleshooting guide + +### Changed + +- **pyproject.toml**: Now serves as single source of truth for version numbers +- **Makefile**: Added version management section to help output + +### Benefits + +- Eliminates version number duplication across files +- Prevents version mismatches between files +- Automates CHANGELOG.md updates +- Streamlines release workflow +- Follows semantic versioning standards +- Provides both CLI and Make interfaces for version management + ## [0.3.2] - 2025-11-10 ### Added diff --git a/Makefile b/Makefile index 1dc1344..0b93cdb 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ # Builds diagrams, colors, PDF, and HTML with dark mode support # Supports multiple projects -.PHONY: all clean colors diagrams pdf html help check test example technical-documentation rebuild install-hook build-project build-summary check-outputs clean-outputs clean-generated server-start server-stop server-status +.PHONY: all clean colors diagrams pdf html help check test example technical-documentation rebuild install-hook build-project build-summary check-outputs clean-outputs clean-generated server-start server-stop server-status version bump-patch bump-minor bump-major # Default project PROJECT ?= technical-documentation @@ -125,7 +125,7 @@ check: @echo "🔍 Checking configuration..." @python3 -c "import json; json.load(open('lib/colors.json')); print('✓ lib/colors.json is valid')" @python3 -c "from pathlib import Path; assert Path('lib/technical-documentation-package.typ').exists(); print('✓ Package exists')" - @python3 -c "from pathlib import Path; assert Path('technical-documentation/technical-documentation.typ').exists(); print('✓ Main document exists')" + @python3 -c "from pathlib import Path; assert Path('docs/main.typ').exists(); print('✓ Main document exists')" @echo "✅ All checks passed" # Internal: Check that build outputs exist @@ -200,6 +200,12 @@ help: @echo " make server-stop - Stop the HTTP server" @echo " make server-status - Check server status" @echo "" + @echo "Version management:" + @echo " make version - Show current version from pyproject.toml" + @echo " make bump-patch - Bump patch version (0.3.2 → 0.3.3)" + @echo " make bump-minor - Bump minor version (0.3.2 → 0.4.0)" + @echo " make bump-major - Bump major version (0.3.2 → 1.0.0)" + @echo "" @echo "Pre-commit hook:" @echo " make install-hook - Install git pre-commit hook" @echo "" @@ -275,3 +281,35 @@ server-status: echo "ℹ️ Server not running (no PID file)"; \ echo " Start with: make server-start"; \ fi + +# ============================================================================== +# Version Management +# ============================================================================== + +# Show current version from pyproject.toml +version: + @echo "Current version: $$(python3 scripts/get_version.py)" + +# Bump patch version (0.3.2 → 0.3.3) +bump-patch: + @echo "🔄 Bumping patch version..." + @python3 scripts/bump_version.py patch + @echo "" + @echo "📝 Next: Review and update CHANGELOG.md with actual changes" + @echo "💾 Then: git add pyproject.toml CHANGELOG.md && git commit -m 'chore(release): bump version'" + +# Bump minor version (0.3.2 → 0.4.0) +bump-minor: + @echo "🔄 Bumping minor version..." + @python3 scripts/bump_version.py minor + @echo "" + @echo "📝 Next: Review and update CHANGELOG.md with actual changes" + @echo "💾 Then: git add pyproject.toml CHANGELOG.md && git commit -m 'chore(release): bump version'" + +# Bump major version (0.3.2 → 1.0.0) +bump-major: + @echo "🔄 Bumping major version..." + @python3 scripts/bump_version.py major + @echo "" + @echo "📝 Next: Review and update CHANGELOG.md with actual changes" + @echo "💾 Then: git add pyproject.toml CHANGELOG.md && git commit -m 'chore(release): bump version'" diff --git a/docs/VERSION_MANAGEMENT.md b/docs/VERSION_MANAGEMENT.md new file mode 100644 index 0000000..49c15f9 --- /dev/null +++ b/docs/VERSION_MANAGEMENT.md @@ -0,0 +1,304 @@ +# Version Management + +This document explains how version numbers are managed in this project using a **single source of truth** approach. + +## Single Source of Truth: `pyproject.toml` + +The version number is defined **once** in `pyproject.toml`: + +```toml +[project] +version = "0.3.2" +``` + +All other uses of the version number are derived from this file. + +## Version Management Tools + +### Get Current Version + +```bash +# Using Python script +python3 scripts/get_version.py + +# Using Make +make version +``` + +### Bump Version + +The `bump_version.py` script automates version bumping following [Semantic Versioning](https://semver.org/): + +```bash +# Bump patch version (0.3.2 → 0.3.3) +python3 scripts/bump_version.py patch + +# Bump minor version (0.3.2 → 0.4.0) +python3 scripts/bump_version.py minor + +# Bump major version (0.3.2 → 1.0.0) +python3 scripts/bump_version.py major + +# Dry run (show what would happen) +python3 scripts/bump_version.py patch --dry-run + +# Skip CHANGELOG update +python3 scripts/bump_version.py patch --no-changelog +``` + +**What it does:** + +1. ✅ Updates version in `pyproject.toml` +2. ✅ Adds new version entry to `CHANGELOG.md` (with date) +3. ✅ Shows next steps (commit, tag, push) + +### Using Make Targets + +```bash +# Show current version +make version + +# Bump patch version and show next steps +make bump-patch + +# Bump minor version +make bump-minor + +# Bump major version +make bump-major +``` + +## Release Workflow + +### Automated Workflow with bump_version.py + +```bash +# 1. Bump version (creates CHANGELOG entry) +python3 scripts/bump_version.py patch + +# 2. Edit CHANGELOG.md to add actual changes +vim CHANGELOG.md + +# 3. Commit +git add pyproject.toml CHANGELOG.md +git commit -m "chore(release): bump version to 0.3.3" + +# 4. Tag +git tag -a 0.3.3 -m "Release 0.3.3" + +# 5. Push +git push && git push --tags + +# 6. Create GitHub release +gh release create 0.3.3 --title "Release 0.3.3" --notes-file RELEASE_NOTES.md +``` + +### Manual Workflow (Current) + +If you prefer manual control: + +```bash +# 1. Edit version in pyproject.toml +vim pyproject.toml + +# 2. Edit CHANGELOG.md +vim CHANGELOG.md + +# 3. Commit, tag, and push (same as above) +``` + +## Where Version is Used + +### Automatically Derived + +These locations automatically read from `pyproject.toml`: + +- **Python scripts:** Can use `importlib.metadata.version("workspace")` +- **Build scripts:** Use `scripts/get_version.py` +- **Git tags:** Match the version in `pyproject.toml` +- **GitHub releases:** Use the git tag + +### Manually Maintained + +These must be updated manually (or use the bump script): + +- **CHANGELOG.md:** Version entries with dates +- **Git tags:** Must match `pyproject.toml` version +- **GitHub releases:** Should match git tags + +## Best Practices + +### 1. Keep pyproject.toml as Source of Truth + +**Always update `pyproject.toml` first**, then derive everywhere else. + +### 2. Use Semantic Versioning + +- **MAJOR** (X.0.0): Breaking changes +- **MINOR** (0.X.0): New features (backward compatible) +- **PATCH** (0.0.X): Bug fixes + +### 3. Update CHANGELOG.md + +Always document changes in CHANGELOG.md: + +```markdown +## [0.3.3] - 2025-11-10 + +### Added +- New feature X + +### Changed +- Updated component Y + +### Fixed +- Bug in Z (#123) +``` + +### 4. Tag Matches Version + +Git tags must **exactly match** the version in `pyproject.toml`: + +```bash +# pyproject.toml has version = "0.3.2" +# Tag must be: +git tag 0.3.2 # ✅ Correct + +# NOT: +git tag v0.3.2 # ❌ Wrong (extra 'v') +git tag 0.3 # ❌ Wrong (missing patch) +``` + +### 5. One Version, One Tag, One Release + +**Never reuse version numbers:** +- Each commit gets a unique version +- Each version gets a unique tag +- Each tag gets a unique release + +## Reading Version in Code + +### Python + +```python +# Using importlib.metadata (recommended) +from importlib.metadata import version +project_version = version("workspace") + +# Using get_version.py +import subprocess +result = subprocess.run( + ["python3", "scripts/get_version.py"], + capture_output=True, + text=True, +) +version = result.stdout.strip() +``` + +### Shell/Bash + +```bash +# Using get_version.py +VERSION=$(python3 scripts/get_version.py) +echo "Version: $VERSION" + +# Using grep/sed (fragile, not recommended) +VERSION=$(grep '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/') +``` + +### Make + +```makefile +# Get version +VERSION := $(shell python3 scripts/get_version.py) + +# Use in targets +release: + @echo "Building version $(VERSION)" + git tag $(VERSION) +``` + +## Troubleshooting + +### Version Mismatch + +If versions are out of sync: + +```bash +# Check what's in pyproject.toml +python3 scripts/get_version.py + +# Check git tags +git tag -l | tail -5 + +# Check latest release +gh release list --limit 5 +``` + +**Fix:** Update everything to match `pyproject.toml`. + +### CHANGELOG Missing Entry + +If you forgot to update CHANGELOG: + +```bash +# Add entry manually or run: +python3 scripts/bump_version.py patch --dry-run # Preview +python3 scripts/bump_version.py patch # Update +``` + +### Tag Already Exists + +If you need to recreate a tag: + +```bash +# Delete local tag +git tag -d 0.3.2 + +# Delete remote tag (CAREFUL!) +git push origin :refs/tags/0.3.2 + +# Create new tag +git tag -a 0.3.2 -m "Release 0.3.2" +git push --tags +``` + +## Advanced: setuptools_scm (Alternative) + +For Python packages, you can use `setuptools_scm` to derive versions from git tags automatically: + +```toml +# pyproject.toml +[build-system] +requires = ["setuptools>=45", "setuptools_scm[toml]>=6.2"] + +[tool.setuptools_scm] +write_to = "src/_version.py" +``` + +Then version is **derived from git tags** instead of being manually set. + +**Pros:** +- Version comes from git tags (single source of truth) +- No manual version updates needed + +**Cons:** +- Requires clean git state +- More complex setup +- May not fit documentation-focused projects + +## Summary + +✅ **DO:** +- Keep version in `pyproject.toml` as single source +- Use `bump_version.py` for automated bumps +- Update CHANGELOG with each version +- Match git tags to `pyproject.toml` version +- Follow semantic versioning + +❌ **DON'T:** +- Hardcode version in multiple files +- Reuse version numbers +- Forget to update CHANGELOG +- Use inconsistent tag formats +- Skip version bumps for releases diff --git a/pyproject.toml b/pyproject.toml index ccff668..e0c5f0b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ [project] name = "workspace" -version = "0.3.2" +version = "0.3.3" description = "workspace - Python project" requires-python = ">=3.12" dependencies = [ diff --git a/scripts/bump_version.py b/scripts/bump_version.py new file mode 100755 index 0000000..7a254ab --- /dev/null +++ b/scripts/bump_version.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Bump version in pyproject.toml and optionally update CHANGELOG.md.""" + +import argparse +import re +import sys +from datetime import date +from pathlib import Path + +try: + import tomllib # Python 3.11+ +except ImportError: + import tomli as tomllib # Fallback for Python 3.10 + + +def get_version(pyproject_path: Path) -> str: + """Extract current version from pyproject.toml.""" + with pyproject_path.open("rb") as f: + data = tomllib.load(f) + return data["project"]["version"] + + +def parse_version(version: str) -> tuple[int, int, int]: + """Parse semantic version string.""" + match = re.match(r"^(\d+)\.(\d+)\.(\d+)$", version) + if not match: + raise ValueError(f"Invalid version format: {version}") + return tuple(map(int, match.groups())) + + +def bump_version(version: str, bump_type: str) -> str: + """Bump version by type (major, minor, patch).""" + major, minor, patch = parse_version(version) + + if bump_type == "major": + return f"{major + 1}.0.0" + elif bump_type == "minor": + return f"{major}.{minor + 1}.0" + elif bump_type == "patch": + return f"{major}.{minor}.{patch + 1}" + else: + raise ValueError(f"Invalid bump type: {bump_type}") + + +def update_pyproject(pyproject_path: Path, new_version: str) -> None: + """Update version in pyproject.toml.""" + content = pyproject_path.read_text() + + # Replace version line + updated = re.sub( + r'^version = "[^"]+"', + f'version = "{new_version}"', + content, + flags=re.MULTILINE, + ) + + pyproject_path.write_text(updated) + print(f'✅ Updated {pyproject_path}: version = "{new_version}"') + + +def update_changelog( + changelog_path: Path, new_version: str, current_version: str +) -> None: + """Add new version entry to CHANGELOG.md.""" + if not changelog_path.exists(): + print(f"⚠️ {changelog_path} not found, skipping") + return + + content = changelog_path.read_text() + today = date.today().isoformat() + + # Find the insertion point (after the header, before first version) + header_end = content.find("\n## [") + if header_end == -1: + print(f"⚠️ Could not find version entries in {changelog_path}") + return + + new_entry = f"\n## [{new_version}] - {today}\n\n### Changed\n\n- Version bump from {current_version}\n" + + updated = content[:header_end] + new_entry + content[header_end:] + changelog_path.write_text(updated) + print(f"✅ Updated {changelog_path}: Added [{new_version}] entry") + + +def main() -> int: + """Main entry point.""" + parser = argparse.ArgumentParser( + description="Bump version in pyproject.toml and optionally update CHANGELOG.md" + ) + parser.add_argument( + "bump_type", + choices=["major", "minor", "patch"], + help="Type of version bump", + ) + parser.add_argument( + "--pyproject", + type=Path, + default=Path("pyproject.toml"), + help="Path to pyproject.toml (default: pyproject.toml)", + ) + parser.add_argument( + "--changelog", + type=Path, + default=Path("CHANGELOG.md"), + help="Path to CHANGELOG.md (default: CHANGELOG.md)", + ) + parser.add_argument( + "--no-changelog", + action="store_true", + help="Don't update CHANGELOG.md", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Show what would be done without making changes", + ) + + args = parser.parse_args() + + try: + # Get current version + current = get_version(args.pyproject) + new = bump_version(current, args.bump_type) + + print(f"Current version: {current}") + print(f"New version: {new}") + print() + + if args.dry_run: + print("🔍 DRY RUN - No changes made") + return 0 + + # Update pyproject.toml + update_pyproject(args.pyproject, new) + + # Update CHANGELOG.md + if not args.no_changelog: + update_changelog(args.changelog, new, current) + + print() + print(f"✅ Version bumped: {current} → {new}") + print() + print("Next steps:") + print(" 1. Review changes: git diff") + print(" 2. Update CHANGELOG.md with actual changes") + print(f" 3. Commit: git commit -am 'chore(release): bump version to {new}'") + print(f" 4. Tag: git tag -a {new} -m 'Release {new}'") + print(" 5. Push: git push && git push --tags") + + return 0 + + except Exception as e: + print(f"❌ Error: {e}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/get_version.py b/scripts/get_version.py new file mode 100755 index 0000000..3f5ab11 --- /dev/null +++ b/scripts/get_version.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Extract version from pyproject.toml.""" + +import sys +from pathlib import Path + +try: + import tomllib # Python 3.11+ +except ImportError: + import tomli as tomllib # Fallback for Python 3.10 + + +def get_version(pyproject_path: Path = Path("pyproject.toml")) -> str: + """Extract version from pyproject.toml.""" + with pyproject_path.open("rb") as f: + data = tomllib.load(f) + return data["project"]["version"] + + +if __name__ == "__main__": + try: + version = get_version() + print(version) + except Exception as e: + print(f"Error: {e}", file=sys.stderr) + sys.exit(1)