Thursday, 27 December 2018

GIT: Stashing changes in Git


22.1. The git stash command
Git provides the git stash command which allows you to record the current state of the working directory and the staging area and to revert to the last committed revision.
This allows you to pull in the latest changes or to develop an urgent fix. Afterwards you can restore the stashed changes, which will reapply the changes to the current version of the source code.

22.2. When to use git stash

In general using the stash command should be the exception in using Git. Typically, you would create new branches for new features and switch between branches. You can also commit frequently in your local Git repository and use interactive rebase to combine these commits later before pushing them to another Git repository.
Even if you prefer not to use branches, you can avoid using the git stash command. In this case you commit the changes you want to put aside and amend the commit with the next commit. If you use the approach of creating a commit, you typically put a marker in the commit message to mark it as a draft, e.g., "[DRAFT] implement feature x".

22.3. Example: Using the git stash command

The following commands will save a stash and reapply them after some changes.
# create a stash with uncommitted changes
git stash

# do changes to the source, e.g., by pulling
# new changes from a remote repo

# afterwards, re-apply the stashed changes
# and delete the stash from the list of stashes
git stash pop
It is also possible to keep a list of stashes.
# create a stash with uncommitted changes
git stash save

# see the list of available stashes
git stash list
# result might be something like:
stash@{0}: WIP on master: 273e4a0 Resize issue in Dialog
stash@{1}: WIP on master: 273e4b0 Silly typo in Classname
stash@{2}: WIP on master: 273e4c0 Silly typo in Javadoc

# you can use the ID to apply a stash
git stash apply stash@{0}

# or apply the latest stash and delete it afterwards
git stash pop

# you can also remove a stashed change
# without applying it
git stash drop stash@{0}

# or delete all stashes
git stash clear

22.4. Create a branch from a stash

You can also create a branch for your stash if you want to continue to work on the stashed changes in a branch. This can be done with the following command.
# create a new branch from your stack and
# switch to it
git stash branch newbranchforstash

0 comments:

Post a Comment