Skip to content

Instantly share code, notes, and snippets.

@ndevenish
Created March 19, 2019 12:07
Show Gist options
  • Save ndevenish/a7a9eb93cc19abbfe80f2daab16d3367 to your computer and use it in GitHub Desktop.
Save ndevenish/a7a9eb93cc19abbfe80f2daab16d3367 to your computer and use it in GitHub Desktop.
Script to rebase pre-black branches onto post-black tree
#!/bin/bash
cat <<EOF
Rewriting current branch to master, by applying black.
This is only tested for simple, linear branches and results should
be checked thoroughly before abandoning the old history.
EOF
# Find out the combined base commit
BASE=$(git merge-base HEAD master)
# How many commits are we ahead?
commit_count=$(git rev-list --count ${BASE}..HEAD)
# Get a list of every .py file that changed - so we don't reformat everything
export changed_files="$(git log --name-only --pretty="format:" -${commit_count} | sort | uniq | sed -e '/^$/d' | grep '.py$')"
echo "Changed files:"
echo "${changed_files}"
# Do the rewriting. Do one commit more than required so that the first commit
# doesn't include the diff from reformatting everything to black
git filter-branch -f --tree-filter 'black $(echo "$changed_files" | xargs ls -d 2>/dev/null)' ${BASE}^..HEAD
# Now, rebase the original number of commits onto the master
git rebase HEAD~${commit_count} --onto master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment