Saturday 26 September 2015

Part 4 - git skim : Rewriting History (Amend, Rebase)

git commit --amend:

Way to fix up the most recent commit. You might have forget adding some file to commit or adding some important point to commit message.
Amend replaces the most recent commit entirely. Previous commit is removed from project history. (Thats why, it is not recommended for public commits).

# Edit file1.sh and file2.sh
git add file1.sh
git commit 
# Oops. forgot to add file2.sh
git add file2.sh
git commit --amend --no-edit
--no-edit flag will commit without opening editor to modify commit message.

git rebase:

Rebase is process of moving your changes on NEW base commit. Your changes might be based upon some "older"  commit. 
Consider following example
  1. You clone repository when it was on commit2.
  2. You start adding few directories and do a local commit.
  3. Meanwhile, someone pushed changes to central repository.
  4. Before pushing your changes to central repository, you would like to base your changes on commit3 rather than commit2.
                    
git log will show you follow status
git log --oneline
8f00c3  local commit
7a4567  commit2
7a4567  commit1
You need to give following commands to move your changes to latest commit.
# Bring all changes to your local machine. In this case, commit3.
git fetch             
# Base your latest commit on tip of the origin/master i.e commit3.
git rebase origin/master   
On issuing "git log --oneline" command, you will see follow
a43981  local commit
7a4567  commit3
7a4567  commit2
7a4567  commit1

Rebasing Branch: 
You can rebase branch as well. Suppose you have two branches "master" and "feature" with following state


Your feature branch is based upon commit2 of master branch. You can rebase it to latest commit of master. You have to do below things to do so
git rebase master

You will have following state after rebase

Its important to note that rebase will maintain a linear project history.
For further reading, please follow link.

NOTE:
merge and rebase are two main ways to integrate changes from one branch to other. We will learn about merge later. Uptill then, just keep in mind that while rebase maintains linear project history, "merge" does NOT maintain a linear history.


No comments:

Post a Comment