summaryrefslogtreecommitdiffstats
path: root/src/subgit-add
blob: e1e0d1932acbae9b9ce58822bd03aac88f3d0fe9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/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[@]}"