Occasionally, you may find yourself needing to extract just one commit from a branch or pluck a specific file from a changeset. In this tip, we’ll explore some methods to accomplish this task.
The common scenario is when you’re examining another branch or someone’s project fork, but you only want to incorporate one or a few specific changesets into your repository. Fortunately, Git offers several tools to simplify this process. Let’s consider the following scenario: there has been extensive development on the “jekyll” repository, but you’re interested in bringing in only one particular commit.
Once you’ve identified the commit SHA, you have several options:
Use git cherry-pick to select and apply the commit, preserving its metadata.
Generate a patch with git format-patch and apply it using git am.
Apply the changes directly to your working directory using git apply.
Merge the commit directly into your branch, preserving the original commit history (assuming no conflicts arise).
Let’s walk through each method. Suppose the commit SHA we’re interested in is “b50788b”.
$ git cherry-pick b50788b
This command cherry-picks the specified commit, creating a new commit with its changes.
$ git format-patch -1 b50788b
$ git am 0001-First-pass-at-rake-task.patch
Here, we create a patch for the commit using format-patch and then apply it using git am.
$ git apply 0001-First-pass-at-rake-task.patch
Using git apply, we directly apply the changes from the patch to our working directory.
$ git merge b50788b
Alternatively, we can merge the commit directly into our branch.
Each method has its advantages and use cases. Cherry-picking and merging preserve the commit history, while applying patches directly to the working directory offers flexibility for further editing.
If you encounter issues, you can revert to the previous state using git reset –hard HEAD^ or by reverting specific files. Additionally, you can explore the reflog for further troubleshooting.
Feel free to share your preferred methods or additional tips in the comments!