Git Intermediate: Undo, Collaborate and Resolve
Stash, Tags and Useful Commands
In this lesson you will
- Shelve and restore unfinished work with git stash
- Create tags for releases
- Investigate history with log, diff and blame
Introduction
This lesson collects the everyday tools that make Git pleasant: parking half-finished work, labelling important points in history, and finding out who changed what and why.
Stash: park work for later
Imagine you are halfway through a change when you must switch branches to fix something urgent. Your edits are not ready to commit. Stash puts them on a shelf:
Terminal
git stash # save changes and clean your working folder
git switch main # do the urgent work
git switch feature
git stash pop # bring the changes backUseful variations:
git stash -ualso stashes new, untracked files.git stash listshows what is on the shelf.git stash applyrestores a stash but keeps it on the shelf.git stash dropremoves one.
Quick quiz
What does git stash pop do?
Tags: label a moment in history
A tag is a permanent name for a specific commit, often a release.
Terminal
git tag -a v1.0.0 -m "First release"
git tag # list tags
git push origin v1.0.0 # tags are not pushed automaticallyUse clear numbers such as semantic versioning: MAJOR.MINOR.PATCH. Increase the patch for bug fixes, the minor number for new features that do not break anything, and the major number for breaking changes.
.gitignore done well
List files that should never be tracked:
node_modules/
.env
*.log
dist/If a file is already tracked, adding it to .gitignore is not enough. Stop tracking it with git rm --cached file. Never commit secrets such as passwords or keys.
Investigate history
Terminal
git log --oneline --graph --all # a map of all branches
git log -p -- notes.txt # every change to one file
git log --author="Sam" --since="2 weeks ago"
git show a1b2c3d # what one commit changed
git diff main..feature # differences between two branches
git blame notes.txt # who last changed each linegit blame is not about blame. It helps you find the commit, and then its message, that explains why a line is the way it is.
Helpful settings
Terminal
git config --global init.defaultBranch main
git config --global pull.rebase false
git config --global alias.st statusAn alias turns git st into git status. Choose settings that match your team's habits.
Try it yourself
In a practice repository, edit a file without committing, stash it, check that the file is clean, then pop the stash. Then tag the latest commit v0.1.0 and list the tags.
Summary
git stashshelves unfinished work, andpopbrings it back.- Annotated tags mark releases, and tags must be pushed separately.
log,show,diffandblamehelp you understand how code got to its current state.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading