2

I have a script which cherry-picks a commit while adding more information to the comment. Today I run git cherry-pick and then git commit --amend to modify the commit message.

I can see there is the -e flag, but it seems to be interactive. Is there a way to run git cherry-pick with a message non interactively?

mark
  • 59,016
  • 79
  • 296
  • 580

2 Answers2

4

I decided to invoke git cherry-pick with the --no-commit flag. Then I commit explicitly with the new message. Currently I do not see a better solution.

mark
  • 59,016
  • 79
  • 296
  • 580
0

I found another solution here, inspired by this article The high-level idea is to:

  1. Create a prepare-commit-msg git hook
  2. In this hook, do whatever you want to edit the message. I used a bash script with sed, but you can use a python script or really any other executable.
  3. (optional) If you don't want this to happen on every commit, remove the git hook when you're done

My specific goal was to update cherry-pick messages to say something like (cherry picked from commit abcd by roryabraham) rather than just (cherry picked from commit abcd). I also couldn't adjust the commit actor rather than the message for reasons that are out-of-scope to explain here.

My solution looks like this:

# Create the git hook
echo '#!/bin/bash' >> .git/hooks/prepare-commit-msg
# shellcheck disable=SC2016
echo 'sed -i "" -E "s/(\(cherry picked from commit .*[^)])/\1 by roryabraham/" $1' >> .git/hooks/prepare-commit-msg

# Make the hook executable
chmod u+x .git/hooks/prepare-commit-msg

# Execute the cherry-pick
git cherry-pick -x --mainline 1 --strategy=recursive -Xtheirs abcd

# Cleanup the hook
rm .git/hooks/prepare-commit-msg

Explaining the sed command:

  • -i flag tells sed to "edit the file inline"
  • -E flag means "use extended regex"
  • The regex looks for (cherry picked by commit abcd and wraps the result in a capture group
  • The second half of the sed uses the capture group (\1) and appends by roryabraham
  • $1 – the first argument to the prepare-commit-msg hook is the filepath of the text file containing the commit message
Rory Abraham
  • 116
  • 1
  • 4