-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit-worktree-create
More file actions
executable file
·94 lines (70 loc) · 1.94 KB
/
git-worktree-create
File metadata and controls
executable file
·94 lines (70 loc) · 1.94 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env bash
function main {
local BRANCH_NAME="${1:-}"
if [ -z "$BRANCH_NAME" ]; then
print-usage
exit 1
fi
if [ "$BRANCH_NAME" = "-h" ] || [ "$BRANCH_NAME" = "--help" ]; then
print-usage
exit 0
fi
local git_dir
if [ -d ".git" ]; then
git_dir="$(pwd)"
else
git_dir="$(dirname "$(ls -d ./*/.git/)" | head -n1)"
fi
if [ -z "$git_dir" ]; then
echo "No git directory found in current or sub-directories"
echo "Please run this script from a git directory or directly above one"
exit 1
fi
local create_dir
create_dir="$(realpath "$git_dir/..")/$BRANCH_NAME"
echo "Creating new git workdir in $create_dir"
mkdir -p "$create_dir"
cd "$git_dir" || fail "Could not cd to $create_dir"
if git rev-parse --verify "$BRANCH_NAME" >/dev/null 2>&1; then
echo "Branch '$BRANCH_NAME' already exists"
else
echo "Creating branch '$BRANCH_NAME'"
git branch "$BRANCH_NAME"
fi
git worktree add "$create_dir" "$BRANCH_NAME"
echo "Workdir created"
echo "Adding upstream remote if applicable"
cd "$create_dir" || fail "Could not cd to $create_dir"
setup-upstream-remote "$BRANCH_NAME"
echo "To switch to this workdir, run:"
echo " cd $(realpath --relative-to="$PWD" "$create_dir")"
}
function setup-upstream-remote {
local BRANCH_NAME="${1}"
git fetch --all
git branch --set-upstream-to=origin/"$BRANCH_NAME" "$BRANCH_NAME" &>/dev/null
local result="$?"
if [ "$result" -ne 0 ]; then
echo "Upstream remote seemingly does not exist"
return
fi
echo "Upstream remote set, pulling commits"
git pull
echo "Synced with upstream"
}
function fail {
echo "Error: $*" >&2
exit 1
}
function print-usage {
local script_name
script_name="$(basename "$0")"
printf "%s - Create a git workdir, but simpler\n" "$script_name"
echo "Usage:"
printf " %s <branch-name>\n" "$script_name"
}
set -uo pipefail
if [ -n "${DEBUG:-}" ]; then
set -x
fi
main "$@"