Preface#
If you are managing code with your team using GitHub or contributing to open source projects, you must have encountered such confusion: How should Commit Messages be written? How should branches be managed? What rules should be followed for Pull Requests? These seemingly simple questions actually directly affect the maintainability of the project and the efficiency of team collaboration.
Development teams need to manage code versions through standardized workflows. This article will systematically introduce the usage specifications of GitHub, including Commit submission specifications, branch management strategies, Pull Request processes, and project documentation standards. Whether you are a beginner just getting started with GitHub or a developer looking to optimize team collaboration processes, you will find practical advice here.
By the end of this article, you will master:
- How to write clear and standardized Commit Messages
- How to choose a branch management strategy suitable for your team
- How to correctly initiate and review Pull Requests
- How to establish a standardized open-source project structure
Commit Message Submission Specifications#
Why Standardized Commit Messages Are Needed#
By reading the commit messages, one can roughly understand the changes in this version without reading the code. Standardized commit messages not only help team members understand code changes but also:
- Quickly browse project history to understand feature evolution
- Automatically generate CHANGELOG documentation
- Facilitate tracking of bug origins and feature implementations
- Improve code review efficiency
Angular Specifications#
The Angular commit specification is one of the earliest widely adopted sets of standards, which later evolved into the more general Conventional Commits; what is commonly referred to as the "industry standard" now leans more towards the latter.
<type>(<scope>): <subject>
<body>
<footer>
Structure Explanation:
- Header (required): Contains type, scope (optional), and subject
- Body (optional): Detailed description of this commit
- Footer (optional): Related Issues or explanation of breaking changes
Detailed Explanation of the Header Section#
Type (required)
Used to indicate the category of this commit, common types include:
feat: New featurefix: Bug fixdocs: Documentation changesstyle: Code formatting adjustments (does not affect code execution)refactor: Refactoring (neither adding a feature nor fixing a bug)perf: Performance optimizationtest: Adding testschore: Changes to the build process or auxiliary toolsci: Changes to CI configuration files and scriptsbuild: Changes affecting the build system or external dependenciesrevert: Reverting a previously committed change
Scope (optional)
Used to indicate the scope affected by the commit, such as data layer, control layer, view layer, etc., depending on the project. For example: Controller, Service, API, UI, Database, etc.
Subject (required)
A brief description of the commit, generally not exceeding 50 characters. Writing requirements:
- Use imperative mood, present tense: use "change" instead of "changed" or "changes"
- Start with a lowercase letter
- Do not add a period at the end
Body Section#
The body is used to provide a detailed description of this commit, explaining:
- Why this change is needed
- The scope of the change
- Comparison with previous behavior
One line should not exceed 72 characters.
Footer Section#
The footer is mainly used for two situations:
1. Closing Issues
Using keywords can automatically close Issues:
Closes #123- Close a single IssueCloses #123, #456- Close multiple Issues- Other keywords:
Fixes,Resolves,Close,Fix,Resolve
2. Breaking Changes
If the current code is not compatible with the previous version, the footer needs to start with BREAKING CHANGE:, explaining the change description, reason for the change, and migration method.
Practical Examples#
Simple Examples:
feat(user): add user login feature
fix(api): resolve timeout issue in payment module
docs(readme): update installation guide
Complete Example:
feat(shopping-cart): add product quantity selector
Allow users to change product quantity directly in the cart page.
This improves user experience by reducing the number of clicks needed.
Closes #234
Including Breaking Changes:
refactor(api): change authentication method
BREAKING CHANGE: The authentication API now requires OAuth 2.0 instead of API keys.
All existing integrations need to be updated to use the new OAuth flow.
See migration guide: docs/migration-oauth.md
Using Tools to Ensure Compliance#
Commitizen - Interactive Submission Tool
Commitizen can provide a friendly interactive interface to help you generate standardized commit messages.
Installation and configuration:
# Install Commitizen
npm install --save-dev commitizen
# Install Angular specification adapter
npm install --save-dev cz-conventional-changelog
# Initialize
npx commitizen init cz-conventional-changelog --save-dev --save-exact
Usage:
# Use git cz instead of git commit
git add .
git cz
Commitlint - Commit Message Validation Tool
Can help us lint commit messages; if our submission does not comply with the specified standards, it will be rejected directly.
Installation configuration:
# Install
npm install --save-dev @commitlint/cli @commitlint/config-conventional
# Create configuration file
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
Combine with Husky:
# Install
npm install husky --save-dev
npx husky init
# Add commit-msg hook
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
This way, if the submission does not comply with the standards, it will be rejected each time.
Branch Management Strategies#
Why a Branch Management Strategy is Needed#
If you are not careful, you may leave a sprawling repository with branches everywhere, making it impossible to see the main development trajectory. A reasonable branching strategy can:
- Isolate the development of different features to avoid interference
- Support parallel development and rapid iteration
- Ensure the stability of the main branch code
- Facilitate version releases and rollbacks
Git Flow - Classic Branch Management Model#
Git Flow is one of the earliest systematically proposed and influential workflows, suitable for projects with clear release cycles.
Main Branches
1. main branch
- Always maintain a stable and deployable state
- Can only be updated by merging other branches
- Each merge must be tagged with a version tag
2. develop branch
- The main branch for daily development
- Contains the latest development results for the next release
- When the code reaches a stable state, merge into main and release
Auxiliary Branches
1. Feature Branches
Feature branches are used for modular feature development and are recommended to be named feature-xxx.
- Created from the develop branch
- Merged back into develop after development is complete
- Naming convention:
feature/feature-nameorfeature-feature-name - Deleted after development is complete
# Create feature branch
git checkout -b feature/user-profile develop
# Merge after development is complete
git checkout develop
git merge --no-ff feature/user-profile
git branch -d feature/user-profile
git push origin develop
2. Release Branches
Release branches are used for pre-release testing and minor bug fixes, recommended to be named release-xxx.
- Created from the develop branch
- Used for testing and minor bug fixes before release
- Merged into main and develop after testing passes
- Naming convention:
release/version-numberorrelease-version-number
# Create release branch
git checkout -b release/1.2.0 develop
# Modify version number and prepare
# Conduct testing and bug fixes
# Merge into main
git checkout main
git merge --no-ff release/1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"
# Merge back into develop
git checkout develop
git merge --no-ff release/1.2.0
# Delete branch
git branch -d release/1.2.0
3. Hotfix Branches
Hotfix branches are used for urgent bug fixes in production, recommended to be named hotfix-xxx.
- Created from the main branch
- Merged into main and develop after fixes are complete
- A fix version tag is added when merging into main
- Naming convention:
hotfix/issue-descriptionorhotfix-issue-description
# Create hotfix branch
git checkout -b hotfix/critical-bug main
# Fix bug
# ...
# Merge into main
git checkout main
git merge --no-ff hotfix/critical-bug
git tag -a v1.2.1 -m "Hotfix for critical bug"
# Merge into develop
git checkout develop
git merge --no-ff hotfix/critical-bug
# Delete branch
git branch -d hotfix/critical-bug
GitHub Flow - Simplified Workflow#
The advantage of GitHub Flow is that it is simpler than Git Flow, suitable for CI/CD (Continuous Integration / Continuous Deployment) process projects.
Basic Principles:
- The main branch is always deployable
- When developing new features, create descriptive branches from main
- Regularly commit to the local branch and push to the remote branch with the same name
- When help is needed or ready to merge, initiate a Pull Request
- After review and testing, merge into main
- Deploy immediately after merging
Workflow:
# 1. Create feature branch
git checkout -b add-user-avatar main
# 2. Develop and commit
git add .
git commit -m "feat: add user avatar upload"
# 3. Push to remote
git push origin add-user-avatar
# 4. Initiate Pull Request on GitHub
# 5. After code review approval, merge into main on GitHub
# 6. Deploy immediately after merging
GitLab Flow - Environment-Oriented Workflow#
GitLab Flow includes branches like staging and production. It combines the advantages of Git Flow and GitHub Flow, focusing more on continuous integration and continuous deployment.
Core Idea:
- Use feature branches for development
- Merge into main after Code Review
- Main serves as the primary development branch
- Create corresponding branches for different environments: staging, production
- Code progresses through environments: main → staging → production
Applicable Scenarios:
- Projects that require multi-environment deployment
- Emphasizing continuous integration and continuous deployment
- Projects that need to validate code in different environments
How to Choose a Branch Strategy#
Choose Git Flow if:
- The project has a clear version release cycle
- Multiple versions need to be maintained simultaneously
- The team size is large with clear division of labor
- There are strict requirements for code quality
Choose GitHub Flow if:
- The project requires continuous deployment
- The team size is small with smooth communication
- You want to maintain a simple workflow
- There is no need to maintain multiple production versions
Choose GitLab Flow if:
- You need to validate code in multiple environments
- Emphasizing CI/CD processes
- Environment isolation and gradual progression are required
Pull Request Best Practices#
What is a Pull Request#
A Pull Request is a notification mechanism. You have modified someone else's code and want to notify the original author of your changes, hoping they will merge your modifications; this is a Pull Request.
Basic Principles of PR#
A PR should focus on a single issue, avoiding overly large PRs. Specifically:
1. Single Responsibility
- A PR should only solve one problem or implement one feature
- Do not mix unrelated changes in the same PR
- If multiple features are needed, split them into multiple PRs
2. Control PR Size
- Ideally, the number of files changed should be less than 12 (excluding files generated by builds)
- The number of lines of code should be kept within a reasonable range (recommended not exceeding 400 lines)
- Overly large PRs are difficult to review and can easily introduce issues
3. Clear Description
The PR title and description should be clear and precise:
- Title format:
[type] + verb + noun + [adjective] + [noun] - For example:
Fix the issue where the Collapse component cannot expand,Add user avatar upload feature
How to Initiate a Pull Request#
Standard Process:
- Fork the target repository (if it is an external project)
- Clone to local
git clone https://github.com/your-username/repo-name.git
cd repo-name
- Create a feature branch
git checkout -b feature/my-feature
- Develop and commit
git add .
git commit -m "feat: add new feature"
- Push to remote
git push origin feature/my-feature
-
Create a Pull Request on GitHub
- Go to your Fork repository
- Click "Compare & pull request"
- Select the correct base branch (usually develop or main)
- Fill in the PR title and description
- Submit the Pull Request
PR Description Template#
A good PR description should include the following content:
## Change Description
Briefly describe the purpose and content of this PR.
## Change Type
- [ ] Bug Fix
- [ ] New Feature
- [ ] Code Refactor
- [ ] Documentation Update
- [ ] Performance Optimization
- [ ] Other (please specify):
## Related Issues
Closes #123
Relates #456
## Testing Description
- Test cases have been added/updated
- Local testing passed
- All CI checks passed
## Screenshots/Videos
(If there are UI changes, please provide screenshots or videos)
## Additional Notes
(Other matters that require the reviewer's attention)
Code Review Key Points#
As a PR Submitter:
- Review the code yourself before submission
- Ensure the code complies with the project's coding standards
- All tests must pass
- Respond promptly to review comments
- Do not fix unrelated issues in the PR during review
As a Code Reviewer:
- Focus on whether the code logic and design are reasonable
- Check for potential bugs or security issues
- Ensure the code complies with team standards
- Provide constructive feedback
- Respond promptly; do not let PRs linger for long periods
Common Problem Handling#
1. PR Conflicts with Main Branch
# Update main branch
git checkout main
git pull origin main
# Switch back to feature branch and rebase
git checkout feature/my-feature
git rebase main
# Resolve conflicts and continue
git add .
git rebase --continue
# Force push (because the commit history has changed)
git push origin feature/my-feature --force
2. Need to Modify an Already Submitted PR
Simply continue to commit on the original branch, and GitHub will automatically update the PR:
git add .
git commit -m "fix: address review comments"
git push origin feature/my-feature
3. Clean Up After PR is Merged
# Delete local branch
git branch -d feature/my-feature
# Delete remote branch
git push origin --delete feature/my-feature
# Update local main branch
git checkout main
git pull origin main
GitHub Project Standards#
Essential Files#
A standardized GitHub project should include the following files:
1. README.md
This is the face of the project. The README file should not only clearly state the project's purpose and functionality but also include installation guides, usage instructions, contribution guidelines, and licensing information.
Basic structure:
# Project Name
A brief description of the project
## Features
- Feature 1
- Feature 2
## Quick Start
### Environment Requirements
- Node.js >= 14
- npm >= 6
### Installation
npm install
### Usage
npm start
## Documentation
For detailed documentation, please refer to [Documentation Directory](./docs)
## Contribution Guidelines
Please refer to [CONTRIBUTING.md](./CONTRIBUTING.md)
## License
[MIT](./LICENSE)
2. .gitignore
Every repository must use a .gitignore file to ignore predefined files and directories.
It is recommended to use gitignore.io to generate a .gitignore file tailored to your tech stack.
3. LICENSE
Choose an appropriate open-source license:
- MIT - The most permissive, allows commercial use
- Apache 2.0 - Provides patent protection
- GPL - Requires derivative works to also be open source
- BSD - Similar to MIT, but with some restrictions
4. CONTRIBUTING.md
Instructions on how to contribute to the project:
- How to submit Issues
- How to submit Pull Requests
- Code standards requirements
- Development environment setup
- Testing requirements
5. CHANGELOG.md
Records the version change history of the project:
# Changelog
## [1.2.0] - 2024-12-06
### Added
- Added user avatar upload feature
### Fixed
- Fixed styling issue on the login page
### Changed
- Optimized database query performance
## [1.1.0] - 2024-11-15
...
Other Best Practices#
1. Protect the Main Branch
Any content in the main branch should be deployable, so code should not be submitted directly to the default branch.
In the GitHub repository settings:
- Settings → Branches → Branch protection rules
- Add rules to protect the main branch
- Require PR review before merging
- Require CI checks to pass
- Prohibit force pushes
2. Use Issue Templates
Create a .github/ISSUE_TEMPLATE directory and add different types of Issue templates:
- bug_report.md - Bug report template
- feature_request.md - Feature request template
3. Configure Code Owners
Using the codeowners feature allows you to define which teams and individuals are automatically selected as reviewers for the repository.
Create a .github/CODEOWNERS file:
# Default for everyone
* @team-lead
# Frontend code
/src/frontend/ @frontend-team
# Backend code
/src/backend/ @backend-team
# Documentation
/docs/ @doc-team
4. Archive Repositories No Longer Maintained
For repositories that are no longer actively developed, the best practice is to archive them and set them to read-only mode.
Select "Archive this repository" in the repository settings.
5. Avoid Committing Sensitive Information
Never commit any secrets to the code. Use environment variables injected from secure storage.
Manage sensitive information using environment variables or configuration files:
- Database passwords
- API keys
- Private tokens
- SSH keys
Common Questions and Solutions#
What to Do If You Committed the Wrong Commit?#
Modify the Most Recent Commit:
# Modify commit message
git commit --amend -m "New commit message"
# Add forgotten files
git add forgotten_file
git commit --amend --no-edit
Revert a Pushed Commit:
- For public branches, prefer using git revert; reset --hard + --force should only be used for personal branches or very special scenarios.
# Soft reset (keep changes)
git reset --soft HEAD~1
git push origin branch-name --force
# Hard reset (discard changes)
# ⚠ Only for feature branches you control, do not do this on shared main/develop
git reset --hard HEAD~1
git push origin branch-name --force
How to Merge Multiple Commits?#
Use interactive rebase:
# Merge the last 3 commits
git rebase -i HEAD~3
# In the editor, change pick to squash (or s) for the commits you want to merge
# Save and exit, then edit the merged commit message
How to Resolve Branch Conflicts?#
# 1. Update main branch
git checkout main
git pull origin main
# 2. Switch back to feature branch
git checkout feature-branch
# 3. Merge or rebase
git merge main
# or
git rebase main
# 4. Resolve conflicts
# Edit conflict files, remove conflict markers
# 5. Mark as resolved
git add .
# 6. Continue merge or rebase
git merge --continue
# or
git rebase --continue
# 7. Push
git push origin feature-branch --force-with-lease
How to Configure Git User Information?#
Ensure your Git client is configured with the correct email address and linked to your GitHub user.
# Global configuration
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
# Project-specific configuration
git config user.name "Your Name"
git config user.email "[email protected]"
# View configuration
git config --list
In Conclusion#
The usage specifications of GitHub may seem cumbersome, but they are actually an important foundation for ensuring project quality and team collaboration efficiency. From my experience, whether a team has clear Git specifications is directly reflected in the maintainability of the project.
When first implementing these specifications, it may feel like it increases the workload, but once you get used to it, you will find that these specifications greatly reduce the maintenance costs later on. Especially when you need to trace back to the introduction time of a bug or quickly understand the implementation logic of a feature, standardized Commit Messages and clear branch history will make your work much easier.
My suggestions are:
- Start Small - Begin with standardizing Commit Messages, gradually introducing other specifications
- Use Tools - Utilize tools like Commitizen and Commitlint for automated checks
- Team Consensus - Specifications should be agreed upon by all members, not enforced
- Continuous Optimization - Adjust specifications based on the team's actual situation, no need to follow them rigidly
- Lead by Example - As a leader or senior member, you should first adhere to the specifications
Remember, the purpose of specifications is to enhance efficiency, not to create obstacles. Choose specifications that suit your team and stick to them, and you will see significant improvements in code quality and collaboration efficiency.
If you encounter problems in practice or have better practical experiences, feel free to discuss in the comments section.
Related Links#
- Angular Commit Message Specification
- Conventional Commits Specification
- Git Flow Original Article
- GitHub Flow Introduction
- GitHub Official Documentation
- Pro Git Chinese Version
- Commitizen Tool
- Commitlint Tool
This article is synchronized by Mix Space to xLog. The original link is https://blog.astrasolis.top/posts/tutorial/github-standard