---
name: git-workflow
description: Intelligent Git workflow automation that manages branches, commits, and releases with best practices.
isolation: worktree
---

# git-workflow

Intelligent Git workflow automation that manages branches, commits, and releases with best practices.

## Usage

Ask me to manage your Git workflow. I'll handle branching, commits, merges, and releases automatically.

## Interactive Git Setup

### Workflow Questions

```
Q1: Workflow type?
   - Git Flow
   - GitHub Flow
   - GitLab Flow
   - Custom workflow

Q2: Branch strategy?
   - Feature branches
   - Release branches
   - Hotfix branches
   - All types

Q3: Commit style?
   - Conventional commits
   - Semantic commits
   - Custom format
   - Simple messages

Q4: Release strategy?
   - Semantic versioning
   - Calendar versioning
   - Custom versioning
   - No versioning

Q5: Automation level?
   - Full automation
   - Semi-automatic
   - Manual approval
   - Advisory only
```

## Automated Git Management

### Phase 1: Branch Management

```bash
#!/bin/bash
# smart-branching.sh

# Create feature branch
create_feature_branch() {
  local feature_name=$1
  local base_branch=${2:-develop}

  # Ensure clean working directory
  if [[ -n $(git status -s) ]]; then
    echo "⚠️ Uncommitted changes detected"
    git stash push -m "Auto-stash before creating feature/$feature_name"
  fi

  # Update base branch
  git checkout $base_branch
  git pull origin $base_branch

  # Create and push feature branch
  git checkout -b feature/$feature_name
  git push -u origin feature/$feature_name

  echo "✅ Created feature/$feature_name from $base_branch"
}

# Create release branch
create_release_branch() {
  local version=$1

  # Generate version if not provided
  if [[ -z "$version" ]]; then
    version=$(npm version patch --no-git-tag-version | sed 's/v//')
  fi

  git checkout -b release/$version develop
  git push -u origin release/$version

  echo "✅ Created release/$version"
}

# Create hotfix branch
create_hotfix_branch() {
  local issue=$1

  git checkout -b hotfix/$issue main
  git push -u origin hotfix/$issue

  echo "✅ Created hotfix/$issue"
}
```

### Phase 2: Smart Commits

```javascript
// generate-commit-message.js
function generateCommitMessage(changes) {
  const types = {
    "src/components/": "feat",
    "src/styles/": "style",
    "tests/": "test",
    "docs/": "docs",
    "package.json": "deps",
    ".github/": "ci",
    "src/utils/": "refactor",
  };

  // Analyze changes
  const analysis = analyzeChanges(changes);

  // Generate conventional commit
  const type = determineType(analysis, types);
  const scope = determineScope(analysis);
  const description = generateDescription(analysis);
  const breaking = detectBreakingChanges(analysis);

  let message = `${type}`;
  if (scope) message += `(${scope})`;
  message += `: ${description}`;

  if (analysis.details.length > 0) {
    message += "\n\n" + analysis.details.join("\n");
  }

  if (breaking) {
    message += "\n\nBREAKING CHANGE: " + breaking;
  }

  return message;
}

// Auto-commit with generated message
async function smartCommit() {
  const changes = await getChanges();
  const message = generateCommitMessage(changes);

  // Stage changes intelligently
  for (const file of changes.files) {
    if (shouldStage(file)) {
      await exec(`git add ${file}`);
    }
  }

  // Commit with generated message
  await exec(`git commit -m "${message}"`);

  console.log(`✅ Committed: ${message.split("\n")[0]}`);
}
```

### Phase 3: Merge Management

```javascript
// smart-merge.js
class SmartMerge {
  async mergeBranch(source, target, options = {}) {
    const {
      squash = false,
      noFastForward = true,
      deleteAfter = true,
    } = options;

    // Pre-merge checks
    await this.preMergeChecks(source, target);

    // Attempt merge
    let mergeCommand = `git merge ${source}`;
    if (squash) mergeCommand += " --squash";
    if (noFastForward) mergeCommand += " --no-ff";

    try {
      await exec(`git checkout ${target}`);
      await exec(`git pull origin ${target}`);
      await exec(mergeCommand);

      // Run tests
      if (!(await this.runTests())) {
        throw new Error("Tests failed after merge");
      }

      // Push changes
      await exec(`git push origin ${target}`);

      // Cleanup
      if (deleteAfter) {
        await exec(`git branch -d ${source}`);
        await exec(`git push origin --delete ${source}`);
      }

      console.log(`✅ Merged ${source} into ${target}`);
    } catch (error) {
      // Handle merge conflicts
      if (error.message.includes("CONFLICT")) {
        await this.resolveConflicts();
      }
    }
  }

  async resolveConflicts() {
    const conflicts = await this.getConflicts();

    for (const file of conflicts) {
      console.log(`Resolving conflict in ${file}`);

      // Try automatic resolution
      const resolved = await this.autoResolve(file);

      if (!resolved) {
        // Mark for manual resolution
        await this.markForManualResolution(file);
      }
    }

    // If all resolved, continue merge
    if (await this.allConflictsResolved()) {
      await exec("git commit --no-edit");
    }
  }
}
```

### Phase 4: Release Management

```javascript
// release-manager.js
class ReleaseManager {
  async createRelease(type = "minor") {
    // 1. Determine version
    const currentVersion = await this.getCurrentVersion();
    const newVersion = this.bumpVersion(currentVersion, type);

    // 2. Create release branch
    await exec(`git checkout -b release/${newVersion} develop`);

    // 3. Update version files
    await this.updateVersionFiles(newVersion);

    // 4. Generate changelog
    await this.generateChangelog(newVersion);

    // 5. Run release checks
    await this.runReleaseChecks();

    // 6. Create PR
    await this.createReleasePR(newVersion);

    // 7. After approval, merge and tag
    await this.finalizeRelease(newVersion);

    return newVersion;
  }

  async generateChangelog(version) {
    const commits = await this.getCommitsSinceLastRelease();
    const grouped = this.groupCommitsByType(commits);

    const changelog = `
# Release ${version} - ${new Date().toISOString().split("T")[0]}

## 🚀 Features
${grouped.feat.map((c) => `- ${c.description}`).join("\n")}

## 🐛 Bug Fixes
${grouped.fix.map((c) => `- ${c.description}`).join("\n")}

## 📚 Documentation
${grouped.docs.map((c) => `- ${c.description}`).join("\n")}

## 🔧 Maintenance
${grouped.chore.map((c) => `- ${c.description}`).join("\n")}

## ⚠️ Breaking Changes
${grouped.breaking.map((c) => `- ${c.description}`).join("\n")}
    `;

    await fs.writeFile("CHANGELOG.md", changelog);
  }

  async finalizeRelease(version) {
    // Merge to main
    await exec("git checkout main");
    await exec(`git merge --no-ff release/${version}`);

    // Tag release
    await exec(`git tag -a v${version} -m "Release version ${version}"`);

    // Merge back to develop
    await exec("git checkout develop");
    await exec("git merge main");

    // Push everything
    await exec("git push origin main develop --tags");

    // Clean up
    await exec(`git branch -d release/${version}`);
    await exec(`git push origin --delete release/${version}`);
  }
}
```

### Phase 5: Git Hooks

```javascript
// .githooks/pre-commit
#!/bin/bash

echo "🔍 Running pre-commit checks..."

# 1. Lint staged files
npx lint-staged

# 2. Run type checks
npm run typecheck

# 3. Check for secrets
if git diff --cached --name-only | xargs grep -E "(api_key|secret|password|token)" > /dev/null; then
  echo "❌ Potential secret detected in commit"
  exit 1
fi

# 4. Check commit message
commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .+'
if ! grep -qE "$commit_regex" "$1"; then
  echo "❌ Commit message doesn't follow conventional format"
  exit 1
fi

echo "✅ Pre-commit checks passed"
```

## Git Workflow Automation

```yaml
# .github/workflows/git-automation.yml
name: Git Workflow Automation

on:
  pull_request:
    types: [opened, synchronize]
  push:
    branches: [main, develop]

jobs:
  auto-merge:
    if: github.event.pull_request.labels.contains('auto-merge')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Auto-merge PR
        run: |
          if [[ "${{ github.event.pull_request.mergeable_state }}" == "clean" ]]; then
            gh pr merge ${{ github.event.pull_request.number }} --auto --squash
          fi

  version-bump:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Bump version
        run: |
          npm version patch
          git push --follow-tags
```

## Example Output

```
🔀 Git Workflow Started

Understanding your workflow...
✓ Type: Git Flow
✓ Branches: Feature + Release
✓ Commits: Conventional
✓ Versioning: Semantic
✓ Automation: Full

Current status:
📊 Branch: develop
📊 Behind main: 0 commits
📊 Ahead of main: 12 commits
📊 Uncommitted: 3 files

Creating feature branch...
✅ Created feature/user-dashboard

Making changes...
✅ 5 files modified
✅ 2 files added

Committing with smart message...
✅ Committed: feat(dashboard): add user analytics widget

Running checks...
✅ Tests passing
✅ Linting clean
✅ No conflicts

Creating pull request...
✅ PR #123 created
✅ CI/CD triggered
✅ Review requested

After approval...
✅ Merged to develop
✅ Branch deleted
✅ Changelog updated

Release preparation...
✅ Version bumped to 1.2.0
✅ Release notes generated
✅ Tagged v1.2.0
✅ Deployed to production

📊 Workflow Summary:
- Feature implemented
- 12 commits added
- 0 conflicts resolved
- Version 1.2.0 released
- All checks passed
```
