|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +### |
| 4 | +# converts a project with git submodules to a monorepo by importing all the |
| 5 | +# submodules into the main repository. |
| 6 | +# |
| 7 | +# gets submodule info from .gitmodules file and imports each submodule into |
| 8 | +# the main repository. |
| 9 | +### |
| 10 | + |
| 11 | +main() { |
| 12 | + if [[ -f .gitmodules ]]; then |
| 13 | + # make sure the .gitmodules file is not empty |
| 14 | + if [[ ! -s .gitmodules ]]; then |
| 15 | + echo ".gitmodules file is empty. nothing to do. exiting..." |
| 16 | + else |
| 17 | + echo "found .gitmodules file. attempting to convert to monorepo..." |
| 18 | + convert |
| 19 | + fi |
| 20 | + else |
| 21 | + echo "mo .gitmodules file found. exiting..." |
| 22 | + fi |
| 23 | +} |
| 24 | + |
| 25 | +convert() { |
| 26 | + # read each submodule from .gitmodules file |
| 27 | + while read -r i; do |
| 28 | + if [[ $i == \[submodule* ]]; then |
| 29 | + read -r i # next line is the path |
| 30 | + path=$(echo "$i" | cut -d'=' -f2 | xargs) |
| 31 | + read -r i # next line is the url |
| 32 | + url=$(echo "$i" | cut -d'=' -f2 | xargs) |
| 33 | + # if path equals "src/llvm-project", skip it |
| 34 | + if [[ $path == "src/llvm-project" ]]; then |
| 35 | + echo "skipping LLVM submodule..." |
| 36 | + continue |
| 37 | + fi |
| 38 | + echo "converting $path from $url..." |
| 39 | + # deinitialize and remove the submodule |
| 40 | + git submodule deinit -f "$path" >/dev/null 2>&1 || fail "failed to deinit $path" |
| 41 | + rm -rf .git/modules/"$path" |
| 42 | + git rm -f "$path" >/dev/null 2>&1 || fail "failed to remove $path" |
| 43 | + # clone the submodule and remove its .git directory |
| 44 | + git clone "$url" "$path" >/dev/null 2>&1 || fail "failed to clone $url" |
| 45 | + rm -rf "$path"/.git |
| 46 | + # add the submodule files and commit |
| 47 | + git add "$path" >/dev/null 2>&1 || fail "failed to add $path with git" |
| 48 | + msg="imported $path into main repository" |
| 49 | + echo "$msg" |
| 50 | + git commit -m "$msg" >/dev/null 2>&1 || fail "failed to commit $path" |
| 51 | + echo "successfully converted $path." |
| 52 | + fi |
| 53 | + done <.gitmodules |
| 54 | +} |
| 55 | + |
| 56 | +fail() { |
| 57 | + printf '%s\n' "$1" >&2 |
| 58 | + exit "${2-1}" |
| 59 | +} |
| 60 | + |
| 61 | +try_and_continue() { |
| 62 | + $1 || echo "command failed: $1, continuing..." |
| 63 | +} |
| 64 | + |
| 65 | +main "$@" && echo "converted to monorepo successfully." |
0 commit comments