-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-main
More file actions
executable file
·96 lines (80 loc) · 2.17 KB
/
Copy pathgit-main
File metadata and controls
executable file
·96 lines (80 loc) · 2.17 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
95
96
#!/bin/zsh
# vim:ft=zsh
#
# git-main - git switch to main branch
#
#==================================================
show_help() {
printf -- "
git-main - git switch to main branch
Usage: git main [OPTIONS]
Options:
-h, --help Show this help message
Description:
Switch to the main branch of the current git repository. The default branch
is determined based on common branch names or fallback to remote HEAD.
Switches the main branch in the main worktree if the current directory is
a linked worktree (does not change shell directory).
"
exit 0
}
find_main_branch() {
command git rev-parse --git-dir &>/dev/null || return 1
local ref remote
local -a branches=(main trunk mainline default stable master)
local -a remotes=(origin upstream)
# 1. Check local branches
for ref in refs/heads/$^branches; do
if command git show-ref -q --verify "$ref"; then
echo "${ref:t}"
return 0
fi
done
# 2. Try to get default branch from remote HEAD
for remote in $remotes; do
if ref=$(command git symbolic-ref "refs/remotes/$remote/HEAD" 2>/dev/null); then
echo "${ref:t}"
return 0
fi
done
# 3. Fallback to common remote branch names
for remote in $remotes; do
for ref in refs/remotes/$remote/$^branches; do
if command git show-ref -q --verify "$ref"; then
echo "${ref:t}"
return 0
fi
done
done
# Ultimate fallback
echo "master"
return 1
}
switch_to_main() {
local main_branch
if ! main_branch=$(find_main_branch); then
echo "Error: Not a git repository or could not determine main branch." >&2
return 1
fi
local curr_wt main_wt
curr_wt=$(command git rev-parse --show-toplevel 2>/dev/null)
main_wt=$(command git worktree list --porcelain | awk '/^worktree / {sub(/^worktree /, ""); print; exit}')
if [[ "$curr_wt" != "$main_wt" ]]; then
echo "Switch to main worktree branch (you are in a linked worktree)."
echo "To work in the main worktree, run: cd \"$main_wt\""
return 0
fi
# Switch branch
command git switch "$main_branch"
}
main() {
case "$1" in
-h|--help)
show_help
;;
*)
switch_to_main
;;
esac
}
main "$@"