You've mastered the basics of Git and GitHub: creating repositories, making commits, and pushing your changes. Now, let's dive into some more advanced features that will elevate your development workflow and collaboration skills. Understanding branching and merging strategies is fundamental to working effectively in teams and managing complex projects. Think of branches as parallel universes for your code. They allow you to work on new features, fix bugs, or experiment with ideas without affecting the main, stable version of your project.
The main (or master in older repositories) branch is typically where your stable, production-ready code resides. When you want to introduce new functionality or fix a bug, the best practice is to create a new branch from main. This isolates your work, preventing potential conflicts and ensuring that main remains clean and deployable.
git checkout main
git pull
git checkout -b my-new-featureThe command git checkout -b my-new-feature does two things: it creates a new branch named my-new-feature and immediately switches you to that branch. Now, any commits you make will be on this new branch, leaving main untouched.
Once you've completed your work on the feature branch and tested it thoroughly, you'll want to integrate those changes back into the main branch. This process is called merging. Merging combines the commit history from your feature branch into the target branch.
git checkout main
git pull
git merge my-new-featureHere, we first switch back to the main branch and pull any recent changes to ensure we're merging into the most up-to-date version. Then, git merge my-new-feature brings the changes from your feature branch into main. If there are no conflicting changes, this is a straightforward process. However, if changes in main overlap with changes in your feature branch, you'll encounter a merge conflict, which Git will prompt you to resolve manually.
graph TD
A[main branch] --> B(Commit 1 on main)
B --> C(Commit 2 on main)
C --> D{Create feature branch}
D --> E[feature branch]
E --> F(Commit 1 on feature)
F --> G(Commit 2 on feature)
G --> H{Switch to main}
H --> I{Merge feature into main}
I --> J[main branch with feature integrated]