Branch management strategy
Branch Management Strategy
Branch management is one of the core features of Git. A reasonable branch strategy can significantly improve team collaboration efficiency and code quality. Different project scales, team structures, and development processes require adapting to different branch management models. The key lies in balancing flexibility and standardization.
Basic Branch Types
Main Branch (main/master)
// Created by default when initializing a repository
git init
git checkout -b main // Modern Git defaults to the branch name 'main'
The main branch always remains in a deployable state, with each commit representing a complete release version. Direct development on this branch is prohibited; updates can only be made by merging code from other branches.
Development Branch (develop)
git checkout -b develop main
An intermediate branch for integrating feature development. All new feature branches are created from this branch. When features accumulate to a releasable state, they are merged into the main branch and tagged.
Common Branch Strategy Models
Git Flow
gitGraph
commit
branch develop
checkout develop
commit
branch feature/login
commit
checkout develop
merge feature/login
branch release/v1.0
commit
checkout main
merge release/v1.0
checkout develop
merge release/v1.0
Includes five branch types:
- Feature branches:
feature/*
- Release branches:
release/*
- Hotfix branches:
hotfix/*
- Development branch:
develop
- Main branch:
main
Suitable for projects with traditional release cycles, but the process is somewhat complex.
GitHub Flow
// Typical workflow example
git checkout -b add-oauth-login main
// Create a PR after development is complete
git push origin add-oauth-login
A simplified model with only the main branch and feature branches:
- All development occurs on feature branches
- Merged into main via Pull Request
- Must pass CI tests before merging
Suitable for SaaS projects with continuous delivery.
GitLab Flow
# Variant with environment branches
git checkout -b production main
git checkout -b pre-production production
git checkout -b staging pre-production
Adds environment branches to GitHub Flow:
production
corresponds to the production environmentpre-production
corresponds to the pre-release environmentstaging
corresponds to the testing environment
Suitable for enterprise-level applications requiring multi-environment validation.
Branch Naming Conventions
Feature Branches
git checkout -b feat/user-profile # New feature
git checkout -b fix/login-error # Bug fix
git checkout -b docs/api-reference # Documentation update
Recommended prefixes:
feat/
: New feature developmentfix/
: Bug fixeschore/
: Build/tool changesrefactor/
: Code refactoringtest/
: Test-related changes
Release Branches
git checkout -b release/v1.2.0
Version numbers follow semantic versioning:
v1.2.3
where 1 is the major version, 2 is the minor version, and 3 is the patch number
Branch Lifecycle Management
Creation Strategy
// Create from the correct base branch
function createFeatureBranch(baseBranch, featureName) {
exec(`git checkout ${baseBranch}`)
exec(`git pull origin ${baseBranch}`)
exec(`git checkout -b feat/${featureName}`)
}
Key points:
- Always create from the latest code
- Keep branches short-lived (lifecycle < 2 days)
- Single-task-per-branch principle
Merge Strategy
# Recommended to use rebase for linear history
git checkout feature/x
git rebase main
git checkout main
git merge --no-ff feature/x
Merge option comparison:
--no-ff
: Preserves branch topology--squash
: Compresses into a single commitrebase
: Rewrites commit history
Conflict Resolution Practices
Conflict Prevention
// Frequently sync with the main branch
function syncWithMain() {
exec('git fetch origin')
exec('git rebase origin/main')
// Or use interactive rebase
exec('git rebase -i origin/main')
}
Conflict Resolution
<<<<<<< HEAD
const api = new RestAPI('/v2');
=======
const api = new GraphQLAPI('/graphql');
>>>>>>> feature/new-api
Resolution steps:
- Identify conflicting files
- Negotiate modifications with the original author
- Use
git add
to mark as resolved - Continue the rebase/merge process
Special Strategies for Large Projects
Long-Term Maintenance Branches
git checkout -b legacy-support v1.0.0
# Apply critical patches
git cherry-pick C1234
Applicable for:
- Maintaining old versions
- Custom versions for different clients
- A/B testing different architectures
Modular Branches
git checkout -b module/auth
git submodule add https://github.com/auth-library
Break down large systems into:
- Core repository main branch
- Independent repositories for each module
- Managed via submodule/subtree
Automation Tool Integration
CI/CD Pipeline
# .gitlab-ci.yml example
stages:
- test
- deploy
feature-test:
rules:
- if: $CI_COMMIT_BRANCH =~ /^feat\//
script:
- npm test
Branch trigger rules:
- Feature branches: Run unit tests
- Release branches: Execute full tests
- Main branch: Trigger production deployment
Branch Protection
// GitHub branch protection rule example
{
"required_status_checks": {
"strict": true,
"contexts": ["ci/build"]
},
"enforce_admins": false,
"required_pull_request_reviews": {
"dismiss_stale_reviews": true,
"required_approving_review_count": 2
}
}
Key protection measures:
- Mandatory code review
- Require passing CI
- Disable force pushes
- Restrict merge permissions
Visualization and Monitoring
Graphical Tools
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
Example output:
* 1a2b3c4 - (HEAD -> main) Update deployment script (2 hours ago) <Zhang San>
* 5e6f7g8 - Merge pull request #123 (4 hours ago) <Li Si>
|\
| * 9i0j1k2 - (feat/search) Implement advanced search (1 day ago) <Wang Wu>
|/
* l3m4n5o - Fix security vulnerability (3 days ago) <Zhao Liu>
Repository Analysis
git branch -a --sort=-committerdate # Sort by last commit time
git for-each-ref --format='%(committerdate) %09 %(authorname) %09 %(refname)' --sort=committerdate
Common metrics:
- Branch lifespan
- Last active date
- Commit frequency
- Merge conflict count
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn