Repository navigation
Expand file tree
/
Copy pathzh
More file actions
executable file
·10740 lines (9531 loc) · 441 KB
/
Copy pathzh
File metadata and controls
executable file
·10740 lines (9531 loc) · 441 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# zh - ZenHub CLI Tool
#
# A command-line interface for ZenHub API operations.
# Wraps the ZenHub GraphQL API to manage issues, pipelines, and workspaces.
#
# Repository: https://github.com/acme-user/zenhub-cli
# License: MIT
#
set -euo pipefail
# Read version from VERSION file (same directory as script, resolving symlinks)
SCRIPT_PATH="${BASH_SOURCE[0]}"
while [[ -L "$SCRIPT_PATH" ]]; do
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
SCRIPT_PATH="$(readlink "$SCRIPT_PATH")"
[[ "$SCRIPT_PATH" != /* ]] && SCRIPT_PATH="$SCRIPT_DIR/$SCRIPT_PATH"
done
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
VERSION=$(cat "${SCRIPT_DIR}/VERSION" 2>/dev/null | tr -d '[:space:]' || echo "unknown")
# =============================================================================
# Configuration
# =============================================================================
CONFIG_DIR="${HOME}/.config/zh"
CONFIG_FILE="${CONFIG_DIR}/config"
ZENHUB_API="https://api.zenhub.com/public/graphql"
# Colors for output
#
# v1.9.2 round-3 (PR #27) finding #9: honor the NO_COLOR informal
# standard (https://no-color.org). When NO_COLOR is set to ANY
# non-empty value, suppress every ANSI escape so the output is plain
# text. Tests can set NO_COLOR=1 to skip the ANSI-strip helper, and
# users on terminals that don't render ANSI (or who prefer plain
# output) get a clean rendering. The variable is checked once at
# script-load time; we don't re-evaluate per-call.
if [[ -n "${NO_COLOR:-}" ]]; then
RED=''
GREEN=''
YELLOW=''
BLUE=''
CYAN=''
NC=''
BOLD=''
else
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
BOLD='\033[1m'
fi
# =============================================================================
# Helper Functions
# =============================================================================
# v1.9.2 round-7 finding #13: switch error/warn/info/success from
# `echo -e` to `printf '%s\n'`. The `echo -e` form interprets
# escape sequences (\n, \t, \\) inside the payload, which silently
# corrupts ZenHub-side error messages that contain `jq -c` JSON
# strings: a value like `"permission denied:\nrepo is archived"`
# rendered as a real newline, fragmenting the single-line warn
# across multiple stderr lines and invalidating the embedded JSON
# for downstream parsers. The round-6 #4 partial-applied warn at
# zh:3569 embeds `jq -c` output via `${gh_errors}`, so this fix
# matters most there but it's correct everywhere.
#
# The color escapes themselves stay (they're literal ANSI bytes in
# the format string, not in the payload, so printf passes them
# through unchanged). Trailing `\n` is added explicitly.
error() {
printf "${RED}Error:${NC} %s\n" "$1" >&2
exit 1
}
warn() {
printf "${YELLOW}Warning:${NC} %s\n" "$1" >&2
}
info() {
printf "${BLUE}Info:${NC} %s\n" "$1"
}
success() {
printf "${GREEN}\xe2\x9c\x93${NC} %s\n" "$1"
}
# v1.9.2 round-3 (PR #27) finding #5: build a single-line cause-hint
# from a possibly-multi-line stderr capture so post-create envelope
# warns can include the actionable detail (e.g. ZenHub's
# "Error: ZenHub API error:\n Hint: regenerate at https://...")
# rather than only the header line. Collapses internal newlines to
# "; ", strips ANSI escapes, drops empty lines, caps at 240 chars
# with a trailing "..." marker if truncated. Reads from a file path
# (which may be /dev/null per the round-1 #2 fail-soft fallback);
# returns empty when the file is missing / empty / /dev/null.
#
# v1.9.2 round-4 (PR #27) finding #12: prefer the coreutils pipeline
# (sed + awk + paste + tr) but fall back to a pure-bash implementation
# when any of those tools are missing (alpine/busybox containers).
# Without the fallback, the pipeline returns empty and every warn
# silently lost its cause clause with no diagnostic. The pure-bash
# variant strips CSI ANSI escapes, OSC sequences (round-4 finding
# #15), drops empty lines, joins with "; ", and caps at 240 chars
# using only built-in parameter expansion.
zh_cause_hint() {
local _f="$1"
if [[ -z "$_f" || "$_f" == "/dev/null" || ! -s "$_f" ]]; then
printf '%s' ""
return 0
fi
local _raw=""
# Detect coreutils availability up-front; if any are missing,
# use the pure-bash fallback. `command -v` returns 0 iff the
# tool resolves on PATH.
if command -v sed >/dev/null 2>&1 \
&& command -v awk >/dev/null 2>&1 \
&& command -v paste >/dev/null 2>&1 \
&& command -v tr >/dev/null 2>&1; then
_raw=$(LC_ALL=C sed -E $'s/\033\\[[0-9;]*[a-zA-Z]//g; s/\033\\][^\007\033]*(\007|\033\\\\)//g' "$_f" 2>/dev/null \
| awk 'NF>0' \
| paste -sd';' - \
| tr -s ';' \
| sed -e 's/;/; /g' 2>/dev/null || true)
else
# Pure-bash fallback: read the file line-by-line, strip
# ANSI escape sequences via regex match-and-replace, drop
# empties, join with "; ". Uses pre-computed sentinel
# strings instead of inline $'\033' interpolation so the
# bash 3.2 / 4.x regex parser doesn't choke.
#
# v1.9.4 round-2 finding #3: pin LC_ALL=C for the duration
# of this fallback so `${str:i:1}` extracts BYTES, not
# characters. Otherwise a UTF-8 locale (the modern default)
# makes the 8-bit C1 byte comparisons below silently fail
# against the canonical UTF-8 encoding (0xC2 0x9C / 0xC2
# 0x9B), leaving OSC garbage in the output. `local` here
# scopes the change to this function call; restoration is
# automatic on return.
local LC_ALL=C
local _esc _csi_re _osc_bel_re
_esc=$'\033'
# CSI: ESC [ <params/intermediates> <final-byte>
_csi_re="${_esc}\[[0-9;]*[a-zA-Z]"
# OSC, BEL-terminated: ESC ] <text> BEL
_osc_bel_re="${_esc}\][^"$'\007\033'"]*"$'\007'
# v1.9.3 pattern-sweep finding #7: handle ESC-backslash (ST)
# terminators too. The coreutils sed branch above strips both
# BEL and ST via `(\007|\033\\\\)`; the pure-bash branch was
# BEL-only.
#
# We deliberately don't run a parallel regex for ST. The naive
# approach is `_osc_st_re="${_esc}\][^${_esc}]*${_esc}\\\\"` and
# then `${_line//${BASH_REMATCH[0]}/}` to substitute, but bash's
# pattern-substitution operator treats the search string as a
# glob pattern, where a trailing backslash (the ST terminator's
# second byte) swallows the closing `/` of the substitution.
# The substitution silently no-ops, the regex re-matches the
# same span, and the loop spins forever.
#
# Instead, normalize ESC-backslash to BEL via a literal-scalar
# `${var/from/to}` substitution (no glob involved, no infinite
# loop), then let the existing BEL OSC regex catch every OSC.
# The normalization is harmless when no OSC is present — a bare
# ESC `\` outside an OSC is not a thing terminals emit. ESC
# alone is excluded from the OSC body class so the BEL regex
# still terminates at the right byte.
local _bel _st8 _csi8
_bel=$'\007'
# v1.9.4 finding #3 / LOW #3: also normalize 8-bit C1 controls.
# 0x9C is the 8-bit ST (string terminator); fold to BEL so the
# BEL OSC regex catches OSC sequences that used the single-byte
# ST. 0x9B is the 8-bit CSI introducer; expand to ESC `[` so
# the existing CSI regex picks it up. The function-scoped
# `local LC_ALL=C` above ensures byte-wise comparison, so this
# also catches the UTF-8-encoded form (0xC2 0x9C / 0xC2 0x9B):
# the leading 0xC2 falls through to the else-branch (no match
# for ESC/8-bit C1), then the trailing 0x9C/0x9B byte matches
# on the next pass.
_st8=$'\234'
_csi8=$'\233'
local _line _out=""
while IFS= read -r _line || [[ -n "$_line" ]]; do
# Normalize OSC ST → OSC BEL FIRST. We can't use
# `${_line//<ESC-backslash>/<BEL>}` because bash's pattern
# substitution treats the trailing backslash in the search
# pattern as a glob escape (the backslash needs a next
# char to escape; there isn't one, so the substitution
# silently no-ops). A character-by-character scan is slow
# but correct on a line; this branch only runs on tiny
# error files, never on the GraphQL response stream.
local _norm="" _len="${#_line}" _i=0 _ch _next
while (( _i < _len )); do
_ch="${_line:_i:1}"
_next="${_line:_i+1:1}"
if [[ "$_ch" == "$_esc" && "$_next" == "\\" ]]; then
# 7-bit ST: ESC \ → BEL
_norm+="$_bel"
_i=$((_i + 2))
elif [[ "$_ch" == "$_st8" ]]; then
# 8-bit ST (0x9C) → BEL
_norm+="$_bel"
_i=$((_i + 1))
elif [[ "$_ch" == "$_csi8" ]]; then
# 8-bit CSI (0x9B) → ESC [
_norm+="${_esc}["
_i=$((_i + 1))
else
_norm+="$_ch"
_i=$((_i + 1))
fi
done
_line="$_norm"
# Strip every CSI sequence on this line.
while [[ "$_line" =~ $_csi_re ]]; do
_line="${_line//${BASH_REMATCH[0]}/}"
done
# Strip every BEL-terminated OSC sequence (now covers
# ST-terminated too, thanks to the normalization above).
while [[ "$_line" =~ $_osc_bel_re ]]; do
_line="${_line//${BASH_REMATCH[0]}/}"
done
# Skip empty / whitespace-only lines.
local _trimmed="${_line#"${_line%%[![:space:]]*}"}"
if [[ -n "$_trimmed" ]]; then
if [[ -n "$_out" ]]; then
_out="${_out}; ${_line}"
else
_out="$_line"
fi
fi
done < "$_f"
_raw="$_out"
fi
if [[ ${#_raw} -gt 240 ]]; then
_raw="${_raw:0:237}..."
fi
printf '%s' "$_raw"
}
# Lowercase a string portably. bash 3.2 (macOS default, and a CI matrix
# target) has no ${var,,} parameter expansion, so use tr.
to_lower() {
printf '%s' "$1" | tr '[:upper:]' '[:lower:]'
}
# Load configuration
load_config() {
# Round-6 #14: precedence must be env > config (to match Python
# `resolve_context` round-3 #11 SPEC).
#
# The pre-fix idiom `source $CONFIG_FILE` overwrote any
# environment-set values with config-file values — config-wins.
# That was inverted vs the Python side, which read env first
# and only fell back to config. A user with `export ZH_REPO=
# acme/widgets` and a stale config file would see Python pick
# `acme/widgets` while bash silently used the config value.
#
# Fix: source each config file in a SUBSHELL, capture the
# variables we care about, then apply them only when the
# caller's env is unset. The subshell isolates the source so
# the file's full set of side effects doesn't leak into our
# process. Quoted-value handling stays correct because bash
# parses the file with its own rules in the subshell.
local config_zh_token=""
local config_zh_rest_token=""
local config_zh_repo=""
local config_zh_workspace=""
_load_config_from() {
local src="$1"
[[ -f "$src" ]] || return 0
# Subshell isolates the source: unset our target vars first
# so the subshell starts with them empty, then source the
# file and emit each captured value on its OWN line so the
# outer reader can pick them by line position. `read -r` with
# tab-delimited values collapses consecutive tabs (empty
# fields disappear), so line-per-value is the robust shape.
local sourced
sourced=$(
unset ZH_TOKEN ZH_REST_TOKEN ZH_REPO ZH_WORKSPACE
# shellcheck disable=SC1090
source "$src" 2>/dev/null
printf '%s\n' \
"${ZH_TOKEN:-}" \
"${ZH_REST_TOKEN:-}" \
"${ZH_REPO:-}" \
"${ZH_WORKSPACE:-}"
)
# Parse line-by-line; empty lines stay as empty values.
local line idx=0
local t="" r="" p="" w=""
while IFS= read -r line; do
case "$idx" in
0) t="$line" ;;
1) r="$line" ;;
2) p="$line" ;;
3) w="$line" ;;
esac
idx=$((idx + 1))
done <<< "$sourced"
# First-wins across the two config sources: only set if not
# already set by an earlier source (or env, see apply step).
[[ -z "$config_zh_token" ]] && config_zh_token="$t"
[[ -z "$config_zh_rest_token" ]] && config_zh_rest_token="$r"
[[ -z "$config_zh_repo" ]] && config_zh_repo="$p"
[[ -z "$config_zh_workspace" ]] && config_zh_workspace="$w"
}
_load_config_from "$CONFIG_FILE"
_load_config_from ".env"
unset -f _load_config_from
# Apply config values ONLY where the corresponding env var is
# unset/empty. Env wins; config is fallback. Matches Python's
# resolve_context precedence.
ZH_TOKEN="${ZH_TOKEN:-$config_zh_token}"
ZH_REST_TOKEN="${ZH_REST_TOKEN:-$config_zh_rest_token}"
ZH_REPO="${ZH_REPO:-$config_zh_repo}"
ZH_WORKSPACE="${ZH_WORKSPACE:-$config_zh_workspace}"
# Validate required config
if [[ -z "${ZH_TOKEN:-}" ]]; then
error "ZH_TOKEN not set. Create ${CONFIG_FILE} with:
ZH_TOKEN=your_zenhub_api_token
Get your token at: https://app.zenhub.com/settings/tokens"
fi
}
# Make a GraphQL request to ZenHub API
zh_graphql() {
local query="$1"
local variables="${2:-{\}}"
# Build request body using jq to ensure proper JSON formatting
local body
body=$(jq -n --arg q "$query" --argjson v "$variables" '{query: $q, variables: $v}')
local response
response=$(curl -s -X POST "$ZENHUB_API" \
-H "Authorization: Bearer ${ZH_TOKEN}" \
-H "Content-Type: application/json" \
-d "$body")
# Check for errors
if echo "$response" | jq -e '.errors' > /dev/null 2>&1; then
local error_msg error_kind
error_msg=$(echo "$response" | jq -r '.errors[0].message // "Unknown error"')
# NO_ACCESS (e.g. on createIssue against a repo object) is the mutation-
# side face of a lapsed ZenHub<->GitHub authorization. Inspect the error
# type / extensions.code / message and append the re-auth hint so the
# mutation path gets the same guidance as the empty-result resolution
# path (see zh_repo_access_hint).
error_kind=$(echo "$response" | jq -r '[.errors[0].type, .errors[0].extensions.code] | map(select(. != null)) | join(" ")')
# Match ZenHub's actual access-denied vocabulary (NO_ACCESS type, and the
# "no access" / "not authorized" human-message variants). Kept narrow on
# purpose: broader synonyms like "forbidden"/"unauthorized" would risk
# appending the re-auth hint to unrelated errors. Explicit else (not a
# fall-through to a second `error`) so the control flow doesn't silently
# depend on error() calling exit.
if printf '%s %s' "$error_kind" "$error_msg" | grep -qiE 'NO_ACCESS|no access|not authorized'; then
error "ZenHub API error: $error_msg
This usually means ZenHub's GitHub authorization has lapsed (its GitHub access
expires separately from your zh token). Sign in at https://app.zenhub.com and
re-authorize GitHub if prompted, then retry."
else
error "ZenHub API error: $error_msg"
fi
fi
echo "$response"
}
# Get GitHub owner/repo. Resolution order:
# 1. ZH_REPO_OVERRIDE — set by the `-r` / `--repo` global flag
# 2. ZH_REPO — config-file value (read by load_config)
# 3. git remote get-url origin in the current directory
#
# The first two paths are explicit; the third is the historical default
# and is what every command does when nothing's overridden.
get_repo_info() {
if [[ -n "${ZH_REPO_OVERRIDE:-}" ]]; then
echo "$ZH_REPO_OVERRIDE"
return
fi
if [[ -n "${ZH_REPO:-}" ]]; then
echo "$ZH_REPO"
return
fi
local remote_url
remote_url=$(git remote get-url origin 2>/dev/null || echo "")
if [[ -z "$remote_url" ]]; then
error "No repository specified.
Either:
- Use -r owner/repo (or --repo) to target a specific repository
- Set ZH_REPO=owner/repo in ${CONFIG_FILE}
- Run from within a git repository with a GitHub remote (origin)
For multi-workspace repos, also see -w / --workspace and ZH_WORKSPACE."
fi
# Parse owner/repo from various URL formats.
#
# Repo names on GitHub can contain dots (e.g. "docs.github.io",
# "my.tool", "internal.docs"). The repo group used to be `[^/.]+`
# which silently failed to match those.
#
# The prefix anchors strictly on either `git@github.com:` (ssh)
# or `https?://github.com/` (https) — the two forms `git remote
# get-url origin` emits in practice. Schemes like `ssh://`,
# `git://`, and `git+ssh://` are accepted by some git clients
# but not produced by `git remote get-url`, so we reject them to
# keep this regex in lockstep with the Python parsers in
# `zh_api._GH_URL_RE` and `similarity._GITHUB_URL_RE`.
# Round-4 finding #5.
#
# Bash extended regex doesn't support non-greedy quantifiers, so
# we trim any trailing `/` from the URL up-front and match
# greedily on `[^/]+`, then strip the optional `.git` suffix
# from the captured repo name.
local trimmed_url="${remote_url%/}"
if [[ "$trimmed_url" =~ ^(git@github\.com:|https?://github\.com/)([^/]+)/([^/]+)$ ]]; then
local owner="${BASH_REMATCH[2]}"
local repo="${BASH_REMATCH[3]}"
repo="${repo%.git}"
echo "${owner}/${repo}"
else
error "Could not parse GitHub repository from remote URL: $remote_url"
fi
}
# Resolve a repo's numeric GitHub ID via the gh CLI, failing closed.
#
# `gh api repos/<owner>/<repo> --jq '.id'` does not fail safely on its own.
# On an HTTP error (404 for a missing or private repo, an auth failure, or a
# misbehaving gh shim that prints an error body but exits 0) the result is
# either a non-zero exit or a non-numeric JSON error body, e.g.
# {"message":"Not Found",...,"status":"404"}. A bare `[[ -z "$gh_id" ]]`
# guard misses the body case; under `set -e` the non-zero case dies silently
# at the bare assignment. The body then flows into the GraphQL
# `$ghIds: [Int!]!` variable and surfaces as a baffling
# "could not coerce value {...} to Int" cascade followed by a misleading
# "No workspace found".
#
# This helper checks BOTH the gh exit status and that the result is purely
# numeric. On success it prints the id and returns 0. On failure it prints
# the (collapsed, one-line) gh diagnostic to stderr and returns 1, so callers
# can abort with a clean actionable message or degrade. The `|| gh_status=$?`
# capture keeps the inner failure from tripping `set -e` before we inspect it.
resolve_gh_repo_id() {
local owner_repo="$1"
local gh_id gh_status=0
gh_id=$(gh api "repos/${owner_repo}" --jq '.id' 2>&1) || gh_status=$?
if (( gh_status != 0 )) || [[ ! "$gh_id" =~ ^[0-9]+$ ]]; then
local detail
detail=$(printf '%s' "$gh_id" | tr '\n' ' ')
printf " GitHub lookup for '%s' failed: %s\n" "$owner_repo" "$detail" >&2
return 1
fi
printf '%s' "$gh_id"
}
# Get ZenHub repository ID from owner/repo (uses gh CLI to get GitHub ID first)
# Shared, actionable guidance for the "ZenHub can't see a repo we know exists on
# GitHub" failure. The tell is "reads work but repo access fails": ZenHub
# authenticates ZH_TOKEN and lists workspaces, yet returns no repo object for the
# repo. ZenHub reaches GitHub repo objects through a GitHub OAuth/App grant that
# expires INDEPENDENTLY of ZH_TOKEN, so the usual cause is a lapsed ZenHub<->GitHub
# authorization (re-auth on the website), not a bad token or a missing repo. The
# other cause is the repo simply not being attached to a workspace. Both surface
# identically (empty repositoriesByGhId), so we name both and lead with the auth
# one. Echoes a multi-line message for error() to frame.
zh_repo_access_hint() {
local owner_repo="$1" gh_id="${2:-}"
local idnote=""
[[ -n "$gh_id" ]] && idnote=" (GitHub ID: ${gh_id})"
cat <<EOF
ZenHub can't see this repository for your account: ${owner_repo}${idnote}.
The token authenticated and workspaces are readable, but ZenHub returned no repo
object. This is usually one of:
1. ZenHub's GitHub authorization has lapsed. Sign in at https://app.zenhub.com
and re-authorize GitHub if prompted, then retry. ZenHub's GitHub access
expires separately from your zh token, so reads keep working while repo
access is denied -- easy to miss.
2. The repo isn't connected to a ZenHub workspace. Add it in ZenHub ->
workspace -> Manage Repositories.
EOF
}
get_repo_id() {
local owner_repo="$1"
# First get the GitHub repo ID using gh CLI
local gh_id
gh_id=$(resolve_gh_repo_id "$owner_repo") || \
error "Could not get GitHub repo ID for: $owner_repo (check the repo path and 'gh auth status')"
# Now query ZenHub with the GitHub ID
local query='
query($ghIds: [Int!]!) {
repositoriesByGhId(ghIds: $ghIds) {
id
ghId
name
}
}'
local variables
variables=$(jq -n --argjson gh_id "$gh_id" '{ghIds: [$gh_id]}')
local response
response=$(zh_graphql "$query" "$variables")
local repo_id
repo_id=$(echo "$response" | jq -r '.data.repositoriesByGhId[0].id // empty')
if [[ -z "$repo_id" ]]; then
error "$(zh_repo_access_hint "$owner_repo" "$gh_id")"
fi
echo "$repo_id"
}
# Hard cap on workspace-list pagination iterations. 50 pages × 50 nodes
# = 2,500 workspaces, vastly more than any plausible per-repo count, so
# the cap only ever fires on a server-side stuck-cursor bug.
ZH_WORKSPACE_PAGINATION_CAP=50
# Walk every page of `workspacesConnection` for a repo and emit a single
# JSON array of `{id, name}` nodes on stdout. Same stuck-cursor +
# iteration-cap defenses as the sub-issue and sprint walkers.
#
# Argument: gh_id (GitHub numeric repo id).
zh_workspaces_fetch_all() {
local gh_id="$1"
local query='
query($ghIds: [Int!]!, $after: String) {
repositoriesByGhId(ghIds: $ghIds) {
id
workspacesConnection(first: 50, after: $after) {
pageInfo { hasNextPage endCursor }
nodes { id name }
}
}
}'
local cursor="null"
local last_cursor=""
local iterations=0
local all_nodes="[]"
while :; do
iterations=$((iterations + 1))
if [[ "$iterations" -gt "$ZH_WORKSPACE_PAGINATION_CAP" ]]; then
warn "Workspace pagination iteration cap (${ZH_WORKSPACE_PAGINATION_CAP}) reached"
break
fi
local variables
variables=$(jq -n --argjson gh_id "$gh_id" --argjson after "$cursor" \
'{ghIds: [$gh_id], after: $after}')
local response
response=$(zh_graphql "$query" "$variables")
# Round-6 #8: `select(. != null)` strips null page entries
# at aggregation, matching the other three walkers.
local page_nodes
page_nodes=$(echo "$response" | jq -c '[(.data.repositoriesByGhId[0].workspacesConnection.nodes // [])[] | select(. != null)]')
all_nodes=$(jq -n --argjson a "$all_nodes" --argjson b "$page_nodes" '$a + $b')
local has_next end_cursor
has_next=$(echo "$response" | jq -r '.data.repositoriesByGhId[0].workspacesConnection.pageInfo.hasNextPage // false')
end_cursor=$(echo "$response" | jq -r '.data.repositoriesByGhId[0].workspacesConnection.pageInfo.endCursor // ""')
if [[ "$has_next" != "true" ]]; then
break
fi
if [[ -z "$end_cursor" || "$end_cursor" == "$last_cursor" ]]; then
warn "Workspace pagination cursor not advancing — bailing"
break
fi
last_cursor="$end_cursor"
cursor=$(jq -n --arg c "$end_cursor" '$c')
done
echo "$all_nodes"
}
# Get workspace ID for a repository (using GitHub ID).
#
# Workspace selection precedence:
# 1. ZH_WORKSPACE_NAME (set by `-w` / `--workspace` global flag) — exact
# case-insensitive match against the workspace name. Errors with the
# list of available workspaces if there's no match.
# 2. ZH_WORKSPACE (config-file value) — same resolution as above.
# 3. First workspace returned by the API (historical default).
#
# (1) and (2) are merged via ZH_WORKSPACE_NAME -> ZH_WORKSPACE precedence
# below. The Python `resolve_context` follows the same chain.
#
# Walks every page of `workspacesConnection` via zh_workspaces_fetch_all
# so name resolution finds workspaces beyond position 50.
get_workspace_id() {
local owner_repo="$1"
# Get GitHub repo ID
local gh_id
gh_id=$(resolve_gh_repo_id "$owner_repo") || \
error "Could not get GitHub repo ID for: $owner_repo (check the repo path and 'gh auth status')"
local workspace_nodes
workspace_nodes=$(zh_workspaces_fetch_all "$gh_id")
local node_count
node_count=$(echo "$workspace_nodes" | jq 'length')
if [[ "$node_count" -eq 0 ]]; then
error "$(zh_repo_access_hint "$owner_repo" "$gh_id")"
fi
# Resolve effective name: flag-set override beats env/config value
local effective_name="${ZH_WORKSPACE_NAME:-${ZH_WORKSPACE:-}}"
local workspace_id
if [[ -n "$effective_name" ]]; then
# Exact match on the workspace name (case-insensitive).
workspace_id=$(echo "$workspace_nodes" | jq -r --arg name "$effective_name" \
'[.[] | select((.name | ascii_downcase) == ($name | ascii_downcase))] | .[0].id // empty')
if [[ -z "$workspace_id" ]]; then
echo -e "${RED}Error:${NC} Workspace '${effective_name}' not found for ${owner_repo}." >&2
echo "" >&2
echo "Available workspaces:" >&2
echo "$workspace_nodes" | jq -r '.[] | " - \(.name)"' >&2
exit 1
fi
else
# Default: first workspace. Historical behaviour, preserved when
# neither -w nor ZH_WORKSPACE is set.
workspace_id=$(echo "$workspace_nodes" | jq -r '.[0].id // empty')
if [[ -z "$workspace_id" ]]; then
error "No workspace found for this repository"
fi
fi
echo "$workspace_id"
}
# Build ZenHub URL for an issue
# Format: https://app.zenhub.com/workspaces/<workspace-id>/issues/gh/<owner>/<repo>/<issue-number>
build_zenhub_url() {
local workspace_id="$1"
local owner_repo="$2"
local issue_num="$3"
echo "https://app.zenhub.com/workspaces/${workspace_id}/issues/gh/${owner_repo}/${issue_num}"
}
# =============================================================================
# Issue-type resolution (v1.9.0: the modern model)
# =============================================================================
#
# ZenHub removed Legacy Epics and ZenhubEpics in June 2025 ("Epics and Projects
# have been replaced with Issue Types and Sub-Issues"). The current model is a
# 5-level Issue Type hierarchy wired with Sub-Issues. assignableIssueTypes
# returns a union of GithubIssueType and ZenhubIssueType, each carrying a single
# `id` that both CreateIssueInput.issueTypeId and
# ChangeIssueTypeOfIssuesInput.issueTypeId accept. That unified id is the reason
# one mechanism covers every level (Initiative/Project/Epic are ZenhubIssueType;
# Bug/Feature/Task are GithubIssueType; Sub-task is ZenhubIssueType): the caller
# never has to branch on the subtype.
# Fetch the workspace's assignable issue types as a JSON array of
# {typename, id, name, level, disposition, isEnabled} on stdout.
# Echoes "[]" if none are returned. Data-driven: no per-noun hardcoding.
zh_fetch_issue_types() {
local owner_repo="$1"
local workspace_id="$2"
# Soft path: this feeds issue-type discovery, so degrade to "[]" rather
# than aborting. 2>/dev/null suppresses the helper's diagnostic to keep
# discovery quiet (the caller surfaces its own error if types are needed).
local gh_id
gh_id=$(resolve_gh_repo_id "$owner_repo" 2>/dev/null) || {
echo "[]"
return
}
local query='
query($ghIds: [Int!]!, $workspaceId: ID!) {
repositoriesByGhId(ghIds: $ghIds) {
assignableIssueTypes(workspaceId: $workspaceId, first: 100) {
nodes {
__typename
... on GithubIssueType { id name level disposition isEnabled }
... on ZenhubIssueType { id name level disposition isEnabled }
}
}
}
}'
local variables
variables=$(jq -n --argjson gh_id "$gh_id" --arg workspace_id "$workspace_id" \
'{ghIds: [$gh_id], workspaceId: $workspace_id}')
local response
response=$(zh_graphql "$query" "$variables")
# v1.9.1 item #4: belt-and-suspenders filter on isEnabled. The
# endpoint is named `assignableIssueTypes` and field-level inspection
# suggests the server already excludes disabled types, but
# zh_hierarchy_require_type's error message tells the user to
# "Enable it... then retry". If the server ever begins returning
# disabled-but-assignable rows (or a future workspace surfaces one),
# the "enable it" branch needs a way to actually fire. Keep the
# filter client-side so the contract on isEnabled is explicit
# regardless of server behavior.
echo "$response" | jq -c '
[ (.data.repositoriesByGhId[0].assignableIssueTypes.nodes // [])[]
| select(.isEnabled != false)
| {typename: .__typename, id: .id, name: .name, level: .level,
disposition: .disposition, isEnabled: .isEnabled} ]'
}
# Resolve an issue-type name (case-insensitive) to its id, using a pre-fetched
# types JSON array. Echoes the id, or empty if no match. Pure jq, no network.
#
# v1.9.1 item #4: zh_fetch_issue_types now filters out isEnabled=false rows
# before this lookup ever runs, so a disabled type cannot resolve to an id
# from here. The previous absence of that filter meant the "enable it in
# workspace settings" hint in zh_hierarchy_require_type could not fire even
# when the server returned a disabled row.
zh_issue_type_id_from() {
local types_json="$1"
local name="$2"
echo "$types_json" | jq -r --arg name "$name" \
'map(select((.name | ascii_downcase) == ($name | ascii_downcase))) | .[0].id // empty'
}
# Build a human-friendly "Available types: ..." list from a types JSON array.
zh_issue_type_names_from() {
local types_json="$1"
echo "$types_json" | jq -r '[.[].name] | join(", ")'
}
# Fetch the workspace's configured priorities as a JSON array of {id, name,
# color} on stdout. Echoes "[]" if none are configured.
zh_fetch_priorities() {
local workspace_id="$1"
local query='
query($workspaceId: ID!) {
workspace(id: $workspaceId) {
prioritiesConnection {
nodes { id name color }
}
}
}'
local variables
variables=$(jq -n --arg workspace_id "$workspace_id" '{workspaceId: $workspace_id}')
local response
response=$(zh_graphql "$query" "$variables")
echo "$response" | jq -c '.data.workspace.prioritiesConnection.nodes // []'
}
# Resolve a priority name (case-insensitive) to its id, using a pre-fetched
# priorities JSON array. Echoes the id, or empty if no match.
zh_priority_id_from() {
local priorities_json="$1"
local name="$2"
echo "$priorities_json" | jq -r --arg name "$name" \
'map(select((.name | ascii_downcase) == ($name | ascii_downcase))) | .[0].id // empty'
}
# =============================================================================
# Commands
# =============================================================================
cmd_help() {
cat << 'EOF'
zh - ZenHub CLI Tool
USAGE:
zh [-r owner/repo] [-w workspace] <command> [options]
GLOBAL OPTIONS (peeled off before the subcommand):
-r, --repo <owner/repo> Target a specific GitHub repository instead
of the one inferred from `git remote get-url
origin`. Can also be set via ZH_REPO in the
config file.
-w, --workspace <name> Target a specific workspace by name
(case-insensitive). If unset, the first
workspace returned by the API wins.
Can also be set via ZH_WORKSPACE.
COMMANDS:
issue <number> View issue details
Example: zh issue 42
mine [user] List issues assigned to you (or specified user)
Example: zh mine
Example: zh mine acme-user
board [--all] Show board overview (issue count per pipeline)
Excludes closed issues by default
count [pipeline] EXACT issue counts (from the API's totalCount —
never a truncated page). -q for a bare number,
--json for machine output, --all to include closed
Example: zh count "Product Backlog" -q
doctor Hierarchy health check: open issues under a CLOSED
parent (they roll up to nothing) and parent cycles
Exits 1 if problems are found
reparent <parent#> <child#> [...]
Move sub-issues to a new parent, detaching them from
their current one. --dry-run shows the plan only
A CLOSED destination is refused; override with
--allow-closed-parent
Example: zh reparent 586 60 72 73 --dry-run
pipeline <name> [--all] List issues in a specific pipeline
Excludes closed issues by default
Example: zh pipeline "In Progress"
Example: zh pipeline todo --all
pipeline create|move|rename|delete
Manage pipelines; see zh pipeline --help
Use zh pipeline -- create to view a verb-named pipeline
pipelines [repo] List pipeline names for a workspace
Example: zh pipelines
move <issue> <pipeline> Move an issue to a pipeline
Example: zh move 42 "In Progress"
Example: zh move #42 done
reorder <issue> <pos> Reorder an issue within its pipeline
Example: zh reorder 42 top
Example: zh reorder 42 bottom
estimate <issue> <pts> Set story point estimate
Example: zh estimate 42 3
Example: zh estimate 42 clear
assign <issue> <user> Assign a user to an issue
Example: zh assign 42 johndoe
unassign <issue> [user] Remove assignee(s) from an issue
Example: zh unassign 42 johndoe (remove one)
Example: zh unassign 42 (remove all)
create <title> [opts] Create a new issue
-t, --type <type> Issue type
-l, --labels <labels> Comma-separated labels
-a, --assignee <user> Assign to user
-p, --pipeline <name> Place in pipeline
-e, --estimate <pts> Story points
-b, --body <text> Short description
-f, --file <path> Read description from file
--stdin Read description from stdin
comment <issue> [opts] Add a comment to an issue
-m, --message <text> Comment text
-f, --file <path> Read from file
--stdin Read from stdin
Example: zh comment 42 "Fixed in PR #99"
Example: zh comment 42 -f notes.md
attach <issue> Open issue in browser to add attachments
(GitHub API doesn't support file uploads)
Example: zh attach 42
close <issue> [comment] Close an issue (moves to Closed pipeline)
Example: zh close 42
Example: zh close 42 "Fixed in PR #99"
reopen <issue> Reopen a closed issue
Example: zh reopen 42
delete <issue> [-y] PERMANENTLY delete a GitHub issue via gh (DANGER:
prefer 'close'; needs admin/triage). Removes it
from the ZenHub board too; also covers sub-issues.
Prompts for confirmation when interactive; -y/--yes
skips it. Epics are issues now, so delete one the
same way: zh delete <issue#>.
Example: zh delete 42
block <issue> <blocker> Set issue as blocked by another
Example: zh block 123 456
(123 is blocked by 456)
unblock <issue> <blocker> Remove a blocking dependency
Example: zh unblock 123 456
(123 is no longer blocked by 456)
priority <issue> [name] Set or view issue priority (name-resolved)
Priorities are workspace-defined; discover with
'zh priorities'. The name is matched case-insensitively.
Example: zh priority 42 "High priority"
Example: zh priority 42 clear
Example: zh priority 42 (view only)
priorities List the workspace's configured priorities
types List assignable issue types (name/level/disposition)
type <issue> <name> Change an existing issue's type
Example: zh type 42 Epic
labels List available labels
users List users who can be assigned to issues
Example: zh users
workspaces List available workspaces for current repo
PLANNING NOUNS (issue-type + sub-issue model):
epic <subcommand> Manage Epic issues (issue-type Epic, level 3)
Subcommands:
list List Epic issues
show <issue#> Show issue + sub-issues
create "Title" [-d body] [-l ...] [-p pipeline] [--json|-q]
update <issue#> [-t ...] [-d ...] Edit title and/or body
add <parent#> <issue#> [...] Attach sub-issues
remove <parent#> <issue#> [...] Detach sub-issues
close <issue#> [comment] Close the issue
reopen <issue#> Reopen the issue
Example: zh epic create "Auth Service" -l backend,auth
Example: zh epic add 42 369 370
initiative <subcommand> Same surface, issue-type Initiative (level 1)
project <subcommand> Same surface, issue-type Project (level 2)
subtask <subcommand> Same surface, issue-type Sub-task (level 5)
(level-4 Bug/Feature/Task use 'zh create -t <type>')
subissue <subcommand> Manage sub-issues (Issue → Sub-issue hierarchy tier)
Subcommands:
add <parent#> <child#> [...] Link issues as sub-issues
remove <parent#> <child#> [...] Unlink sub-issues
list <parent#> List sub-issues of a parent
reorder <child#> <position> Reorder sub-issue among siblings
Position: top | bottom |
after <sib#> | before <sib#>
A CLOSED parent is refused on add; override with
--allow-closed-parent
Example: zh subissue add 42 100 101
Example: zh subissue list 42
Example: zh subissue reorder 100 after 101
(aliases: sub, child, children)
sprints [--all] List sprints in workspace
Shows open sprints by default; ● marks the active sprint
Example: zh sprints
Example: zh sprints --all
(alias: sp)
sprint <name> [opts] View sprint details and issues
Special names: 'current' or 'active' for the active sprint
Options:
--no-urls Compact output (no per-issue URLs)
Example: zh sprint "Sprint 5"
Example: zh sprint current
Example: zh sprint # (defaults to current)
sprint add <name> <issue#> [<issue#> ...]
Add one or more issues to a sprint
Example: zh sprint add "Sprint 5" 42 43
Example: zh sprint add current 42
(top-level alias: sa)
sprint remove <name> <issue#> [<issue#> ...]
Remove one or more issues from a sprint
Example: zh sprint remove "Sprint 5" 42
Example: zh sprint rm current 42 43
(top-level alias: sr)
releases [--all|--closed] [--json]
List releases in workspace (open by default)
Example: zh releases --all
(aliases: rels, release list)
release <subcommand> Manage releases (titles match case-insensitively;