|
| 1 | +#!/usr/bin/env bash |
| 2 | +set -euo pipefail |
| 3 | + |
| 4 | +# Sync submodules quietly after common Git operations. |
| 5 | + |
| 6 | +# Resolve repository root; bail out if not inside a Git repo. |
| 7 | +repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)" |
| 8 | +if [[ -z "${repo_root}" ]]; then |
| 9 | + exit 0 |
| 10 | +fi |
| 11 | + |
| 12 | +cd "${repo_root}" |
| 13 | + |
| 14 | +# No submodules configured. |
| 15 | +if [[ ! -f .gitmodules ]]; then |
| 16 | + exit 0 |
| 17 | +fi |
| 18 | + |
| 19 | +# No submodule paths registered in .gitmodules. |
| 20 | +if ! git config --file .gitmodules --get-regexp '^submodule\..*\.path$' >/dev/null 2>&1; then |
| 21 | + exit 0 |
| 22 | +fi |
| 23 | + |
| 24 | +# Disable prompts and keep this hook silent for users without repo access. |
| 25 | +export GIT_TERMINAL_PROMPT=0 |
| 26 | +export GIT_ASKPASS=/bin/true |
| 27 | +export GIT_SSH_COMMAND="ssh -o BatchMode=yes" |
| 28 | + |
| 29 | +run_quiet() { |
| 30 | + # Ignore failures to avoid blocking normal Git operations. |
| 31 | + "$@" >/dev/null 2>&1 || true |
| 32 | +} |
| 33 | + |
| 34 | +# Initialize submodules first so each path exists. |
| 35 | +run_quiet git submodule update --init --recursive |
| 36 | + |
| 37 | +# Iterate configured submodules to ensure we are on a branch (not detached). |
| 38 | +while read -r key path; do |
| 39 | + # Convert `submodule.<name>.path` -> `<name>`. |
| 40 | + name="${key#submodule.}" |
| 41 | + name="${name%.path}" |
| 42 | + |
| 43 | + # Skip if the submodule path is missing or not initialized. |
| 44 | + if [[ ! -d "${path}" ]]; then |
| 45 | + continue |
| 46 | + fi |
| 47 | + |
| 48 | + # Skip if the path is not a Git repo. |
| 49 | + if ! git -C "${path}" rev-parse --git-dir >/dev/null 2>&1; then |
| 50 | + continue |
| 51 | + fi |
| 52 | + |
| 53 | + # Prefer repo-local submodule.<name>.branch, fallback to .gitmodules. |
| 54 | + branch="$(git config --get "submodule.${name}.branch" || true)" |
| 55 | + if [[ -z "${branch}" ]]; then |
| 56 | + branch="$(git config --file .gitmodules --get "submodule.${name}.branch" || true)" |
| 57 | + fi |
| 58 | + |
| 59 | + if [[ -n "${branch}" ]]; then |
| 60 | + # Try to checkout the branch if it already exists locally. |
| 61 | + run_quiet git -C "${path}" checkout -q "${branch}" |
| 62 | + |
| 63 | + # If still detached, create/reset the branch from origin. |
| 64 | + if ! git -C "${path}" symbolic-ref -q HEAD >/dev/null 2>&1; then |
| 65 | + run_quiet git -C "${path}" checkout -q -B "${branch}" "origin/${branch}" |
| 66 | + fi |
| 67 | + fi |
| 68 | +done < <(git config --file .gitmodules --get-regexp '^submodule\..*\.path$') |
| 69 | + |
| 70 | +# Move submodules to the newest commit on their tracking branch, merging instead of detaching. |
| 71 | +run_quiet git submodule update --remote --merge --recursive |
0 commit comments