---
name: source-control-management
description: Manage source control systems including repository organization, branching strategies, access controls, code ownership, and git operations at scale. Use when setting up repository structures, defining branching models (GitFlow, trunk-based), configuring branch protection rules, managing CODEOWNERS, implementing commit policies, managing repository access, or establishing source control governance. Triggers on phrases like "source control", "git management", "branching strategy", "GitFlow", "trunk-based development", "branch protection", "CODEOWNERS", "repository governance", "git hooks", "commit policy", "merge strategy", "release branching", "git workflow".
---

# Source Control Management

Enterprise source control governance covering repository organization, branching strategies, access control, code review enforcement, and git operations at organizational scale.

## Workflow

1. Select source control platform: GitHub Enterprise, GitLab (self-managed or SaaS), Bitbucket Data Center, Azure DevOps Repos; evaluate based on team size, integration needs, compliance requirements, budget.
2. Define repository organization strategy: monorepo vs. polyrepo; repository naming conventions; group/organization structure; template repositories for standardization.
3. Establish branching strategy: trunk-based development (recommended for CI/CD), GitFlow (for release-managed products), GitHub Flow (for continuous deployment); document and communicate to all teams.
4. Configure branch protection rules: required reviews, required status checks, restriction on direct pushes, linear history enforcement, signed commit requirements.
5. Implement CODEOWNERS framework: define code ownership by directory/owner; require owner approval for changes; document ownership responsibility.
6. Set up pre-commit and commit hooks: linting, formatting, secret scanning, commit message validation; enforce consistent commit standards.
7. Configure access controls: role-based permissions (admin, maintainer, developer, reporter, read-only); team-based access; external contributor policy.
8. Implement release management: tag conventions (semantic versioning), release branching (if applicable), changelog automation, release notes generation.
9. Establish source control metrics: code review cycle time, merge frequency, branch age, developer productivity metrics; dashboard for engineering leadership.
10. Conduct quarterly audits: repository hygiene (archived repos, stale branches), access reviews (unused accounts, excessive permissions), compliance checks (branch protection coverage).

## Branching Strategy Framework

```
BRANCHING STRATEGIES COMPARISON
=================================

TRUNK-BASED DEVELOPMENT (Recommended for CI/CD):

  Model:
    → Single main branch (main/trunk) as source of truth
    → Short-lived feature branches (hours to 1-2 days, not weeks)
    → Merge to main multiple times per day
    → Feature flags for incomplete features
    → Continuous integration and continuous deployment

  Branch Structure:
    main/
    └── feature/[brief-description] (short-lived, merged within 1-2 days)
    └── fix/[brief-description] (short-lived bug fix)
    └── hotfix/[brief-description] (emergency fix, merged immediately)

  Branch Protection (main):
    → Required reviewers: 1 (fast feedback; quality via automation)
    → Required status checks: All CI checks must pass
    → No direct pushes (all changes via PR/MR)
    → Linear history: Squash merge or rebase only
    → Dismiss stale reviews: Auto-dismiss on new push

  Advantages:
    → Minimal merge conflicts (short-lived branches)
    → Fast feedback loop (code in main within hours)
    → Always-shippable main branch
    → Simple workflow (less branching overhead)
    → Best for continuous deployment

  Disadvantages:
    → Requires mature CI/CD (fast, reliable pipeline)
    → Feature flags add complexity
    → Not suitable for long development cycles (months)
    → Cultural shift for teams used to long branches

  Best for: Web applications, SaaS products, teams with mature CI/CD, startups, continuous delivery organizations

GITFLOW (For Release-Managed Products):

  Model:
    → Long-lived branches: main (production), develop (integration)
    → Feature branches branched from develop, merged back to develop
    → Release branches for stabilization and QA
    → Hotfix branches from main for emergency production fixes
    → Tags for each production release

  Branch Structure:
    main/ (production — only stable, released code)
    develop/ (integration — next release features)
    feature/[name]/ (branched from develop, merged to develop)
    release/[version]/ (branched from develop, merged to main + develop)
    hotfix/[name]/ (branched from main, merged to main + develop)

  Branch Protection:
    main:
      → Required reviewers: 2+
      → Required status checks: All tests + security scan + deployment check
      → No direct pushes
      → Only release/ and hotfix/ branches can merge
    develop:
      → Required reviewers: 1+
      → Required status checks: All tests + security scan
      → No direct pushes
      → Only feature/ and release/ branches can merge

  Release Process:
    1. Create release/X.Y.Z branch from develop
    2. Freeze feature additions (only bug fixes on release branch)
    3. QA testing on release branch
    4. Fix bugs found during QA (on release branch)
    5. Tag release (vX.Y.Z)
    6. Merge release branch to main (and tag)
    7. Merge release branch back to develop (sync fixes)
    8. Deploy from tagged release

  Advantages:
    → Clear separation between development and production
    → Structured release process
    → Good for regulated industries (audit trail per release)
    → Supports parallel feature development

  Disadvantages:
    → Complex workflow (5 branch types to manage)
    → Long-lived develop branch → merge conflicts
    → Slower feedback loop (code sits in develop for weeks)
    → Release branches add overhead

  Best for: Desktop applications, mobile apps, products with formal release cycles, regulated industries, organizations with QA gates

GITHUB FLOW (Simplified Continuous Deployment):

  Model:
    → Single main branch (no develop branch)
    → Branch off main for every change (feature, fix, experiment)
    → Open pull request early (even for WIP feedback)
    → Deploy to staging/production after merge
    → Ship when ready (no formal release process)

  Branch Structure:
    main/ (always deployable)
    └── [any-descriptive-name] (short-lived, merged when ready)

  Branch Protection (main):
    → Required reviewers: 1+
    → Required status checks: Build + test + deploy
    → No direct pushes
    → Conversation must be resolved before merge

  Advantages:
    → Simplest workflow (easiest to learn)
    → Great for web applications with continuous deployment
    → Minimal branching overhead
    → Encourages small, frequent changes

  Disadvantages:
    → No formal release management
    → Not suitable for products needing versioned releases
    → Less structure for large teams

  Best for: Web applications, SaaS products, teams deploying continuously, small to medium teams

BRANCH NAMING CONVENTIONS:

  Feature: feature/[JIRA-123]-brief-description
  Bug Fix: fix/[JIRA-456]-brief-description
  Hotfix: hotfix/critical-issue-description
  Release: release/v1.2.3
  Documentation: docs/brief-description
  Refactor: refactor/brief-description
  Chore: chore/dependency-updates

  Rules:
    → Lowercase with hyphens (not underscores or camelCase)
    → Include ticket/issue reference
    → Keep description brief (3-5 words)
    → No personal names in branch names
```

## Repository Organization

```
REPOSITORY ORGANIZATION STRATEGY
==================================

MONOREPO vs. POLYREPO:

  Monorepo (Single Repository for All Code):

    Structure:
      company-monorepo/
      ├── packages/
      │   ├── api-gateway/
      │   ├── auth-service/
      │   ├── payment-service/
      │   └── shared-utils/
      ├── apps/
      │   ├── web-frontend/
      │   ├── mobile-app/
      │   └── admin-dashboard/
      ├── infra/
      │   ├── terraform/
      │   └── kubernetes-manifests/
      ├── docs/
      └── tools/

    Advantages:
      → Single source of truth (one clone, all code)
      → Cross-project changes in single commit/PR
      → Shared dependencies and utilities (no version mismatch)
      → Unified CI/CD pipeline configuration
      → Easy code discovery and refactoring across projects
      → Atomic commits (related changes together)

    Disadvantages:
      → Repository grows large (slow clone, high disk usage)
      → Access control is all-or-nothing (cannot restrict per-project)
      → CI/CD must be efficient (affected path detection critical)
      → Requires mature tooling (Bazel, Buck, Nx, Turborepo)
      → Team coordination overhead (merge conflicts across teams)

    Best for: Organizations with tightly coupled services (Google, Meta, Monada); teams using Nx/Bazel; companies prioritizing code sharing

  Polyrepo (Multiple Repositories):

    Structure:
      GitHub Organization / GitLab Group
      ├── team-frontend/
      │   ├── web-app/
      │   └── mobile-app/
      ├── team-backend/
      │   ├── api-gateway/
      │   ├── auth-service/
      │   └── payment-service/
      ├── team-platform/
      │   ├── terraform-infrastructure/
      │   └── kubernetes-config/
      └── team-shared/
          ├── shared-lib/
          └── design-system/

    Advantages:
      → Granular access control (per-repository permissions)
      → Independent CI/CD pipelines per repository
      → Smaller repositories (fast clone, low disk)
      → Team autonomy (own repo, own pipeline, own release)
      → Technology diversity (different repos can use different stacks)

    Disadvantages:
      → Cross-repository changes require coordination (multiple PRs)
      → Dependency version management (semantic versioning required)
      → Code duplication (shared utilities duplicated across repos)
      → Harder to refactor across repositories
      → Discovery requires repository browsing/search

    Best for: Organizations with independent teams; microservices architecture; companies needing granular access control; open-source projects

REPOSITORY NAMING CONVENTIONS:

  Format: [team-or-domain]-[service-name]

  Examples:
    → payments-checkout-service
    → auth-user-management
    → platform-api-gateway
    → frontend-web-application
    → data-analytics-pipeline
    → infra-terraform-aws

  Rules:
    → Lowercase with hyphens
    → Prefix with team or domain for easy filtering
    → Avoid abbreviations (use full words)
    → Include service type if helpful (service, app, lib, tool)

TEMPLATE REPOSITORIES:

  Purpose: Standardize new repository setup with pre-configured templates

  Templates Provided:
    → Backend Service Template: Standard directory structure, CI pipeline, Dockerfile, README template
    → Frontend Application Template: React/Vue/Angular scaffold, linting config, CI pipeline, storybook
    → Library Template: Package structure, publishing config, documentation template, changelog
    → Infrastructure Template: Terraform module structure, validation pipeline, security scanning

  Usage:
    → "Use template" button in GitHub/GitLab
    → Internal developer portal (Backstage) for template selection
    → Automated repo creation via API for onboarding
```

## Access Control and Governance

```
SOURCE CONTROL ACCESS CONTROL
================================

ROLE-BASED PERMISSIONS:

  Administrator:
    → Full repository control
    → Can change settings, webhooks, integrations
    → Can manage branch protection rules
    → Can add/remove other administrators
    → Can delete repository
    → Assignment: Repository owners, lead engineers (maximum 2-3 per repo)

  Maintainer / Write:
    → Push to non-protected branches
    → Create and merge PRs/MRs (to protected branches, if authorized)
    → Manage issues and project boards
    → Cannot change repository settings
    → Cannot delete repository
    → Assignment: Senior engineers, tech leads on the project

  Developer:
    → Push to own branches
    → Create PRs/MRs (cannot merge to protected branches)
    → Comment on PRs/MRs
    → Cannot push directly to main/develop
    → Assignment: All active project contributors

  Reporter / Read-Write:
    → Clone and pull repository
    → Create issues and comment
    → Cannot push code
    → Assignment: QA team, product managers, stakeholders

  Read-Only:
    → Clone and pull repository
    → View code, issues, PRs
    → Cannot comment or create issues
    → Assignment: Auditors, external reviewers, onboarding engineers

TEAM-BASED ACCESS:

  Model: Assign permissions to teams, not individuals
    → Team: platform-backend-team → Write access to backend repos
    → Team: security-reviewers → Read access to all repos + review rights
    → Team: release-managers → Merge access to release branches

  Benefits:
    → Easier onboarding/offboarding (add/remove from team)
    → Consistent access across related repositories
    → Audit trail by team (not by individual)

  Implementation:
    → GitHub: Organizations with teams; team synchronization with LDAP/SCIM
    → GitLab: Groups and subgroups; LDAP/SCIM integration
    → Bitbucket: Project roles with group assignment

EXTERNAL CONTRIBUTOR POLICY:

  Process:
    → Contributor submits PR to public repository
    → Maintainer reviews and approves
    → Contributor signs DCO (Developer Certificate of Origin) or CLA (Contributor License Agreement)
    → PR merged after approval + DCO/CLA verification
    → Contributor not added as repository member (fork-and-PR model)

  Enterprise External Contributors (vendors, partners):
    → Temporary access via expiring invitation
    → Access limited to specific repositories
    → Access reviewed monthly; revoked if not needed
    → All activity logged and monitored
```

## Integration Points

- **GitHub Enterprise**: Repository management; branch protection; CODEOWNERS; GitHub Actions (CI/CD); Dependabot (dependency updates); GitHub Advanced Security (code scanning, secret scanning); $21/user/month
- **GitLab (Self-Managed/SaaS)**: Repository management; CI/CD built-in; container registry; dependency proxy; security scanning; compliance management; tiered pricing from free to $199/user/month
- **Bitbucket Data Center**: Repository management; Bitbucket Pipelines; Stash integrations; Atlassian ecosystem (Jira, Confluence, Bamboo); per-user pricing
- **Azure DevOps Repos**: Git repositories; branch policies; PR workflows; Azure DevOps ecosystem integration; included in Azure DevOps plans
- **Pre-commit Hooks**: Client-side validation before commit; linting, formatting, secret scanning (git-secrets, TruffleHog); framework-agnostic; free
- **Backstage (Spotify)**: Internal developer portal; template management; software catalog; integrates with GitHub/GitLab/Bitbucket; open-source
- **SonarQube / SonarCloud**: Code quality analysis; quality gates; integrates as PR check; multi-language support
- **GitHub/GitLab Webhooks**: Trigger CI/CD pipelines, notifications, and automation on repository events (push, PR, merge, tag)

## Edge Cases

- **Very large repositories (10GB+)**: Git performance degrades; solution: git sparse-checkout (checkout only needed directories); git LFS for large files; consider splitting into multiple repositories; shallow clones for CI/CD
- **Merged organizations (M&A)**: Multiple repository structures to consolidate; different branching strategies and workflows; solution: phased migration; maintain both structures during transition; align on governance post-merge
- **Regulated industries requiring audit trails**: Every code change must be traceable; signed commits required; branch protection enforced; PR history retained; solution: enforce signed commits (GPG/SSH); enable audit log; archive repositories for compliance
- **Open-source + proprietary code**: Need to share some code publicly while keeping core proprietary; solution: separate repositories with clear boundaries; use open-source for shared libraries; dual-licensing model if applicable; careful dependency management
- **High-security environments (air-gapped)**: No internet access for source control; solution: self-hosted GitLab/Bitbucket; manual update process for server patches; internal mirror for open-source dependencies; USB-based code transfer if needed
- **Legacy SVN/CVS migration to Git**: Historical migration preserving commit history; solution: svn2git or git-svn for migration; preserve branch/tag structure; train team on Git workflow; keep SVN read-only for reference period
- **Cross-team dependencies in polyrepo**: Changes in shared library require coordinated updates across consuming repos; solution: semantic versioning; automated dependency update tools (Dependabot, Renovate); CI checks for breaking changes; clear changelog communication
