#!/bin/bash usage() { die $(cat <<-EOF Usage: subgit add [-c COMMIT] [-b BRANCH] REMOTE DEST subgit add [-c COMMIT] [-b BRANCH] PATH Begin tracking a remote repository, optionally at a specific branch or commit, as a subgit repo in the current path. REMOTE DEST: Clone from remote URL to destination path PATH: Add existing local repo, extracting remote/commit from it EOF ) } branch= commit= initargs=() while [ "$1" ]; do case $1 in -b) [ $# -lt 2 ] && die "Missing branch" || branch="$2"; shift; shift;; -c) [ $# -lt 2 ] && die "Missing commit" || commit="$2"; shift; shift;; -h) usage;; --) shift; break;; -*) initargs+=("$1"); shift;; *) break;; esac done if [ $# -eq 1 ]; then # Single argument - existing local repo if [ ! -d "$1" ]; then die "Directory does not exist: $1" fi path=$(realpath "$1") if [ ! -d "$path/.git" ]; then die "Not a git repository: $path" fi # Extract remote URL from existing repo remote=$(git -C "$path" remote get-url origin 2>/dev/null || echo "") if [ -z "$remote" ]; then die "No remote 'origin' found in $path" fi # Extract current branch if not specified with -b if [ -z "$branch" ]; then branch=$(git -C "$path" branch --show-current) fi # Extract current commit if not specified with -c if [ -z "$commit" ]; then commit=$(git -C "$path" rev-parse HEAD) fi elif [ $# -eq 2 ]; then # Two arguments - remote and destination (original behavior) remote=$1 path=$(realpath -m "$2") else usage fi root=$(realpath .) [ "${path#$root/}" = "$path" ] && die "Not a subdirectory" relpath=$(realpath -m --relative-to="$root" "$path") alt_root=$(subgit-sub root "$path" &>/dev/null) if [ ! -z "$alt_root" ]; then alt_relpath=$(subgit-sub relpath "$alt_root" "$path" &>/dev/null) if [ ! -z "$alt_relpath" ]; then if [ "${alt_relpath#$relpath}" != "${alt_relpath}" ]; then die "Already tracked in $alt_root" fi fi fi if [ -d "$path" ]; then warn "Path $relpath already exists, adding.." mkdir -p "$(dirname "$root/.subgit/$relpath")" mv "$path/.git" "$root/.subgit/$relpath" fi if [ -e "$root/.subgitrc" ]; then source "$root/.subgitrc" [ ! -z "${subgit[$relpath]}" ] && \ die "Subrepo $relpath already added" else subgit-source genrc > "$root/.subgitrc" source "$root/.subgitrc" fi subgit[$relpath]=1 subgitinfo[$relpath/remote]=$remote subgitinfo[$relpath/branch]=$branch subgitinfo[$relpath/commit]=$commit subgit-source genrc > "$root/.subgitrc" # in case init fails subgit-source init -S -u "${initargs[@]}"