I ran into a situation recently where I wanted to perform a git cherry-pick operation, but I only wanted to pull specific files from the commit. The reasons for this itself aren’t so important – I just wanted to make a note for myself and others wrestling with this.
The general approach is to use git show to generate a diff involving the desired files, and then treat that as a patch to apply applied.
The general format is:
git show [sha] -- [file1 ... filen] | git apply --index -
The --index argument on git apply will essentially make the changes to your working files and then perform a git add so that they are ready to commit. If you leave off --index, you’ll simply need to perform a git add when you’re ready to commit.
For example:
git show 547f82a7a5 -- src/vendor-driver-refactored/sensirion_common.c | git apply --index -
Now you need to commit. You can write a new commit at this point. But you can also reuse the commit message, authorship info, and timestamp from the other commit with the -C or -c flags using git commit. The “big C” variant will use the commit information directly, with the “little c” variant will open the editor so you can adjust the commit message if needed.
git commit -c 547f82a7a5
# opens an editor
-C <commit>--reuse-message=<commit>Take an existing commit object, and reuse the log message and the authorship information (including the timestamp) when creating the commit.
-c <commit>
--reedit-message=<commit>
Like -C, but with -c the editor is invoked, so that the user can further edit the commit message.
References
- git (Field Atlas)
- git commit documentation
