Git Branching Strategy
A branching strategy is the set of rules which a team follows for creating branches and merging them. Without rules, a big team can mess the code quickly. Here are the most common ones.
1. Feature branch workflow
The main branch always has working code. For every task (feature or bug fix), a developer creates a new branch from main, works there, and opens a pull request (or merge request). After review, the branch is merged to main and deleted. This is the simplest and most popular workflow.
2. Git Flow
A more detailed model with long living branches.
| Branch | Purpose |
|---|---|
main | Only released and stable code, tagged with versions |
develop | Integration branch for the next release |
feature/* | New features, created from develop |
release/* | Preparing a release, only bug fixes |
hotfix/* | Urgent fixes for production, created from main |
It fits software with planned releases. It is heavy for small teams or for websites which deploy many times a day.
3. Trunk based development
Everybody works on one main branch (the trunk) using very short branches (a day or less) or directly on it. Features that are not ready are hidden with feature flags. It needs good automatic tests, and it is common in big companies with continuous delivery.
Feature branch workflow step by step
$ git switch -c feature/contact-page
Switched to a new branch 'feature/contact-page'
$ echo "contact" > contact.html
$ git add .
$ git commit -q -m "Add contact page"
$ git push -u origin feature/contact-page
To /home/robin/team/server.git
* [new branch] feature/contact-page -> feature/contact-page
branch 'feature/contact-page' set up to track 'origin/feature/contact-page'.
At this point you open a pull request on GitHub or GitLab, and your team reviews it. After the approval, the merge button does the following (we do it by hand here):
$ git switch main
Switched to branch 'main'
Your branch is up to date with 'origin/main'.
$ git merge –no-ff feature/contact-page -m "Merge pull request: contact page"
Merge made by the 'ort' strategy.
contact.html | 1 +
1 file changed, 1 insertion(+)
create mode 100644 contact.html
$ git push
To /home/robin/team/server.git
72ef56d..5bafb52 main -> main
$ git branch -d feature/contact-page
Deleted branch feature/contact-page (was 76cbaa3).
$ git push origin –delete feature/contact-page
To /home/robin/team/server.git
– [deleted] feature/contact-page
$ git branch -a
* main
remotes/origin/main
Good rules for any team
- Keep
mainalways working. Do not commit to it directly. - Make small branches and merge them often.
- Use clear branch names, like
feature/loginorfix/cart-total. - Review every change with a pull request.
- Delete the branch after it is merged.
- Use automatic tests (CI) on every pull request.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |