-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgh-context
More file actions
executable file
·428 lines (352 loc) · 12.1 KB
/
Copy pathgh-context
File metadata and controls
executable file
·428 lines (352 loc) · 12.1 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#!/usr/bin/env bash
set -euo pipefail
# gh-context: A kubectx-style context switcher for GitHub CLI
# Manages multiple GitHub accounts/hosts and switches between them easily
# Config locations (XDG Base Directory compliant)
CTX_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/gh/contexts"
ACTIVE_FILE="$CTX_DIR/active"
mkdir -p "$CTX_DIR"
usage() {
cat <<'EOF'
gh-context: A kubectx-style context switcher for GitHub CLI
Usage:
gh context list
gh context current
gh context new [--from-current | --hostname <host> --user <user>] [--transport ssh|https] [--ssh-host <alias>] --name <name>
gh context use <name>
gh context delete <name>
gh context bind <name>
gh context unbind
gh context apply
gh context shell-hook
Commands:
list List all contexts with active indicator
current Show active context and repo-bound context
new Create a new context
use <name> Switch to context (fast by default, prompts to auth if needed)
delete <name> Remove a saved context
bind <name> Write .ghcontext in repo root
unbind Remove .ghcontext from repo root
apply Read .ghcontext in this repo and switch to it
shell-hook Print shell snippet for auto-apply on cd
Examples:
gh context new --from-current --name work
gh context new --hostname github.com --user myuser --transport ssh --name personal
gh context use work
gh context bind work
gh context shell-hook >> ~/.bashrc
Contexts are stored in: $CTX_DIR
EOF
}
err() { echo "✗ $*" >&2; }
info() { echo "• $*"; }
ok() { echo "✓ $*"; }
ctx_file() { echo "$CTX_DIR/$1.ctx"; }
have_cmd() { command -v "$1" >/dev/null 2>&1; }
repo_root() {
git rev-parse --show-toplevel 2>/dev/null || true
}
read_kv() {
# shellcheck disable=SC1090
source "$1"
}
write_ctx() {
local file="$1" hostname="$2" user="$3" transport="$4" ssh_host="${5:-}"
{
echo "HOSTNAME=$hostname"
echo "USER=$user"
echo "TRANSPORT=$transport"
echo "SSH_HOST_ALIAS=$ssh_host"
} > "$file"
}
get_active_name() {
[[ -f "$ACTIVE_FILE" ]] && cat "$ACTIVE_FILE" || true
}
set_active_name() {
echo "$1" > "$ACTIVE_FILE"
}
ensure_logged_in() {
local host="$1" user="$2"
# For context creation, we just need to verify some auth exists
if ! GH_HOST="$host" gh auth token --hostname "$host" >/dev/null 2>&1; then
err "No authentication found for '$host'"
info "Please authenticate first: gh auth login --hostname $host --scopes repo,read:org"
exit 1
fi
# We don't switch users during context creation, just verify connectivity
if ! timeout 3 bash -c "GH_HOST=\"$host\" gh api user --hostname \"$host\"" >/dev/null 2>&1; then
err "Unable to connect to '$host'"
info "Check your network connection or try: gh auth refresh --hostname $host"
exit 1
fi
}
validate_context_name() {
local name="$1"
if [[ ! "$name" =~ ^[a-zA-Z0-9_-]+$ ]]; then
err "Context name '$name' contains invalid characters"
info "Use only alphanumeric characters, hyphens, and underscores"
exit 1
fi
}
# Subcommands
cmd_list() {
local active
active="$(get_active_name)"
if ! ls "$CTX_DIR"/*.ctx >/dev/null 2>&1; then
info "No contexts found. Create one with: gh context new --from-current --name <name>"
return 0
fi
printf "Available contexts:\n"
for f in "$CTX_DIR"/*.ctx; do
local name
name="$(basename "$f" .ctx)"
read_kv "$f"
local indicator=""
[[ "$name" == "$active" ]] && indicator=" *"
printf " %s%s\t(%s@%s, %s%s)\n" \
"$name" "$indicator" "$USER" "$HOSTNAME" "$TRANSPORT" \
"$( [[ -n "${SSH_HOST_ALIAS:-}" ]] && printf ", ssh_host=%s" "$SSH_HOST_ALIAS" )"
done
[[ -n "$active" ]] && printf "\n* = active context\n"
}
cmd_current() {
local active
active="$(get_active_name)"
if [[ -z "$active" ]]; then
echo "No active context"
else
local f; f="$(ctx_file "$active")"
if [[ -f "$f" ]]; then
read_kv "$f"
echo "Active: $active ($USER@$HOSTNAME, $TRANSPORT${SSH_HOST_ALIAS:+, ssh_host=$SSH_HOST_ALIAS})"
else
err "Active context '$active' points to missing file"
info "Run 'gh context list' to see available contexts"
fi
fi
local root; root="$(repo_root)"
if [[ -n "$root" && -f "$root/.ghcontext" ]]; then
local bound; bound="$(cat "$root/.ghcontext")"
echo "Repo-bound: $bound (in $root/.ghcontext)"
fi
}
cmd_new() {
local name="" from_current="false" host="" user="" transport="ssh" ssh_host=""
while [[ $# -gt 0 ]]; do
case "$1" in
--name) name="$2"; shift 2;;
--from-current) from_current="true"; shift;;
--hostname) host="$2"; shift 2;;
--user) user="$2"; shift 2;;
--transport) transport="$2"; shift 2;;
--ssh-host) ssh_host="$2"; shift 2;;
*) err "Unknown flag: $1"; usage; exit 1;;
esac
done
[[ -n "$name" ]] || { err "Context name is required (--name <name>)"; exit 1; }
validate_context_name "$name"
local file; file="$(ctx_file "$name")"
[[ -f "$file" ]] && { err "Context '$name' already exists"; exit 1; }
if [[ "$from_current" == "true" ]]; then
host="${host:-${GH_HOST:-github.com}}"
if ! login="$(GH_HOST="$host" gh api user --hostname "$host" --jq .login 2>/dev/null)"; then
err "Could not detect current user on '$host'"
info "Make sure you're logged in: gh auth login --hostname $host"
exit 1
fi
user="${user:-$login}"
else
if [[ -z "$host" || -z "$user" ]]; then
err "Provide either --from-current or both --hostname and --user"
usage
exit 1
fi
fi
# Validate transport
case "$transport" in
ssh|https) ;;
*) err "Transport must be 'ssh' or 'https', got: $transport"; exit 1;;
esac
write_ctx "$file" "$host" "$user" "$transport" "$ssh_host"
ok "Created context '$name' → $user@$host ($transport${ssh_host:+, ssh_host=$ssh_host})"
}
cmd_use() {
local name="${1:-}"
[[ -n "$name" ]] || { err "Context name required"; info "Usage: gh context use <name>"; exit 1; }
local file; file="$(ctx_file "$name")"
[[ -f "$file" ]] || {
err "Context '$name' not found"
info "Available contexts: $(ls "$CTX_DIR"/*.ctx 2>/dev/null | xargs -I {} basename {} .ctx | tr '\n' ' ' || echo 'none')"
exit 1
}
read_kv "$file"
# Set context immediately (fast by default)
set_active_name "$name"
ok "Switched to context '$name' ($USER@$HOSTNAME)"
# Test if authentication works
info "• Testing authentication..."
if test_auth "$HOSTNAME" "$USER"; then
ok "Authentication verified"
return 0
fi
# Authentication failed - prompt user to fix it
err "Authentication required for $USER@$HOSTNAME"
info ""
info "Your context has been set, but authentication is needed."
info "Please authenticate and your context will work automatically:"
info ""
info " gh auth login --hostname $HOSTNAME --username $USER --scopes repo,read:org"
info ""
info "After authentication, all gh commands will use the correct account."
}
# Test authentication without switching
test_auth() {
local host="$1" user="$2"
# Check if the target user has authentication available
if ! gh auth status --hostname "$host" 2>/dev/null | grep -q "Logged in to $host account $user"; then
return 1 # User not authenticated at all
fi
# Try to switch to the user (this is fast if they're already authenticated)
if GH_HOST="$host" gh auth switch --hostname "$host" --user "$user" >/dev/null 2>&1; then
# Verify the switch worked with a quick API test
local current_user
if current_user="$(timeout 3 bash -c "GH_HOST=\"$host\" gh api user --hostname \"$host\" --jq .login 2>/dev/null")"; then
current_user="${current_user//\"/}"
current_user="${current_user// /}"
[[ "$current_user" == "$user" ]]
else
return 1
fi
else
return 1 # Switch failed
fi
}
cmd_delete() {
local name="${1:-}"
[[ -n "$name" ]] || { err "Context name required"; info "Usage: gh context delete <name>"; exit 1; }
local file; file="$(ctx_file "$name")"
[[ -f "$file" ]] || { err "Context '$name' not found"; exit 1; }
rm -f "$file"
# Clear active pointer if it pointed to this context
if [[ "$(get_active_name)" == "$name" ]]; then
rm -f "$ACTIVE_FILE"
info "Cleared active context pointer"
fi
ok "Deleted context '$name'"
}
cmd_bind() {
local name="${1:-}"
[[ -n "$name" ]] || { err "Context name required"; info "Usage: gh context bind <name>"; exit 1; }
local file; file="$(ctx_file "$name")"
[[ -f "$file" ]] || { err "Context '$name' not found"; exit 1; }
local root; root="$(repo_root)"
[[ -n "$root" ]] || { err "Not inside a Git repository"; exit 1; }
echo "$name" > "$root/.ghcontext"
ok "Bound repo to context '$name' ($root/.ghcontext)"
info "Add .ghcontext to .gitignore if you don't want to commit it"
}
cmd_unbind() {
local root; root="$(repo_root)"
[[ -n "$root" ]] || { err "Not inside a Git repository"; exit 1; }
if [[ -f "$root/.ghcontext" ]]; then
rm -f "$root/.ghcontext"
ok "Removed repo binding"
else
info "No repo binding found"
fi
}
cmd_apply() {
local root; root="$(repo_root)"
[[ -n "$root" ]] || { err "Not inside a Git repository"; exit 1; }
[[ -f "$root/.ghcontext" ]] || {
err "No .ghcontext file found in repository"
info "Create one with: gh context bind <name>"
exit 1
}
local name; name="$(cat "$root/.ghcontext")"
cmd_use "$name"
}
cmd_shell_hook() {
cat <<'EOS'
# Auto-apply gh context when entering a repo with .ghcontext
# Add this to your shell configuration (.bashrc, .zshrc, etc.)
gh_context_auto_apply() {
local root
root="$(git rev-parse --show-toplevel 2>/dev/null)" || return 0
if [[ -f "$root/.ghcontext" ]]; then
local name current
name="$(cat "$root/.ghcontext")"
current=""
[[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/gh/contexts/active" ]] && \
current="$(cat "${XDG_CONFIG_HOME:-$HOME/.config}/gh/contexts/active")"
if [[ "$current" != "$name" ]]; then
echo "• Auto-applying gh context: $name"
gh context use "$name" 2>/dev/null || true
fi
fi
}
# Bash integration
if [[ -n "${BASH_VERSION:-}" ]]; then
PROMPT_COMMAND="gh_context_auto_apply; ${PROMPT_COMMAND:-}"
fi
# Zsh integration
if [[ -n "${ZSH_VERSION:-}" ]]; then
autoload -U add-zsh-hook
add-zsh-hook precmd gh_context_auto_apply
fi
EOS
}
cmd_auth_status() {
printf "Authentication status for all contexts:\n\n"
if ! ls "$CTX_DIR"/*.ctx >/dev/null 2>&1; then
info "No contexts found"
return 0
fi
local current_active
current_active="$(get_active_name)"
for f in "$CTX_DIR"/*.ctx; do
local name
name="$(basename "$f" .ctx)"
read_kv "$f"
local status_icon=""
[[ "$name" == "$current_active" ]] && status_icon=" *"
printf "Context: %s%s\n" "$name" "$status_icon"
printf " Host: %s\n" "$HOSTNAME"
printf " User: %s\n" "$USER"
printf " Transport: %s\n" "$TRANSPORT"
# Check authentication status without switching users
local auth_status="❌"
# Check if user has stored credentials
if gh auth status --hostname "$HOSTNAME" 2>/dev/null | grep -q "Logged in to $HOSTNAME account $USER"; then
auth_status="✅"
fi
printf " Auth: %s\n" "$auth_status"
# Show login command if not authenticated
if [[ "$auth_status" == "❌" ]]; then
printf " To fix: gh auth login --hostname %s --username %s --scopes repo,read:org\n" "$HOSTNAME" "$USER"
fi
printf "\n"
done
[[ -n "$current_active" ]] && printf "* = active context\n"
}
# Main dispatch
if ! have_cmd gh; then
err "GitHub CLI (gh) not found"
info "Install it from: https://cli.github.com/"
exit 1
fi
sub="${1:-}"
case "$sub" in
list) shift; cmd_list "$@";;
current) shift; cmd_current "$@";;
new) shift; cmd_new "$@";;
use) shift; cmd_use "$@";;
delete) shift; cmd_delete "$@";;
bind) shift; cmd_bind "$@";;
unbind) shift; cmd_unbind "$@";;
apply) shift; cmd_apply "$@";;
shell-hook) shift; cmd_shell_hook "$@";;
auth-status) shift; cmd_auth_status "$@";;
-h|--help|help|"") usage;;
*) err "Unknown command: $sub"; echo; usage; exit 1;;
esac