Git – Cherry Picking Specific Commit Ranges

Something a little different today.. Recently while doing some kernel work, I came across the situation when I had to cherry-pick all the commits made by a specific author in a remote branch, in the order in which they were initially committed, to avoid conflicts.

After thinking about it for a while, I came up with the following:


git_log_cmd='<criteria for check-in>'
git_log_prefix="git log"
git_log_super='--reverse --oneline --no-merges --pretty=%H'
git_log_full="$git_log_prefix $git_log_super $git_log_cmd"

echo "Running command:"
echo "$git_log_full"
nr_commits=$($git_log_full | wc -l)

echo Found $nr_commits, starting cherry-pick

for sha in $($git_log_full); do
        echo $git_log_prefix --oneline $sha -1
        echo Cherry picking commit \($commit_counter/$nr_commits\): $($git_log_prefix --oneline $sha -1)
        git cherry-pick $sha
        if [ $? -ne 0 ]; then
                read -p "Conflict Detected: Press any key to continue when resolved.." -n 1 -s
        let commit_counter=commit_counter+1

The above code does the following

1. Look into the remote_branch on the server remote
2. Find all changes matching the “prefix“keyword in the subject and authored by Some Author which are not merge commits
3. Print out the SHA hashes of each found change
4. Pipe the SHA hash list to tac to sort the changes by earliest first
5. Cherry-pick each commit, effectively playing back all the found commits on the local branch
6. If there is a conflict with the commit, give us a chance to fix it, and resume on the next key press

I am sure there are many more efficient ways to do the above, however at the drop of a hat that is what I came up with. Feel free to leave any pointers below on what to improve.

Leave a Reply