Git - Enterprise Workflows

Advanced

Enterprise Git workflows address the unique challenges of large organizations: complex permissions, multiple teams, compliance requirements, and scale. Master these patterns for professional enterprise development.

Enterprise Git Challenges

Large organizations face unique version control challenges:

# Enterprise challenges:
# - Hundreds of developers across multiple teams
# - Complex permission models and security requirements
# - Compliance and audit trails
# - Multiple products and repositories
# - Integration with corporate systems
# - Performance at scale
# - Standardization across teams

Centralized Workflow with Controls

Protected Branch Model

# GitHub Enterprise branch protection
# Settings → Branches → Add rule

Branch protection rules:
├── Require pull request reviews
├── Dismiss stale reviews
├── Require review from code owners
├── Restrict who can dismiss reviews
├── Require status checks to pass
├── Require branches to be up to date
├── Require signed commits
├── Include administrators
└── Restrict pushes to matching branches

CODEOWNERS File

# .github/CODEOWNERS
# Global owners
* @enterprise-team/core-maintainers

# Frontend code
/frontend/ @enterprise-team/frontend-team
*.js @enterprise-team/frontend-team
*.css @enterprise-team/frontend-team

# Backend code  
/backend/ @enterprise-team/backend-team
*.java @enterprise-team/backend-team
*.py @enterprise-team/backend-team

# Infrastructure
/infrastructure/ @enterprise-team/devops
/docker/ @enterprise-team/devops
*.yml @enterprise-team/devops

# Documentation
/docs/ @enterprise-team/technical-writers
*.md @enterprise-team/technical-writers

# Security sensitive
/security/ @enterprise-team/security-team
*.pem @enterprise-team/security-team

Git Flow for Enterprise

Enhanced Git Flow Model

# Enterprise Git Flow branches:

main/master          # Production releases only
├── develop          # Integration branch
├── release/v2.1     # Release preparation
├── hotfix/urgent    # Production hotfixes
└── feature/         # Feature development
    ├── feature/auth-service
    ├── feature/payment-api
    └── feature/user-dashboard

# Support branches:
├── support/v1.0     # Long-term support
└── experimental/    # Research and prototypes

Enterprise Git Flow Commands

# Initialize Git Flow
git flow init

# Feature development
git flow feature start user-authentication
git flow feature publish user-authentication  # Share with team
git flow feature finish user-authentication   # Merge to develop

# Release process
git flow release start v2.1.0
git flow release publish v2.1.0               # QA testing
git flow release finish v2.1.0                # Merge to main + develop

# Hotfix process
git flow hotfix start critical-security-fix
git flow hotfix finish critical-security-fix  # Immediate release

# Support branches
git flow support start v1.0 main

Multi-Repository Management

Monorepo vs Multi-Repo Strategies

# Monorepo structure
enterprise-platform/
├── services/
│   ├── auth-service/
│   ├── payment-service/
│   └── user-service/
├── frontend/
│   ├── admin-dashboard/
│   └── customer-portal/
├── shared/
│   ├── libraries/
│   └── configurations/
└── tools/
    ├── build-scripts/
    └── deployment/

# Multi-repo structure  
├── auth-service (separate repo)
├── payment-service (separate repo)
├── user-service (separate repo)
├── admin-dashboard (separate repo)
├── customer-portal (separate repo)
└── shared-libraries (separate repo)

Git Submodules for Enterprise

# Add shared library as submodule
git submodule add https://github.com/company/shared-lib.git lib/shared

# Initialize submodules for new developers
git submodule update --init --recursive

# Update all submodules to latest
git submodule update --remote

# Freeze submodule at specific version
cd lib/shared
git checkout v1.2.3
cd ../..
git add lib/shared
git commit -m "Update shared library to v1.2.3"

# Submodule management script
#!/bin/bash
# update-submodules.sh
git submodule foreach 'git fetch origin; git checkout $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo main); git reset --hard origin/$(git config -f $toplevel/.gitmodules submodule.$name.branch || echo main)'

Security and Compliance

Signed Commits

# Generate GPG key
gpg --gen-key

# Configure Git to use GPG
git config --global user.signingkey <key-id>
git config --global commit.gpgsign true
git config --global tag.gpgsign true

# Sign commits manually
git commit -S -m "Signed commit for compliance"

# Verify signatures
git log --show-signature
git verify-commit HEAD

Audit Trail and Compliance

# Generate audit reports
#!/bin/bash
# audit-report.sh

SINCE_DATE=${1:-"30 days ago"}
OUTPUT_FILE="audit-report-$(date +%Y%m%d).csv"

echo "Date,Author,Email,Commit,Files,Additions,Deletions,Message" > $OUTPUT_FILE

git log --since="$SINCE_DATE" --pretty=format:"%ad,%an,%ae,%H" --date=iso --numstat | \
awk 'BEGIN {OFS=","} 
     /^[0-9]/ {date=$1; author=$2; email=$3; hash=$4; getline; files=0; add=0; del=0} 
     /^[0-9]+\t[0-9]+\t/ {files++; add+=$1; del+=$2} 
     /^$/ {print date,author,email,hash,files,add,del,"\"" message "\""; message=""} 
     !/^[0-9]/ && !/^$/ {if(message) message=message " "; message=message $0}' >> $OUTPUT_FILE

Secret Management

# Git-crypt for sensitive files
git-crypt init
git-crypt add-gpg-user [email protected]

# .gitattributes for encryption
secrets.yaml filter=git-crypt diff=git-crypt
*.key filter=git-crypt diff=git-crypt
config/production.env filter=git-crypt diff=git-crypt

# Pre-commit hook for secret detection
#!/bin/bash
# .git/hooks/pre-commit

# Check for secrets in staged files
if git diff --cached --name-only | xargs grep -l -E "(password|secret|api_key|private_key)" 2>/dev/null; then
    echo "❌ Potential secrets detected in staged files:"
    git diff --cached | grep -E "(password|secret|api_key|private_key)"
    echo "Please remove secrets or encrypt files with git-crypt"
    exit 1
fi

Performance at Scale

Partial Clone and Sparse Checkout

# Partial clone (Git 2.19+)
git clone --filter=blob:none https://github.com/large-repo.git
git clone --filter=tree:0 https://github.com/large-repo.git

# Sparse checkout for large monorepos
git clone https://github.com/company/monorepo.git
cd monorepo
git config core.sparseCheckout true
echo "services/my-service/*" > .git/info/sparse-checkout
echo "shared/libraries/*" >> .git/info/sparse-checkout
git read-tree -m -u HEAD

# Update sparse checkout
git sparse-checkout set services/my-service shared/libraries
git sparse-checkout add frontend/admin-dashboard

LFS for Large Assets

# Install and configure Git LFS
git lfs install
git lfs track "*.psd"
git lfs track "*.zip"
git lfs track "*.mp4"
git lfs track "docs/*.pdf"

# .gitattributes entries
*.psd filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
docs/*.pdf filter=lfs diff=lfs merge=lfs -text

# Migrate existing large files
git lfs migrate import --include="*.psd,*.zip"

# LFS management
git lfs ls-files                    # List LFS files
git lfs fetch                       # Download LFS files
git lfs prune                       # Clean up old LFS files

Team Coordination

Multiple Team Integration

# Integration manager workflow
# Team leads as integration managers

# Frontend team workflow
git checkout -b integration/frontend
git merge team-a/feature-auth
git merge team-b/feature-dashboard
# Run integration tests
git push origin integration/frontend

# Backend team workflow  
git checkout -b integration/backend
git merge team-c/feature-api
git merge team-d/feature-database
# Run integration tests
git push origin integration/backend

# Final integration
git checkout develop
git merge integration/frontend
git merge integration/backend
# Run full system tests

Cross-Team Dependencies

# Dependency management with Git
# teams.yml - Team dependency configuration
teams:
  frontend:
    depends_on: [shared-components, api-contracts]
    repositories: [admin-dashboard, customer-portal]
  
  backend:
    depends_on: [shared-libraries, database-schemas]  
    repositories: [auth-service, payment-service]
  
  infrastructure:
    depends_on: []
    repositories: [kubernetes-configs, terraform-modules]

# Dependency check script
#!/bin/bash
# check-dependencies.sh

TEAM=$1
DEPENDENCIES=$(yq eval ".teams.$TEAM.depends_on[]" teams.yml)

for dep in $DEPENDENCIES; do
    echo "Checking dependency: $dep"
    cd ../shared/$dep
    
    # Check if dependency has breaking changes
    if git log --since="7 days ago" --grep="BREAKING" --oneline | grep -q "BREAKING"; then
        echo "⚠️  Breaking changes detected in $dep"
    fi
done

Release Management

Enterprise Release Pipeline

# Release branches with environment promotion
main (production)
├── staging       # Staging environment  
├── qa           # QA environment
└── develop      # Development environment

# Promotion workflow
#!/bin/bash
# promote-release.sh

FROM_ENV=$1
TO_ENV=$2
VERSION=$3

case "$TO_ENV" in
    "qa")
        git checkout qa
        git merge develop
        git tag -a "qa-$VERSION" -m "QA release $VERSION"
        ;;
    "staging")  
        git checkout staging
        git merge qa
        git tag -a "staging-$VERSION" -m "Staging release $VERSION"
        ;;
    "production")
        git checkout main
        git merge staging  
        git tag -a "v$VERSION" -m "Production release $VERSION"
        ;;
esac

git push origin $TO_ENV
git push origin --tags

Hotfix and Rollback Procedures

# Emergency hotfix procedure
#!/bin/bash
# emergency-hotfix.sh

ISSUE_ID=$1
DESCRIPTION=$2

# Create hotfix from production
git checkout main
git pull origin main
git checkout -b "hotfix/emergency-$ISSUE_ID"

echo "1. Make your emergency fix"
echo "2. Test thoroughly"
echo "3. Run: git add . && git commit -m 'Emergency fix: $DESCRIPTION'"
echo "4. Run: git push origin hotfix/emergency-$ISSUE_ID"
echo "5. Create emergency PR for review"
echo "6. After approval, merge to main"
echo "7. Cherry-pick to develop: git cherry-pick <hotfix-commit>"

# Rollback procedure
#!/bin/bash
# rollback-production.sh

PREVIOUS_VERSION=$1

echo "Rolling back to version: $PREVIOUS_VERSION"
git checkout main
git reset --hard $PREVIOUS_VERSION
git push --force-with-lease origin main

echo "⚠️ Production rollback completed"
echo "Don't forget to:"
echo "1. Update monitoring dashboards"  
echo "2. Notify stakeholders"
echo "3. Create incident report"

Automation and Integration

Git Hooks for Enterprise

# Server-side pre-receive hook
#!/bin/bash
# hooks/pre-receive

while read oldrev newrev refname; do
    # Enforce branch naming conventions
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    
    if [[ $branch =~ ^(feature|bugfix|hotfix)/.+ ]]; then
        echo "✓ Branch naming convention: $branch"
    elif [[ $branch =~ ^(main|develop|release/.+)$ ]]; then
        echo "✓ Protected branch: $branch"
    else
        echo "❌ Invalid branch name: $branch"
        echo "Use: feature/*, bugfix/*, hotfix/*, release/*"
        exit 1
    fi
    
    # Enforce commit message format
    git rev-list $oldrev..$newrev | while read commit; do
        message=$(git log --format=%B -n 1 $commit)
        if ! echo "$message" | grep -qE "^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}"; then
            echo "❌ Invalid commit message format: $commit"
            echo "Use: type(scope): description"
            exit 1
        fi
    done
done

Automated Quality Gates

# Quality gate script
#!/bin/bash
# quality-gate.sh

BRANCH=$1
COMMIT=$2

echo "Running quality gates for $BRANCH at $COMMIT"

# Code quality checks
echo "1. Running code quality analysis..."
sonarqube-scanner -Dsonar.projectKey=enterprise-app -Dsonar.sources=src

# Security scanning  
echo "2. Running security scan..."
snyk test --severity-threshold=high

# License compliance
echo "3. Checking license compliance..."
license-checker --production --onlyAllow 'MIT;Apache-2.0;BSD-3-Clause'

# Test coverage
echo "4. Checking test coverage..."
COVERAGE=$(npm run test:coverage | grep "All files" | awk '{print $4}' | sed 's/%//')
if [ "$COVERAGE" -lt 80 ]; then
    echo "❌ Test coverage too low: $COVERAGE%"
    exit 1
fi

echo "✅ All quality gates passed"

Monitoring and Analytics

Development Metrics

# Development analytics script
#!/bin/bash
# dev-metrics.sh

REPO_PATH=$1
SINCE_DATE=${2:-"30 days ago"}

echo "Development Metrics Report"
echo "=========================="
echo "Repository: $REPO_PATH"
echo "Period: Since $SINCE_DATE"
echo ""

# Commit activity
echo "Commit Activity:"
git --git-dir="$REPO_PATH/.git" log --since="$SINCE_DATE" --pretty=format:"%ad" --date=short | sort | uniq -c

# Author contributions
echo -e "\nTop Contributors:"
git --git-dir="$REPO_PATH/.git" shortlog --since="$SINCE_DATE" -sn | head -10

# Code churn
echo -e "\nCode Churn:"
git --git-dir="$REPO_PATH/.git" log --since="$SINCE_DATE" --stat --pretty=format: | awk '/^ / { files++; insertions += $4; deletions += $6 } END { print "Files changed:", files, "\nInsertions:", insertions, "\nDeletions:", deletions }'

# Branch health
echo -e "\nBranch Health:"
echo "Active branches: $(git --git-dir="$REPO_PATH/.git" branch -r | wc -l)"
echo "Stale branches (>30 days): $(git --git-dir="$REPO_PATH/.git" for-each-ref --format='%(refname:short) %(committerdate)' refs/remotes | awk '$2 < "'$(date -d '30 days ago' +%Y-%m-%d)'"' | wc -l)"

Best Practices

Enterprise Git Best Practices:
  • Implement consistent branching strategy across all teams
  • Use signed commits for compliance and security
  • Automate quality gates and security scanning
  • Establish clear code ownership with CODEOWNERS
  • Monitor repository health and performance metrics
  • Provide team training and documentation
  • Plan for disaster recovery and backup strategies

Enterprise Git Training Program

# Training levels and paths

Level 1: Git Basics (All developers)
├── Version control concepts
├── Basic Git commands
├── Branch and merge workflows
└── Company Git standards

Level 2: Advanced Git (Senior developers)
├── Interactive rebase and history management
├── Conflict resolution strategies  
├── Git internals understanding
└── Performance optimization

Level 3: Git Leadership (Team leads, architects)
├── Workflow design and implementation
├── Repository architecture decisions
├── Security and compliance requirements
└── Tool integration and automation

Level 4: Git Administration (DevOps, platform teams)
├── Git server management
├── Performance tuning at scale
├── Backup and disaster recovery
└── Enterprise integration patterns

Troubleshooting at Scale

# Enterprise troubleshooting toolkit
#!/bin/bash
# git-enterprise-health.sh

echo "Enterprise Git Health Check"
echo "==========================="

# Repository size analysis
echo "Repository Analysis:"
git count-objects -v -H

# Performance metrics
echo -e "\nPerformance Metrics:"
time git log --oneline -1000 >/dev/null
echo "Time to scan 1000 commits: $(time git log --oneline -1000 >/dev/null 2>&1 | grep real)"

# Object database health
echo -e "\nObject Database:"
git fsck --full --strict

# Network performance (for remote operations)
echo -e "\nNetwork Performance:"
time git ls-remote origin >/dev/null

# Hook performance
echo -e "\nHook Performance:"
time find .git/hooks -executable -type f -exec {} \;

Key Takeaways

  • Scale Planning: Design workflows that support hundreds of developers
  • Security First: Implement comprehensive security and compliance measures
  • Automation: Automate quality gates, security scanning, and compliance checks
  • Team Coordination: Establish clear processes for multi-team collaboration
  • Performance: Optimize for large repositories and distributed teams
  • Governance: Implement consistent policies and standards across organization

Enterprise Git workflows require careful planning, robust automation, and clear governance. Master these patterns to successfully manage Git at enterprise scale while maintaining security, compliance, and developer productivity.