Skip to content

Instantly share code, notes, and snippets.

@shotasenga
Last active November 18, 2021 07:31
Show Gist options
  • Save shotasenga/ac0907b39fcdeb0e99781b1ef939fff4 to your computer and use it in GitHub Desktop.
Save shotasenga/ac0907b39fcdeb0e99781b1ef939fff4 to your computer and use it in GitHub Desktop.
git-sort (1)
#!/bin/bash
#
# Sort commit hash in topological order (oldest -> newest)
# *Unknown commit hash will be silently ignored
#
# This can be used to cherry-pick commits in appropriate order
# $ git cherry-pick `git sort hash-1 hash-2 ... hash-n`
# $ git cherry-pick `cat /path/to/commit-hash/file | git sort`
# create temporary file descriptor (see: https://unix.stackexchange.com/a/181938/501792)
tmpfile=$(mktemp /tmp/git-sort.XXXXXX)
exec 3>"$tmpfile"
exec 4<"$tmpfile"
rm $tmpfile
cat /dev/stdin >&3
for ((i=1; i<=$#; i++))
do
echo "${!i}" >&3
done
# rev-list
git rev-list --all --topo-order --reverse | grep -f <(cat <&4)
@shotasenga
Copy link
Author

The order of commit hash matters when you cherry-pick multiple commits.

Install

  1. download git-sort and move it somewhere in your $PATH
  2. make it executable - chmod +x /path/to/git-sort

Example

Sort commit hashes

git sort ac7b63d136 1bc2f4a187 5fc07626fc

Sort commit hashes in a file

$ cat /commit-hash
ac7b63d136
1bc2f4a187
5fc07626fc

$ cat /commit-hash | git sort

with cherry-pick

git cherry-pick `cat /commit-hash-to-include | git sort`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment