Git Interview Question 8: Cherry Pick Wrong Branch
Git Interview Questions · Test 1 · question 8 of 10
You meant to commit a bug fix to your existing feature/login branch. Instead you committed it to your local main, and you have not pushed. feature/login branched from main a week ago, and main has since received many unrelated commits. Your working tree is clean.
You want only the fix commit on feature/login, and you want local main to end up exactly as it was before the mistake. Which sequence does this?
Show answer and explanation
Answer:
git cherry-pick <commit> applies the change that one commit introduces and records it as a new commit on the current branch. While main still points at the misplaced fix, git cherry-pick main copies just that one commit onto feature/login. Then, back on main, git reset --hard HEAD~1 moves main back one commit. Nothing was pushed and the working tree is clean, so this rewrites no shared history and loses no uncommitted work. The fix now exists only on feature/login.
Option A does get the fix onto feature/login (after the revert, main~1 is the fix commit), but main keeps two extra commits: the fix and its revert. Local main isn't back to how it was before the mistake, which the stem requires.
Option B brings the fix and also every unrelated commit main gained in the past week into feature/login. The stem wants only the fix.
Option D has the same problem as B. Rebasing feature/login onto main puts it on top of all of main's new commits, including the fix and everything else.
References: git-cherry-pick; git-reset