Git Branches: Managing Parallel Development
Git branches are essential for managing parallel development and keeping your main codebase stable. They allow you to work on new features or bug fixes without affecting the main branch.
Basic Branch Commands:
git branch
: Lists all branches in your repository. A*
indicates the currently active branch.git switch -c <branch-name>
: Creates a new branch named<branch-name>
and switches to it. This is the preferred method for creating and switching branches. Older examples may usegit checkout -b <branch-name>
.git switch <branch-name>
: Switches to an existing branch named<branch-name>
. This is the preferred method for switching between branches. Older examples may usegit checkout <branch-name>
.git merge <branch-name>
: Merges the specified branch into the currently active branch.git branch -d <branch-name>
: Deletes the branch named<branch-name>
. This is safe only if the branch has been merged.git branch -D <branch-name>
: Forcefully deletes the branch named<branch-name>
, even if it hasn’t been merged. Use with caution.
Workflow Example:
-
Create a Branch: Start by creating a new branch from your main branch (usually
main
ormaster
). This creates a copy of your project’s current state. -
Make Changes: Make all necessary changes within the new branch.
-
Commit Changes: Commit your changes as you make them to track your progress.
-
Switch Back to Main: Once you have finished your changes and committed them, switch back to the main branch.
-
Merge the Branch: Merge the feature branch into the main branch. This incorporates your changes into the main codebase.
-
Delete the Branch: The feature branch is no longer needed, so you can delete it.
Git Flow
This is a common branching strategy
- Main/Master branch: Holds the production-ready code. Changes are generally merged into this branch only after rigorous testing.
- Feature Branches: Short-lived branches to develop a specific new feature.
- Bug Fix Branches: Short-lived branches to fix a specific bug.
Collaboration: In collaborative projects, it’s crucial to work on separate branches to avoid conflicts and keep the main branch stable. Each developer should create their own branch for feature development or bug fixes, merge their changes into the main branch when ready, and then delete their feature or bug-fix branch.
This workflow helps maintain a clean and organized project history, simplifies collaboration, and reduces the risk of introducing errors into the main codebase.