Commit 5e0e6c6f authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Refactor to fix git-supertree-add

parent adb54109
Loading
Loading
Loading
Loading
+45 −14
Original line number Diff line number Diff line
@@ -147,6 +147,12 @@ set_head()
	git symbolic-ref HEAD refs/heads/${2-master}
)

get_head()
{
	cd "$1"
	git symbolic-ref --short HEAD
}

get_remote_head()
{
	git ls-remote --symref ${1-origin} HEAD |
@@ -155,7 +161,18 @@ get_remote_head()

new_worktree()
{
	local WORKTREE=$1 NAME=$2
	local WORKTREE=$1 BRANCH=$(git rev-parse --symbolic-full-name "$2" 2>/dev/null)
	local FROM=$3 HEAD
	declare -a BRANCH_REMOTES=(
		$(git for-each-ref \
			--format='%(refname)' \
			"refs/remotes/*/$2" \
		)
	)

	if [[ -n "$FROM" ]] && branch_exists "$BRANCH"; then
		arg_error "$BRANCH already exists, did you mean to use --from?"
	fi

	# minimal manual worktree creation
	WT_GIT="$WORKTREE/.git"
@@ -164,7 +181,23 @@ new_worktree()
	PREFIX=gitdir gitlink $WT_GIT $WT_REPO
	REL=.git gitlink "$WT_REPO/gitdir" "$WT_GIT"
	gitlink "$WT_REPO/commondir" .git
	echo "ref: refs/heads/$NAME" > "$WT_REPO/HEAD"

	echo "ref: refs/null" > "$WT_REPO/HEAD"

	if [[ "$BRANCH" = $(git symbolic-ref HEAD) ]]; then
		echo "ref: $BRANCH" > "$WT_REPO/HEAD"
		(cd "$WORKTREE"; git reset --hard)
	elif branch_exists "$BRANCH"; then
		(cd "$WORKTREE"; git checkout $(git for-each-ref "$BRANCH" --format='%(refname:short)') )
	elif [[ -n "$FROM" ]]; then
		(cd "$WORKTREE"; git checkout -b "$BRANCH" "$FROM")
	elif [[ ${#BRANCH_REMOTES[*]} -eq 1 ]]; then
		(cd "$WORKTREE"; git checkout -b "$BRANCH" "$BRANCH_REMOTES")
	elif branch_exists "${HEAD:=$(git symbolic-ref HEAD)}"; then
		(cd "$WORKTREE"; git checkout -b "$BRANCH" "$HEAD")
	else
		echo "ref: $BRANCH" > "$WT_REPO/HEAD"
	fi
}

gitlink()
@@ -226,9 +259,7 @@ action_clone()
		cd ${REPOPATH}
		git remote add origin "${URL}"
		git fetch origin
		new_worktree ${BRANCH_PATH} ${BRANCH_NAME}
		cd ${BRANCH_PATH}
		git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
		action_add "${BRANCH_NAME}:${BRANCH_PATH}" --from origin/${BRANCH_NAME}
	)

	set_head "${REPOPATH}" "${BRANCH_NAME}"
@@ -314,18 +345,18 @@ action_add()

	if ! [[ -v BRANCH_SPEC ]]; then
		arg_error "A branch name is required"
	fi

	else
		local BRANCH_NAME=${BRANCH_SPEC%:*}
		local BRANCH_PATH=${BRANCH_SPEC#*:}
	fi

	if branch_exists $BRANCH_NAME; then
		git worktree add $BRANCH_PATH $BRANCH_NAME
	elif branch_exists ${FROM:-HEAD}; then
		git worktree add -b $BRANCH_NAME $BRANCH_PATH ${FROM:-HEAD}
	else
		new_worktree $BRANCH_PATH $BRANCH_NAME
	if [[ -d "$BRANCH_PATH" ]] && [[ -f "$BRANCH_PATH/.git" ]]; then
		die "worktree $BRANCH_PATH already exists and has '$(get_head "$BRANCH_PATH")' checked out"
	elif [[ -e "$BRANCH_PATH" ]]; then
		die "$BRANCH_PATH exists, but is not a worktree"
	fi

	new_worktree "$BRANCH_PATH" "$BRANCH_NAME" "${FROM-}"
}

action_rm()