Video in progress

Strong Middle 🌿 Git

You need to restore a single file to its state on another branch or in an old commit, without touching the other files. How do you do it?

git restore --source=<commit> -- <file> brings the file to its state in that commit, by default only in the working tree; with --staged --worktree the index is updated too. If you only need to look at it, use git show <commit>:<path>.

📖 Answer

# make pom.xml the same as on main
git restore --source=main -- pom.xml

# the state three commits ago, including the index
git restore --source=HEAD~3 --staged --worktree -- src/main/resources/application.yml

# view it, or save it elsewhere, without writing to the working tree
git show v2.3.0:src/main/resources/application.yml > /tmp/app-2.3.yml

The old way, git checkout main -- pom.xml, also works, but with one difference: it writes the file into the index right away too. restore by default writes only to disk, so you look at it with git diff and decide afterwards.

Bringing back a deleted file works the same way:

git log --oneline --diff-filter=D -- src/main/java/uz/shop/LegacyExporter.java
# 7c1d2e3 Eski eksport olib tashlandi
git restore --source=7c1d2e3^ -- src/main/java/uz/shop/LegacyExporter.java

The ^ matters: the file is not in the commit that deleted it, but it is in that commit's parent.

If you need to pick only some pieces, git restore -p --source=main -- pom.xml asks about each chunk of change.

In git show, the path is written relative to the repo root. If you are in a subfolder and want to write it relative to the current folder, use git show main:./application.yml.