Yeswanth Madasu

Day 10/13 of Git 101 Series

STASH, RESTORE, CLEAN


Concept Explanation

Stash temporarily saves uncommitted changes so you can switch branches safely.
It captures both the index and working tree.

Restore resets file content from HEAD or a specific revision and can also unstage changes.

Clean removes untracked files and directories, keeping your working tree tidy.

Together, they help manage incomplete work and cleanup tasks.


Commands

git stash push -m "msg" # save staged + unstaged work
git stash list
git stash apply / pop
git stash drop / clear

git restore # restore from HEAD
git restore --staged # unstage
git restore --source=

git clean -n # preview deletions
git clean -f # delete untracked files
git clean -fd # delete untracked dirs
git clean -fx # delete untracked + ignored


Strong Example

You are midway through writing a new search function, but a hotfix is needed on main.

git status
git stash push -m "WIP search"
git checkout main

fix bug + commit

git checkout feature
git stash pop

Your WIP changes return atop the updated base.
If conflicts occur, Git prompts you to resolve them before completing the stash apply/pop.


Real World Use Case

A backend engineer working on API changes is interrupted by a production issue.
Instead of committing half-finished work or losing it, they stash it.
They switch to main, fix the bug, return to their feature branch, and reapply the stash.
Clean helps remove temporary build artifacts used by build tools or test runners, preventing clutter in commits.


Underhood Explanation

A stash is actually a series of commits stored under refs/stash:

With -u or -a, Git adds extra trees for untracked or ignored files.

Applying a stash behaves like cherry-picking those diffs onto the working directory.

Restore is a porcelain wrapper over low-level operations (checkout-index, read-tree) to bring content from index or commits into your working tree.

Clean scans for untracked files using Git’s index and deletes them directly from your filesystem.