Branches
Understand what is Git branches.
What is Git Branch?
Default branch will be created either master or main depends on the settings.
Branch is an independent line of development work. As an example, if you are working on a large project and you want to add a new feature, you can't commit all your changes straight away and push them to the default branch, since that would make the commit history pretty messy and it would be hard to tell which changes were made.
Regardless of how big or small your changes are, always create a branch and work on it to encapsulate your changes.
All new commits you make to that branch will be recorded in that branch as well.
Git branch commands
Create branch
Checkout/Switch branch
Remember that the HEAD is Git's way of referring to the current snapshot
Once we have created the branch, we have to switch or checkout to that branch.
- the default branch can still proceed with the commits even though we have checkout to develop branch
Merge branch (Fast-forward)
The git merge
command will combine two branches, so it will consolidate multiple commit sequences into a single history.
Here is the scenario, since develop branch came directly from main and no other changes had been made to main, so it can fast-forward.
Merge conflicts
A merge conflict will arise when two developers have changed the same lines in a file. Because of that, Git does not know which one is correct.
To resolve merge conflict, you have to open the file to make necessary changes. Then, use git add
command to stage the new merged commit and the final step is to merge your latest commits into it.
List branches
Delete branch
Rename branch
Create remote branches and push
Before we want to push our local branches to our remote repository. The remote repository needs to be added to our local project if it hasn't already been. Normally the remote name is origin, but you can change it.
Once you initialize, you have access to this remote repository. So you can push your local branch to the remote at remote name.
- The reason why we need to set-upstream from local to remote is because it makes our jobs easier when we want to perform push and pull operation. With an upstream branch set, you can simply
git pull
orgit push
instead ofgit push origin <branch>
An upstream is just a remote tracking branch that is associated with your local branch. Do take note that, each branch only has one upstream.
You can use the following command:
- if the remote branch already exists or
- you want to change upstream branch