|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +abort() { |
| 4 | + error="$1" && shift |
| 5 | + echo "ERROR: $*" 1>&2 |
| 6 | + test -z "$FORCE" && exit "$error" |
| 7 | +} |
| 8 | + |
| 9 | +# Don't abort on failures. This allows to cleanup after a previous failure. |
| 10 | +[ "$1" = '--force' ] && FORCE=1 && shift |
| 11 | + |
| 12 | +test -z "$1" && abort 1 'Submodule required' |
| 13 | +cd "$(git root)" || abort 5 'Cannot change to repository root' |
| 14 | +test ! -f '.gitmodules' && abort 2 '.gitmodules file not found' |
| 15 | + |
| 16 | +NAME="${1%/}" |
| 17 | +test -z "$(git config --file='.gitmodules' "submodule.$NAME.url")" \ |
| 18 | + && abort 3 'Submodule not found' |
| 19 | + |
| 20 | +# 1. Handle the .git directory |
| 21 | +# 1.a. Delete the relevant section from .git/config |
| 22 | +git submodule deinit -f "$NAME" || abort 4 "Failed to deinitialize $NAME" |
| 23 | +# 1.b. Delete empty submodule directory |
| 24 | +git rm -f "$NAME" |
| 25 | + |
| 26 | +# 2. Handle .gitmodules file |
| 27 | +# 2.a. Delete the relevant line from .gitmodules |
| 28 | +git config --file='.gitmodules' --remove-section "submodule.$NAME" 2>/dev/null || : |
| 29 | +# 2.b and stage changes |
| 30 | +git add '.gitmodules' |
| 31 | +# 2.c. Delete empty .gitmodules |
| 32 | +[ "$(wc -l '.gitmodules' | cut -d' ' -f1)" = '0' ] && git rm -f '.gitmodules' |
| 33 | + |
| 34 | +# 3. Need to confirm and commit the changes for yourself |
| 35 | +git_status_text="$(git submodule status 2>&1)" |
| 36 | +git_status_exit=$? |
| 37 | +if [ "$git_status_exit" -eq 0 ] \ |
| 38 | + && printf '%s' "DUMMY$git_status_text" | grep -v "$NAME" > /dev/null; then |
| 39 | + # grep fails when piping in an empty string, so we add a DUMMY prefix |
| 40 | + |
| 41 | + echo "Successfully deleted $NAME." |
| 42 | +else |
| 43 | + abort 6 "Failed to delete $NAME with error:\n$git_status_text" |
| 44 | +fi |
| 45 | +printf '\n%s\n' '== git submodule status ==' |
| 46 | +printf '%s\n' "$git_status_text" |
| 47 | +printf '%s\n' '==========================' |
| 48 | +# shellcheck disable=SC2016 |
| 49 | +echo 'Confirm the output of `git submodule status` above (if any)' \ |
| 50 | + 'and then commit the changes.' |
0 commit comments