# Git: stashing

Stashing is a great tool for making work with branches a bit smoother.

## Rationale

**Scenario:** you're building a new feature in a dedicated branch, the feature
is far from being ready, all good under the sun. But your blissful development
peace is broken by gentle knock to shoulder by quality assurance, they have come
up with a critical bug that needs your attention, _urgently_. Essentially, what
you want is: switch to master, fix the bug, deploy, and continue with your
feature. But, **you can't, because you got a half assed feature in the open
branch**, and you’d have to commit the changes before switching branches, but
forcefully committing unfinished feature is not really to your liking. That's
when you would **stash the made changes**, safely switch branches, switch back
to feature branch, and revive the stash.

In a nutshell:

- Dirty tree in a feature branch
- Stash changes
- Checkout another branch
- Hack hack hack... and commit
- Checkout feature branch
- Revive the stash

## Stashing

The status of your project might look something like this:

```shell
$ git status
On branch new-feature-thingy
Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   my-project/dist/css/style.css
    modified:   my-project/src/sass/base/_constants.scss
    modified:   my-project/src/sass/elements/_typo.scss

no changes added to commit (use "git add" and/or "git commit -a")
```

Now if `$ git stash` is applied all the changes are stashed into a secure area:

```shell
$ git stash
Saved working directory and index state WIP on new-security-page: dc7a6dc New new security page
HEAD is now at dc7a6dc New new feature thingy
```

Status shows a clean tree:

```shell
$ git status
# On branch master
nothing to commit, working directory clean
```

## Getting the stash back

To get the most recent stash back, `apply` it:

```shell
$ git stash apply
```

Even better, `pop` it back, `pop` will apply the latest stash and then destroy
it:

```shell
$ git stash pop
```

To list all stashes:

```shell
$ git stash list
stash@{0}: WIP on new-feature-thingy: dc7a6dc New new security page
stash@{1}: WIP on master: c5d658f Build JS
stash@{2}: WIP on new-feature-thingy: 654d7aa Fix a thing
```

To get an older stash back, use the stash name as parameter for the apply
command:

```shell
$ git stash apply stash@{2}
```

## Getting rid of old stashes

Refer a stash name in the `git stash drop` command:

```shell
$ git stash drop stash@{0}
Dropped stash@{0} (79d291f180ac9be18fdce2733ee7635bde6120ca)
```
