Git Branching and Merging
In this post, let’s go through simple Branching and Merging workflow in the GIT. In our day by day work we always take some task or hotfix and work on it. At this situation, we would do the followings:
- Create a new branch from master.
- Do some updates in that new branch for the new task.
- After testing completed, merge the code for task or hotfix whatever you do with the master branch, and push to cloud.
git checkout -b [Branch Name]
To create a new branch and switch to it at the same time, you can run the git checkout command with the -b switch
$ git checkout -b hotfix
After creating the new branch you do some updated and need to commit those updated, for that
$ git add index.html $ git commit -m "Removed the unwanted entries" $ git push
When all the testing has been completed and the issue got fixed means, you have to merge this hotfix branch to master.
You have to first checkout to master branch.
$ git checkout master $ git merge hotfix $ git branch -d hotfix
In this below image, Branch Task123 is created from the master branch with the commit C3, After that there is changes in Master branch. In this case, If need code changes that are newly added to Master branch, you can merge Master branch into the Task123
$ git merge Master
If you changed the same part of the same file differently in the two branches you’re merging, Git won’t be able to merge them cleanly. If your fix for Task123 modified the same part of a file as the Master branch, you’ll get a merge conflict that looks something like this:
$ git merge Master Auto-merging index.html CONFLICT (content): Merge conflict in index.html Automatic merge failed; fix conflicts and then commit the result.
In this scenario, Git created a new merge commit. Git adds standard conflict-resolution markers to the files that have conflicts, so you can open them manually and resolve those conflicts.
<<<<<<< HEAD:index.html <div id="footer">Visit: https://poopcode.com/ </div> ======= <div id="footer"> please do visit us https://poopcode.com/ </div> >>>>>>> iss53:index.html
This differentiate the version in two branch. HEAD(your master branch, because that was what you had checked out when you ran your merge command) is the top part of that block (everything above the =======), while the version in your Task123 branch looks like everything in the bottom part.
In order to resolve the conflict manually, you have to either choose one side or the other or merge the contents yourself. This resolution has a little of each section, and the <<<<<<<, =======, and >>>>>>> lines have been completely removed.
If you’re happy with that, and you verify that everything that had conflicts has been staged, you can stage the file to mark as resolved, and type git commit to finalize the merge commit.