Skip to content

Instantly share code, notes, and snippets.

@dpolyakov
Forked from x3ro/git-rewrite-to-subfolder
Last active November 6, 2020 08:05
Show Gist options
  • Save dpolyakov/8a448a0815039a529d3e14292f662b5a to your computer and use it in GitHub Desktop.
Save dpolyakov/8a448a0815039a529d3e14292f662b5a to your computer and use it in GitHub Desktop.
#!/bin/bash
# We need the TAB character for SED (Mac OS X sed does not understand \t)
TAB="$(printf '\t')"
function abort {
echo "$(tput setaf 1)$1$(tput sgr0)"
exit 1
}
function request_input {
read -p "$(tput setaf 4)$1 $(tput sgr0)"
}
function request_confirmation {
read -p "$(tput setaf 4)$1 (y/n) $(tput sgr0)"
[ "$REPLY" == "y" ] || abort "Aborted!"
}
cat << "EOF"
Please provide the path which should be prepended to the current root. In the
above example, that would be "src/lib". Please note that the path MUST NOT contain
a trailing slash.
EOF
request_input "Please provide the desired path (e.g. 'src/lib'):"
# Escape input for SED, taken from http://stackoverflow.com/a/2705678/124257
TARGET_PATH=$(echo -n "$REPLY" | sed -e 's/[\/&]/\\&/g')
# Last confirmation
git ls-files -s | sed "s/${TAB}/${TAB}$TARGET_PATH\//"
request_confirmation "Please take a look at the printed file list. Does it look correct?"
# The actual processing happens here
CMD="git ls-files -s | sed \"s/${TAB}/${TAB}$TARGET_PATH\//\" | GIT_INDEX_FILE=\${GIT_INDEX_FILE}.new git update-index --index-info && mv \${GIT_INDEX_FILE}.new \${GIT_INDEX_FILE}; /bin/true"
git filter-branch -f \
--index-filter "$CMD" \
HEAD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment