-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworktree-clone.sh
More file actions
executable file
·70 lines (56 loc) · 1.71 KB
/
worktree-clone.sh
File metadata and controls
executable file
·70 lines (56 loc) · 1.71 KB
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
#!/bin/bash
# Clone a repo as a bare repository optimized for a worktree-based workflow.
# Every branch becomes a sibling directory under one project folder.
#
# Usage: worktree-clone.sh <repo-url> [directory-name]
if ! command -v git >/dev/null 2>&1; then
echo "Error: git is not installed"
exit 1
fi
if [ $# -lt 1 ]; then
echo "Usage: worktree-clone.sh <repo-url> [directory-name]"
exit 1
fi
REPO_URL="$1"
DIR_NAME="${2:-$(basename "$REPO_URL" .git)}"
if [ -d "$DIR_NAME" ]; then
echo "Error: Directory '$DIR_NAME' already exists"
exit 1
fi
mkdir "$DIR_NAME" && cd "$DIR_NAME" || exit 1
git clone --bare "$REPO_URL" .bare
if [ $? -ne 0 ]; then
echo "Failed to clone repository"
cd ..
rm -rf "$DIR_NAME"
exit 1
fi
echo "gitdir: ./.bare" > .git
# Shared .envrc for all worktrees (direnv walks up directories)
cat > .envrc << 'ENVRC'
# Shared environment variables for all worktrees in this project.
# direnv automatically loads this from any worktree subdirectory.
# Add project-wide env vars below:
ENVRC
if command -v direnv >/dev/null 2>&1; then
direnv allow .
fi
# Fix fetch refspec so `git fetch` grabs all remote branches
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
git fetch origin
if [ $? -ne 0 ]; then
echo "Failed to fetch branches"
exit 1
fi
# Determine the default branch
DEFAULT_BRANCH=$(git remote show origin | grep 'HEAD branch' | awk '{print $NF}')
if [ -z "$DEFAULT_BRANCH" ]; then
DEFAULT_BRANCH="main"
fi
git worktree add "$DEFAULT_BRANCH"
if [ $? -eq 0 ]; then
echo "Successfully cloned '$REPO_URL' into '$DIR_NAME/' with worktree '$DEFAULT_BRANCH/'"
else
echo "Failed to create worktree for '$DEFAULT_BRANCH'"
exit 1
fi