#!/usr/bin/env bash set -euo pipefail repo_root="${JEANNIE_SERVER_REPO_ROOT:-${REPO_ROOT:-$(pwd)}}" remote="${JEANNIE_REPO_SYNC_REMOTE:-origin}" branch="${JEANNIE_REPO_SYNC_BRANCH:-}" while (($# > 0)); do case "$1" in --remote) remote="${2:-}"; shift 2 ;; --branch) branch="${2:-}"; shift 2 ;; *) echo "Usage: ./jeannie repo-sync [--remote REMOTE] [--branch BRANCH]" >&2; exit 2 ;; esac done [[ -d "${repo_root}/.git" ]] || { echo "Git repository not found: ${repo_root}" >&2; exit 1; } git_cmd=(git -C "${repo_root}") current_branch="$("${git_cmd[@]}" branch --show-current)" [[ -n "${branch}" ]] || branch="${current_branch}" [[ -n "${branch}" ]] || { echo "Repository is in detached HEAD; specify --branch." >&2; exit 2; } "${git_cmd[@]}" remote get-url "${remote}" >/dev/null || { echo "Git remote not found: ${remote}" >&2 exit 2 } # OpenTofu leaves transient lock metadata after an interrupted plan. Remove # only these generated files, and only when no OpenTofu process is running; # real source changes remain blocking as before. if ! pgrep -af '[t]ofu' >/dev/null 2>&1; then while IFS= read -r stale_tofu_lock; do [[ -n "${stale_tofu_lock}" ]] || continue rm -f "${stale_tofu_lock}" echo "Removed stale OpenTofu lock metadata: ${stale_tofu_lock}" done < <(find "${repo_root}/bootstrap" -type f -name '.terraform.tfstate.lock.info' -print) fi if [[ -f "${repo_root}/go.sum" ]] && ! "${git_cmd[@]}" ls-files --error-unmatch go.sum >/dev/null 2>&1; then rm -f "${repo_root}/go.sum" echo "Removed generated untracked Go checksum file: ${repo_root}/go.sum" fi go_mod_diff="$("${git_cmd[@]}" diff --unified=0 -- go.mod)" if [[ -n "${go_mod_diff}" && "${go_mod_diff}" == *"// indirect"* ]]; then added_go_mod_lines="$(printf "%s\n" "${go_mod_diff}" | grep -E "^\\+[^+]" || true)" non_generated_go_mod_lines="$(printf "%s\n" "${added_go_mod_lines}" | grep -vE "^\\+(require \\(|\\)|[[:space:]]+[^[:space:]]+[[:space:]]+v[^[:space:]]+[[:space:]]+// indirect|[[:space:]]*)$" || true)" if [[ -z "${non_generated_go_mod_lines}" ]]; then "${git_cmd[@]}" restore -- go.mod echo "Restored generated indirect-only Go module changes." fi fi if [[ -n "$("${git_cmd[@]}" status --porcelain)" ]]; then echo "Refusing repo sync: working tree is not clean." >&2 "${git_cmd[@]}" status --short >&2 exit 1 fi before="$("${git_cmd[@]}" rev-parse HEAD)" printf 'Repository: %s\nRemote: %s\nBranch: %s\nBefore: %s\n' "${repo_root}" "${remote}" "${branch}" "${before}" "${git_cmd[@]}" fetch --prune "${remote}" "${branch}" remote_ref="${remote}/${branch}" "${git_cmd[@]}" rev-parse --verify "${remote_ref}" >/dev/null || { echo "Remote branch not found: ${remote_ref}" >&2 exit 1 } "${git_cmd[@]}" merge --ff-only "${remote_ref}" after="$("${git_cmd[@]}" rev-parse HEAD)" if [[ "${before}" == "${after}" ]]; then echo "Already up to date." else printf 'Updated: %s -> %s\n' "${before}" "${after}" fi