Appearance
Git branch lifecycle management — DevOps guide
Branches are the unit of collaboration in Git. Left unmanaged, they accumulate, rot, and create confusion in CI/CD pipelines. This guide covers the full lifecycle: naming conventions, creation, promotion, decay detection, cleanup, and the automation policies that keep a repo healthy.
Branch topology in a DevOps context
A healthy repo has a small number of permanent branches and a large but temporary set of short-lived branches.
Permanent: main, develop, release/v*, hotfix/v*. Everything else is ephemeral. If a branch lives longer than a sprint, it is either a release branch or dead weight.
Naming conventions
Consistent names let automation parse intent from the branch name. This scheme maps directly to Forgejo/GitHub branch protection rules and CI skip logic.
| Pattern | Purpose | CI treatment |
|---|---|---|
feature/<issue>-<slug> | New feature or enhancement | Full CI |
fix/<issue>-<slug> | Bug fix on existing feature | Full CI |
hotfix/<issue>-<slug> | Urgent production fix (bypasses develop) | Full CI + immediate deploy |
release/v<major>.<minor> | Release preparation | CI + staging deploy |
chore/<slug> | Maintenance, refactor, deps | CI (no deploy) |
docs/<slug> | Documentation | Docs CI only |
deps/<slug> | Dependency updates | CI + integration tests |
wip/<user>/<slug> | Work-in-progress sharing | Light CI or skipped |
Enforce with a pre-receive hook:
bash
#!/bin/bash
# .git/hooks/pre-receive — reject branch names that don't match convention
zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
pattern='^(feature|fix|hotfix|release|chore|docs|deps|wip)\/[a-z0-9._-]+$'
while read oldrev newrev refname; do
branchname=${refname#refs/heads/}
if [[ "$branchname" != "main" && "$branchname" != "develop" ]] \
&& ! echo "$branchname" | grep -qE "$pattern"; then
echo "ERROR: Branch '$branchname' does not match naming convention."
echo " Allowed: feature/, fix/, hotfix/, release/, chore/, docs/, deps/, wip/"
exit 1
fi
doneBranch lifecycle states
CREATE → ACTIVE → MERGED → DELETE
↘ STALE → WARN → DELETECREATE
Create branches from a fresh main:
bash
git checkout main
git pull --ff-only
git checkout -b feature/1428-add-metrics-dashboardNever branch from a feature branch unless you are deliberately stacking (see --update-refs in the fixup-autosquash guide).
ACTIVE
A branch is active while it has open pull requests or recent commits. Active branches older than 14 days should be flagged unless they are release branches.
MERGED
Once merged, the remote branch should be deleted. The PR UI usually offers this. Automate it:
bash
# Delete merged branches locally
git branch --merged main | grep -v 'main\|develop' | xargs git branch -d
# Delete merged branches on remote
git branch -r --merged origin/main | grep -v 'origin/main\|origin/develop' \
| sed 's/origin\///' | xargs -I {} git push origin --delete {}STALE
A stale branch has no commits in N days and no open PR. Stale branches signal abandoned work, forgotten experiments, or dead-ends.
DELETE
Branches deleted on the remote should be cleaned from local clones too:
bash
# Prune remote-tracking branches that no longer exist
git remote prune origin
# Remove local branches whose upstream was deleted
git fetch -p && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -dStale branch detection and cleanup
Find branches with no commits in 30 days
bash
#!/bin/bash
# stale-branches.sh — list branches untouched since a cutoff
cutoff=$(date -d '30 days ago' +%s)
git for-each-ref --format='%(refname:short) %(committerdate:unix)' refs/heads/ \
| while read branch ts; do
if [ "$ts" -lt "$cutoff" ]; then
# Skip permanent branches
case "$branch" in main|develop|release/*|hotfix/*) continue;; esac
echo "$branch (last commit: $(date -d @$ts '+%Y-%m-%d'))"
fi
doneAutomated cleanup with safeguards
Never delete blindly. Use a two-stage process:
- Flag — list stale branches in a weekly CI job and post to a channel.
- Grace period — branches flagged for 7 more days without activity get deleted.
- Archive tag — before deletion, tag the branch tip so it is not truly lost:
bash
git tag archive/<branchname>-$(date +%Y%m%d) origin/$branchname
git push origin archive/<branchname>-*
git push origin --delete $branchnameRecovery
If someone needs a deleted branch back:
bash
git checkout -b <branchname> archive/<branchname>-<date>Branch protection policies (Forgejo / GitHub)
These rules prevent force-pushes and accidental deletions on critical branches.
Server-side deny for permanent branches
bash
# .git/hooks/update — on the remote (bare) repo
refname="$1"
oldrev="$2"
newrev="$3"
case "$refname" in
refs/heads/main|refs/heads/develop|refs/heads/release/*)
# Only allow fast-forward merges (no force-push, no branch delete)
if ! git merge-base --is-ancestor "$oldrev" "$newrev"; then
echo "ERROR: $refname is protected. Only fast-forward updates allowed."
exit 1
fi
;;
esac
exit 0Forgejo API protection
Set per-branch protection via git-mcp:
tool_call(name="mcp__git_mcp__get_repo", ...)
# Parse response for protection rules
# Forgejo supports branch protection via the repo settings UI and API
# Key settings:
# - Enable push restrictions on main/develop
# - Require pull request for pushes
# - Dismiss stale approvals
# - Require signed commits
# - Require up-to-date branchesWorkflow: Branch lifecycle from CI
A CI pipeline can enforce lifecycle policy without developer action.
yaml
# .forgejo/workflows/branch-lifecycle.yaml
on:
schedule:
- cron: '0 6 * * 1' # Monday 6am
jobs:
stale-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Flag stale branches
run: |
cutoff=$(date -d '30 days ago' +%s)
stale=""
git for-each-ref --format='%(refname:short) %(committerdate:unix)' refs/heads/ \
| while read branch ts; do
case "$branch" in main|develop) continue;; esac
[ "$ts" -lt "$cutoff" ] \
&& stale="$stale $branch ($(date -d @$ts '+%Y-%m-%d'))\n"
done
if [ -n "$stale" ]; then
echo "Stale branches detected:"
echo -e "$stale"
fiMerged branch cleanup automation
Safe merged branch removal
bash
#!/bin/bash
# cleanup-merged.sh — delete merged branches except protected ones
protect="^(main|develop|release/|hotfix/)"
# Local merged branches
git branch --merged origin/main \
| grep -vE "$protect" \
| xargs -r git branch -d
# Remote merged branches
git branch -r --merged origin/main \
| sed 's/origin\///' \
| grep -vE "$protect" \
| xargs -r -I{} git push origin --delete {}Post-merge hook (client-side)
Delete the branch automatically after the PR is merged:
bash
# .git/hooks/post-merge (needs core.hooksPath or in .git/hooks/)
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$current_branch" != "main" ] && [ "$current_branch" != "develop" ]; then
echo "You are on '$current_branch'. Switch to main/develop after merging."
echo "Then delete: git branch -d $current_branch && git push origin --delete $current_branch"
fiBranch lifecycle in monorepos
Monorepos make branch lifecycle harder because one branch touches many projects.
Path-scoped branch validation
Enforce that docs/* branches only touch docs/ paths:
bash
# pre-receive hook — reject docs/ branch that changes non-docs files
while read oldrev newrev refname; do
branchname=${refname#refs/heads/}
case "$branchname" in
docs/*)
non_docs=$(git diff --name-only "$oldrev" "$newrev" -- . ':!docs/' 2>/dev/null)
if [ -n "$non_docs" ]; then
echo "ERROR: docs/ branch '$branchname' changes non-docs files:"
echo "$non_docs"
exit 1
fi
;;
esac
doneCI scope detection for branch types
yaml
# Extract branch type from GITHUB_REF and route CI accordingly
- name: Determine CI scope
run: |
branch_type=$(echo "${GITHUB_REF#refs/heads/}" | cut -d/ -f1)
case "$branch_type" in
docs) echo "CI_SCOPE=docs" >> $GITHUB_ENV ;;
chore) echo "CI_SCOPE=lint" >> $GITHUB_ENV ;;
deps) echo "CI_SCOPE=deps" >> $GITHUB_ENV ;;
*) echo "CI_SCOPE=full" >> $GITHUB_ENV ;;
esacBranch archival strategy
Instead of deleting old branches (which loses PR references and commit context in some UIs), archive them:
| Method | Pros | Cons |
|---|---|---|
| Delete + archive tag | Clean branch list, recoverable | Extra tag management |
| Delete only | Simplest | No recovery path |
Prefix with archive/ | Visible in branch picker | Pollutes branch list |
| Delete + note | Preserves context in git notes | Two-step recovery |
Recommended: delete the branch, create an archive/<name>-<date> tag.
Summary of policies
| Policy | Recommendation |
|---|---|
| Naming convention | type/ticket-slug enforced via pre-receive hook |
| Max branch age | 30 days stale, 7 day grace, then delete + archive tag |
| Permanent branches | main, develop, release/*, hotfix/* with force-push deny |
| Post-merge cleanup | Auto-delete merged branches weekly via CI |
| Recovery | Archive tags under archive/ namespace |
| Scope gating | Branch type determines CI pipeline depth |