← Writing

git checkout <sha>^ -- <path> removes one feature without rewriting history

How to build a clean test branch containing four merged features but not the fifth — restore a path to its pre-commit state instead of force-pushing or reverting across a shared branch.

The situation: a tester needed four features tested — credit notes, bulk quotations, category hierarchy, import sheets — but a fifth, unfinished feature had already been merged into the same shared dev branch. The tester needed a build without it.

We walked through the usual options and rejected each: force-pushing dev to before the merge rewrites shared history under everyone else’s feet; reverting on dev pollutes the branch with revert commits that will need re-reverting when the feature is actually ready; cherry-picking the four wanted features onto a fresh branch means untangling every commit they’re spread across.

The tool that made it clean:

git checkout <sha>^ -- <path>

This restores <path> to exactly how it looked before commit <sha> — in the current working tree, as a normal staged change. So the recipe was:

  1. Branch off dev at its current state.
  2. Find the commit(s) that introduced the unwanted feature’s directory.
  3. git checkout <sha>^ -- <feature-dir> to snap that directory back to its pre-feature state (for files that didn’t exist before, remove them).
  4. Commit the result on the new branch and open a single PR for the test build.

Shared history is untouched — dev keeps its true record, the unfinished feature stays merged there, and the test branch is an ordinary branch containing an ordinary commit that happens to subtract one feature. When the feature is finished, nothing needs undoing anywhere.

The general lesson: git checkout <ref> -- <path> (and its modern spelling git restore --source=<ref> -- <path>) is surgical in a way branch-level commands aren’t. Most “we need history without X” problems are actually “we need a tree without X” problems, and trees are cheap.

← All writing Book a call →
Book a call → WhatsApp