Git Basics: diff commit and merge branches


Use git diff show the difference between commits.

git co master
git diff 0da94be..59ff30c > /tmp/my.patch
# Checkout new branch: (this will not reset your work)
git co branches-dev git apply /tmp/my.patch

Diff a single file by different commits:

git diff 5bb72a8 HEAD -- twentytwelve/style.cs

Compare files from two different branches:

# You can do this: `git diff branch1:file branch2:file`
git diff master:twentytwelve/style.css branche-dev:twentytwelve/style.css

Git – Create a branch with current changes

Just use:

git checkout -b topic/newbranch

Any uncommitted work will be taken along to the new branch.

GIT Merge

Merge some (not all) files from one Git branch to another.

As it turns out, we’re trying too hard. Our good friend git checkout is the right tool for the job.

git checkout <branch> <paths>...

We can simply give git checkout the name of the feature branch and the paths to the specific files that we want to add to our master branch.

# merge a single commit from another branch
git cherry-pick <commit_sha1>

# merge without auto commit
git merge v1.0 --no-commit --no-ff

Syncing a fork

Merge the changes from upstream/master into your local master branch. This brings your fork’s master branch into sync with the upstream repository, without losing your local changes.
We can configure git to sync your fork with the original repository git remote add upstream <ORIGINAL_REPOSITORY.git>

git merge upstream/master
# Updating a422352..5fdff0f
# Fast-forward
#  README                    |    9 -------
#                 |    7 ++++++
#  2 files changed, 7 insertions(+), 9 deletions(-)
#  delete mode 100644 README
#  create mode 100644

Git merge “accept theirs” or “accept mine” options

git checkout --ours -- <filename>
git checkout --theirs -- <filename>

Resolving the conflict

Just modify the files conflicting. You would need to call git add to mark the conflict as resolved:

$ git add file_with_resolved_conflicts

This will also add the file to the index. After you repeat the same process for other conflicting files, you can safely commit your changes using git commit command:

git commit -m 'Merged with branch src-branch and resolved the conflicts.'


Helper commands

  • use git difftool to manally merge files: git config merge.tool vimdiff
  • undo current changess: git reset --hard origin/master

Reference Links

Adding And Removing Remote Branches – Git Branch