Chapter 31 Exercises: Version Control Workflows

These exercises are organized into five tiers of increasing difficulty, aligned with Bloom's taxonomy. Complete them in order to build a comprehensive understanding of Git workflows in AI-assisted development.


Tier 1: Remember and Recall (Exercises 1-6)

Exercise 1: Git Area Identification

For each of the following scenarios, identify which Git area (working directory, staging area, or repository) is primarily involved:

a) You just ran git add myfile.py. b) An AI tool generated a new file on disk but you have not run any Git commands. c) You just ran git commit -m "add feature". d) You ran git add -p and selected some hunks but not others. e) You ran git stash.

Expected output: A list of area names with brief justifications.


Exercise 2: Conventional Commit Types

Match each change description to the correct conventional commit type (feat, fix, docs, style, refactor, test, chore, perf, ci, build):

a) Added a new user registration endpoint. b) Fixed a null pointer exception in the payment module. c) Updated the API documentation with new examples. d) Reformatted all Python files with Black. e) Extracted a helper function without changing behavior. f) Added unit tests for the search module. g) Updated the GitHub Actions workflow to include Python 3.12. h) Improved database query performance with a new index. i) Updated the Dockerfile to use a smaller base image. j) Bumped the requests library from 2.28 to 2.31.

Expected output: A mapping of letters to commit types with example commit messages.


Exercise 3: Merge Strategy Identification

For each scenario, identify whether a merge commit, rebase, or squash merge would be most appropriate:

a) A feature branch with 15 messy WIP commits that collectively implement one feature. b) A bug fix branch with a single clean commit. c) A long-running feature branch where you want to preserve the full development history. d) A branch where you experimented with three different AI-generated approaches before settling on one. e) A branch with two commits that need to stay on top of the latest main.

Expected output: Strategy name with a one-sentence justification for each.


Exercise 4: Git Command Matching

Match each task to the correct Git command:

a) Find which commit introduced a bug. b) Apply a specific commit from another branch. c) Temporarily save uncommitted changes. d) View a record of all HEAD movements. e) Check out multiple branches simultaneously. f) Rewrite the last 5 commits interactively.

Commands: git bisect, git cherry-pick, git stash, git reflog, git worktree, git rebase -i HEAD~5

Expected output: Matched pairs with brief descriptions of how each command works.


Exercise 5: Branch Naming Convention

Write properly formatted branch names for each of the following tasks, following the type/description convention:

a) Adding a shopping cart feature to an e-commerce app. b) Fixing a crash that occurs when users upload large images. c) Experimenting with switching from REST to GraphQL. d) Refactoring the database access layer to use an ORM. e) Updating the CI pipeline to run security scans. f) AI-generated implementation of a recommendation engine.

Expected output: Six properly formatted branch names.


Exercise 6: Semantic Version Bumps

Given the current version v3.2.1, what should the next version be for each change:

a) Fixed a typo in an error message. b) Added a new API endpoint that does not change existing endpoints. c) Removed a deprecated API endpoint that clients still use. d) Improved the performance of an existing endpoint (no API changes). e) Added a new optional parameter to an existing endpoint.

Expected output: Version numbers with justifications referencing SemVer rules.


Tier 2: Understand and Explain (Exercises 7-12)

Exercise 7: Explain the AI Commit Paradox

Write a 200-word explanation of why AI-assisted development requires more version control discipline, not less. Include at least three specific examples of how AI-generated code can create version control challenges and how the practices in this chapter address them.

Expected output: A short essay with concrete examples.


Exercise 8: Compare Branching Strategies

Create a comparison table with at least 8 dimensions comparing trunk-based development, feature branches, and Gitflow. For each dimension, explain which strategy is best suited for a team of 5 developers using AI coding tools extensively.

Expected output: A detailed comparison table with recommendations.


Exercise 9: PR Review Checklist for AI-Generated Code

Explain why reviewing AI-generated code differs from reviewing human-written code. Then create a checklist of at least 10 items that a reviewer should verify when reviewing a PR that contains AI-generated code. For each item, explain why it is especially important for AI-generated code.

Expected output: An explanatory paragraph followed by an annotated checklist.


Exercise 10: Monorepo Trade-offs Analysis

A startup has three components: a React frontend, a FastAPI backend, and a shared Python types package. They currently use three separate repositories. The team of 4 developers has just adopted AI coding tools. Write a recommendation (with justification) for whether they should migrate to a monorepo. Address at least 5 specific trade-offs.

Expected output: A structured recommendation with pros, cons, and a final verdict.


Exercise 11: Conflict Resolution Walkthrough

Given the following merge conflict, explain what happened (what each branch changed and why), then write the correct resolution:

<<<<<<< HEAD
def process_payment(amount: float, currency: str = "USD") -> PaymentResult:
    """Process a payment with currency conversion."""
    if currency != "USD":
        amount = convert_currency(amount, currency, "USD")
    return charge_card(amount)
=======
def process_payment(amount: float, retry_count: int = 3) -> PaymentResult:
    """Process a payment with automatic retry."""
    for attempt in range(retry_count):
        try:
            return charge_card(amount)
        except PaymentError:
            if attempt == retry_count - 1:
                raise
            time.sleep(2 ** attempt)
>>>>>>> feature/payment-retry

Expected output: An explanation of both sides and a merged resolution that incorporates both currency conversion and retry logic.


Exercise 12: Git Hook Justification

For each of the following Git hooks, explain (a) what it does, (b) when it runs, and (c) why it is especially valuable in AI-assisted development:

  1. Pre-commit linter check
  2. Pre-commit secret detection
  3. Commit-msg conventional format validation
  4. Pre-push test runner
  5. Post-merge dependency installer

Expected output: Structured explanations for each hook with AI-specific justifications.


Tier 3: Apply and Implement (Exercises 13-18)

Exercise 13: Implement a Conventional Commit Validator

Write a Python script that validates commit messages against the Conventional Commits specification. The script should:

  • Accept a commit message as a command-line argument or read from a file.
  • Validate the type, optional scope, and description.
  • Check that the subject line is under 72 characters.
  • Check that the body (if present) is separated from the subject by a blank line.
  • Output clear error messages for any violations.

Expected output: A complete, working Python script with type hints and docstrings.


Exercise 14: Build a Branch Manager

Write a Python script that manages Git branches for an AI-assisted development workflow:

  • List all branches with their last commit date and message.
  • Identify stale branches (no commits in the last 30 days).
  • Suggest branches that can be safely deleted (already merged into main).
  • Validate new branch names against the naming convention.
  • Display a summary of branch health.

Expected output: A complete Python script using the subprocess module to interact with Git.


Exercise 15: Create a PR Description Generator

Write a Python function that takes a Git diff and a list of commit messages and generates a structured PR description. The function should:

  • Summarize the changes in 2-3 sentences.
  • List the files changed, grouped by type (added, modified, deleted).
  • Extract any issue references from commit messages.
  • Flag potentially risky changes (large files, security-sensitive paths).
  • Generate a testing checklist.

Expected output: A complete Python function with type hints, docstrings, and example usage.


Exercise 16: Set Up Pre-commit Configuration

Create a complete .pre-commit-config.yaml file for a Python project that includes:

  • Trailing whitespace removal
  • End-of-file fixer
  • YAML validation
  • Large file detection (max 500KB)
  • Black formatting
  • Flake8 linting
  • Mypy type checking
  • Secret detection
  • A custom hook that warns about files with more than 500 lines

Write installation instructions and a script to run all hooks against the entire codebase.

Expected output: A YAML configuration file and accompanying setup script.


Exercise 17: Implement a Changelog Generator

Write a Python script that generates a changelog from Git commit history:

  • Parse conventional commit messages to categorize changes.
  • Group changes by type (Added, Fixed, Changed, Deprecated, Removed, Security).
  • Include PR/issue references if present.
  • Support generating changelogs between two tags.
  • Output in Markdown format.

Expected output: A complete Python script with example output.


Exercise 18: Git Bisect Automation Script

Write a Python script that automates git bisect for a specific type of bug:

  • Accept a good commit, bad commit, and a test command as arguments.
  • Run the bisect process programmatically.
  • Report the offending commit with its diff summary.
  • Clean up the bisect state when done.

Expected output: A complete Python script using subprocess to drive git bisect.


Tier 4: Analyze and Evaluate (Exercises 19-24)

Exercise 19: Audit a Git History

Given the following Git log, identify all the version control anti-patterns and suggest specific improvements:

* 9f2a1b3 fix
* 8e1c2d4 WIP
* 7d0b3e5 more stuff
* 6c9a4f6 Update files
* 5b8e5g7 AI generated code
* 4a7d6h8 Revert "AI generated code"
* 3f6c7i9 AI generated code v2
* 2e5b8j0 forgot to add file
* 1d4a9k1 fix typo
* 0c3f0l2 final fix
* 9b2e1m3 actually final fix
* 8a1d2n4 ok now it works

Expected output: A numbered list of anti-patterns with specific references to the log entries, followed by a rewritten commit history (after interactive rebase) with proper conventional commit messages.


Exercise 20: Evaluate Merge Strategies

A team has the following situation: - Main branch has 200 commits ahead of the feature branch's base. - Feature branch has 45 commits over 3 weeks. - 12 of the feature branch commits are "WIP" or "fix typo" commits. - The feature branch modifies 35 files, including 5 that have also been modified on main.

Analyze the trade-offs of each merge strategy (merge commit, rebase, squash) for this specific situation. Recommend a strategy and explain your reasoning step by step.

Expected output: A detailed analysis with a clear recommendation.


Exercise 21: PR Quality Assessment

Review the following PR and score it on a scale of 1-10 across five dimensions (title, description, size, commit quality, testing). Provide specific feedback for improvement.

PR Title: "Updates"
Description: "Some changes I made with Copilot"
Files changed: 47
Lines added: 2,341
Lines removed: 892
Commits: 1 (squashed)
Commit message: "Various updates and improvements"
Tests: None added
CI Status: 2 checks failing

Expected output: A scored rubric with detailed feedback for each dimension.


Exercise 22: Repository Structure Analysis

Given a monorepo with the following structure, identify potential issues and suggest improvements:

project/
├── src/
│   ├── frontend/          (React, 150 files)
│   ├── backend/           (Python, 200 files)
│   ├── mobile/            (React Native, 180 files)
│   ├── shared/            (TypeScript, 40 files)
│   └── ml-pipeline/       (Python, 90 files)
├── tests/                 (all tests for all components, 300 files)
├── .github/workflows/     (single CI pipeline)
├── package.json           (root)
├── requirements.txt       (root)
└── .gitignore             (single file)

Expected output: A list of issues with proposed restructuring and justifications.


Exercise 23: Release Process Evaluation

A team follows this release process: 1. Developer finishes a feature on a branch. 2. Developer merges directly to main (no PR). 3. When ready to release, someone manually bumps the version in setup.py. 4. The release is tagged and pushed. 5. The changelog is written manually from memory.

Evaluate this process, identify all the risks and inefficiencies, and design an improved process that incorporates AI assistance, automation, and the best practices from this chapter.

Expected output: A critique of the current process and a detailed improved process with automation recommendations.


Exercise 24: Hook Effectiveness Analysis

A team has the following pre-commit hooks: - Black formatting (auto-fix) - Flake8 linting (error on violations) - Mypy type checking (error on failures) - Pytest (runs full test suite, takes 8 minutes) - Large file detection (error on files > 1MB)

The team reports that developers are frequently running git commit --no-verify to skip hooks because the commit process takes too long. Analyze the problem and propose a solution that maintains code quality without frustrating developers.

Expected output: An analysis of the problem and a redesigned hook configuration with timing estimates.


Tier 5: Create and Synthesize (Exercises 25-30)

Exercise 25: Design a Complete Git Workflow

Design a complete Git workflow for a team of 8 developers building a SaaS application using AI coding tools. Your design should include:

  • Branching strategy with naming conventions.
  • Commit message conventions.
  • PR requirements (size, reviews, CI checks).
  • Merge strategy.
  • Release process with versioning.
  • Git hooks configuration.
  • Branch protection rules.

Document the workflow in a format suitable for a team wiki or onboarding guide.

Expected output: A comprehensive workflow document (1000+ words).


Exercise 26: Build an AI-Assisted Git CLI Tool

Design and implement a command-line tool (in Python) that provides AI-assisted Git operations:

  • ai-git commit — Analyzes staged changes and suggests a commit message.
  • ai-git pr — Generates a PR description from the branch's commit history.
  • ai-git review — Reviews staged changes for common issues.
  • ai-git changelog — Generates a changelog between two tags.

Implement at least two of these commands as fully working Python code (you may simulate the AI response with templates for testing purposes).

Expected output: A complete Python CLI tool with argument parsing, Git integration, and template-based output generation.


Exercise 27: Create a Git Workshop Curriculum

Design a 2-hour workshop curriculum for teaching AI-assisted Git workflows to a team that is experienced with basic Git but new to AI coding tools. Include:

  • Learning objectives.
  • Agenda with time allocations.
  • At least 3 hands-on exercises.
  • A cheat sheet for participants.
  • Assessment criteria.

Expected output: A complete workshop plan with all materials.


Exercise 28: Implement a Repository Health Dashboard

Write a Python script that generates a "repository health" report including:

  • Branch statistics (total, stale, unmerged).
  • Commit frequency analysis (commits per day/week).
  • Author contribution distribution.
  • Average PR size and review turnaround time.
  • Commit message quality score (based on conventional commits adherence).
  • Large file detection.

The script should output an HTML or Markdown report.

Expected output: A complete Python script that generates a Markdown health report from Git data.


Exercise 29: Design a Migration Plan

A company has 12 developers working across 8 separate repositories. They want to: 1. Migrate to a monorepo. 2. Adopt trunk-based development. 3. Implement conventional commits. 4. Set up automated releases with semantic versioning.

Design a phased migration plan that minimizes disruption. Include timelines, tooling recommendations, training requirements, and rollback plans for each phase.

Expected output: A detailed migration plan with phases, timelines, and risk mitigation strategies.


Exercise 30: End-to-End Automation Pipeline

Create a complete automation pipeline that integrates Git hooks, CI/CD, and AI assistance:

  1. Pre-commit: Lint, format, type check, secret detection.
  2. Commit-msg: Validate conventional commit format.
  3. Pre-push: Run tests, check branch naming.
  4. CI/CD (GitHub Actions workflow): Run full test suite, build, deploy to staging.
  5. PR automation: Auto-generate description, assign reviewers, label based on changed files.
  6. Release automation: Generate changelog, bump version, create GitHub release.

Implement all components as working code (shell scripts, Python scripts, and YAML configuration files).

Expected output: A complete set of automation files with documentation explaining how they work together.