-
Notifications
You must be signed in to change notification settings - Fork 21
/
gh-branch
executable file
·111 lines (97 loc) · 2.45 KB
/
gh-branch
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
105
106
107
108
109
110
111
#!/usr/bin/env bash
set -e
help() {
cat <<EOF
Usage: gh branch
Displays an interactive branch switcher that lists local branches in relation
to the pull requests in the repository. The selected branch is checked out.
With \`--static\`, print a non-interactive list of branches.
Dependencies: fzf
EOF
# You can also select multiple branches with Tab and press Ctrl-D to delete them.
}
static=
while [ $# -gt 0 ]; do
case "$1" in
-h|--help)
help
exit 0
;;
--static)
static=1
;;
*)
help >&2
exit 1
;;
esac
shift
done
branch_info() {
git for-each-ref 'refs/heads/**' --format='%(refname:short)%09%(committerdate:unix)%09%(committerdate:relative)%09%(HEAD)'
}
list_prs() {
gh api graphql --cache=5m -F owner='{owner}' -F repo='{repo}' -f query='
query ($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
pullRequests(last: 100) {
nodes {
number
author {
login
}
state
headRefName
}
}
}
}
' --template '
{{- range .data.repository.pullRequests.nodes -}}
{{- .headRefName | printf "%s\t" -}}
{{- $stateColor := "green" -}}
{{- if eq .state "CLOSED" }}{{ $stateColor = "red" }}
{{- else if eq .state "MERGED" }}{{ $stateColor = "magenta" }}{{ end -}}
{{- .number | printf "#%.0f" | color $stateColor -}}
{{- .author.login | printf " by %s\n" -}}
{{- end -}}
'
}
find_pr() {
local head_branch rest
while IFS=$'\t' read -r head_branch rest; do
if [ "$1" = "$head_branch" ]; then
printf "\t%s" "$rest"
break
fi
done
}
render() {
local branches branch timeago current all_prs
branches="$(branch_info)" || return 1
all_prs="$(list_prs 2>/dev/null || true)"
sort -k2 -r <<<"$branches" | while IFS=$'\t' read -r branch _ timeago current _; do
[ "$current" = "*" ] && continue
printf "%s\t%s%s\n" "$branch" "$timeago" "$(find_pr "$branch" <<<"$all_prs")"
done | tableize
}
tableize() {
column -t -s$'\t'
}
if [ -n "$static" ]; then
render
exit 0
fi
if ! type -p fzf >/dev/null; then
echo "error: install \`fzf\` to use this command" >&2
exit 1
fi
choose() {
local rendered
rendered="$(render)" || return 1
#--multi --bind "ctrl-d:execute-silent(git branch -D {+1})+reload(\"$0\" --static)"
fzf --ansi <<<"$rendered"
}
selected="$(choose)"
[ -n "$selected" ] || exit 1
git checkout "${selected%% *}"