Mémo Git usage (part II)

Here, you will find some useful (and a little advanced) use cases with git.

The Cherry-pick

TODO …..

Get the SHA1 of the last commit :

git rev-parse HEAD

Stash a part of code

You might have made some change, and then you need to switch your branch but you don’t want to commit your current work : what to do ? Stash is the answer ! Git stash is a stack where you can pop and get your uncommited code.

# put your work at the index 0 of the stack
git stash

# same, but with a name/label
git stash save "the name i want to give"

# will list the actual state of the stack
git stash list

# apply the code save at the index 2 of the stack
git stash apply stash@{2}

# delete the index 1 of the stack
git stash drop stash@{1}

For the 2 last (apply and drop), if no index is specified, Git will take the more recent (the index 0), so be carefull.

There is no git unapply, but a stash can be unmade with the following command, but the stash must still be in the stack !

git stash show -p stash@{2} | git apply -R

Tutorial in french : http://git-scm.com/book/fr/Utilitaires-Git-Le-remisage

Amend your last commit

You have committed something but forget a line or a file in the commit. Rather than make a second commit fixing the first one, you can amend the last commit (it doesn’t work if other commits arrived after the bad one). Your local branch must be at the last commit, plus the modifications you forget.

# see the modified files, not commited
git status
# add your forgotten file to the staging
git add myfile.py
# amend the commit and add the file in a new one
git commit --amend

The commit –amend will take all the changes of the last commit, remove the commit, create another one mixing the changes of the removed one and the changes of the files you just add. These modifications are committed in a new commit (new id).

Your default editor open to ask you if you want to change the commit message. Edit or not, save and exit.

Then, you must push force to your repo. –force, because you have a commit to remove. This must be use VERY CARREFULLY.

git push remote-repo branch-name --force

Without the –force, you will get an error saying that your branch have diverged too much.



@see : https://www.atlassian.com/git/tutorial/