-
Notifications
You must be signed in to change notification settings - Fork 1
/
ok.sh
2584 lines (2275 loc) · 65.8 KB
/
ok.sh
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
#!/usr/bin/env sh
# # A GitHub API client library written in POSIX sh
#
# https://github.com/whiteinge/ok.sh
# BSD licensed.
#
# ## Requirements
#
# * A POSIX environment (tested against Busybox v1.19.4)
# * curl (tested against 7.32.0)
#
# ## Optional requirements
#
# * jq <http://stedolan.github.io/jq/> (tested against 1.3)
# If jq is not installed commands will output raw JSON; if jq is installed
# the output will be formatted and filtered for use with other shell tools.
#
# ## Setup
#
# Authentication credentials are read from a `$HOME/.netrc` file on UNIX
# machines or a `_netrc` file in `%HOME%` for UNIX environments under Windows.
# [Generate the token on GitHub](https://github.com/settings/tokens) under
# "Account Settings -> Applications".
# Restrict permissions on that file with `chmod 600 ~/.netrc`!
#
# machine api.github.com
# login <username>
# password <token>
#
# machine uploads.github.com
# login <username>
# password <token>
#
# Or set an environment `GITHUB_TOKEN=token`
#
# ## Configuration
#
# The following environment variables may be set to customize ${NAME}.
#
# * OK_SH_URL=${OK_SH_URL}
# Base URL for GitHub or GitHub Enterprise.
# * OK_SH_ACCEPT=${OK_SH_ACCEPT}
# The 'Accept' header to send with each request.
# * OK_SH_JQ_BIN=${OK_SH_JQ_BIN}
# The name of the jq binary, if installed.
# * OK_SH_VERBOSE=${OK_SH_VERBOSE}
# The debug logging verbosity level. Same as the verbose flag.
# * OK_SH_RATE_LIMIT=${OK_SH_RATE_LIMIT}
# Output current GitHub rate limit information to stderr.
# * OK_SH_DESTRUCTIVE=${OK_SH_DESTRUCTIVE}
# Allow destructive operations without prompting for confirmation.
# * OK_SH_MARKDOWN=${OK_SH_MARKDOWN}
# Output some text in Markdown format.
export NAME=$(basename "$0")
export VERSION='0.5.1'
export OK_SH_URL=${OK_SH_URL:-'https://api.github.com'}
export OK_SH_ACCEPT=${OK_SH_ACCEPT:-'application/vnd.github.v3+json'}
export OK_SH_JQ_BIN="${OK_SH_JQ_BIN:-jq}"
export OK_SH_VERBOSE="${OK_SH_VERBOSE:-0}"
export OK_SH_RATE_LIMIT="${OK_SH_RATE_LIMIT:-0}"
export OK_SH_DESTRUCTIVE="${OK_SH_DESTRUCTIVE:-0}"
export OK_SH_MARKDOWN="${OK_SH_MARKDOWN:-0}"
# Detect if jq is installed.
command -v "$OK_SH_JQ_BIN" 1>/dev/null 2>/dev/null
NO_JQ=$?
# Customizable logging output.
exec 4>/dev/null
exec 5>/dev/null
exec 6>/dev/null
export LINFO=4 # Info-level log messages.
export LDEBUG=5 # Debug-level log messages.
export LSUMMARY=6 # Summary output.
# Generate a carriage return so we can match on it.
# Using a variable because these are tough to specify in a portable way.
crlf=$(printf '\r\n')
# ## Main
# Generic functions not necessarily specific to working with GitHub.
# ### Help
# Functions for fetching and formatting help text.
_cols() {
sort | awk '
{ w[NR] = $0 }
END {
cols = 3
per_col = sprintf("%.f", NR / cols + 0.5) # Round up if decimal.
for (i = 1; i < per_col + 1; i += 1) {
for (j = 0; j < cols; j += 1) {
printf("%-24s", w[i + per_col * j])
}
printf("\n")
}
}
'
}
_links() { awk '{ print "* [" $0 "](#" $0 ")" }'; }
_funcsfmt() { if [ "$OK_SH_MARKDOWN" -eq 0 ]; then _cols; else _links; fi; }
help() {
# Output the help text for a command
#
# Usage:
#
# help commandname
#
# Positional arguments
#
local fname="$1"
# Function name to search for; if omitted searches whole file.
# Short-circuit if only producing help for a single function.
if [ $# -gt 0 ]; then
awk -v fname="^$fname\\\(\\\) \\\{$" '$0 ~ fname, /^}/ { print }' "$0" \
| _helptext
return
fi
_helptext < "$0"
printf '\n'
help __main
printf '\n'
printf '## Table of Contents\n'
printf '\n### Utility and request/response commands\n\n'
_all_funcs public=0 | _funcsfmt
printf '\n### GitHub commands\n\n'
_all_funcs private=0 | _funcsfmt
printf '\n## Commands\n\n'
for cmd in $(_all_funcs public=0); do
printf '### %s\n\n' "$cmd"
help "$cmd"
printf '\n'
done
for cmd in $(_all_funcs private=0); do
printf '### %s\n\n' "$cmd"
help "$cmd"
printf '\n'
done
}
_all_funcs() {
# List all functions found in the current file in the order they appear
#
# Keyword arguments
#
local public=1
# `0` do not output public functions.
local private=1
# `0` do not output private functions.
for arg in "$@"; do
case $arg in
(public=*) public="${arg#*=}";;
(private=*) private="${arg#*=}";;
esac
done
awk -v public="$public" -v private="$private" '
$1 !~ /^__/ && /^[a-zA-Z0-9_]+\s*\(\)/ {
sub(/\(\)$/, "", $1)
if (!public && substr($1, 1, 1) != "_") next
if (!private && substr($1, 1, 1) == "_") next
print $1
}
' "$0"
}
__main() {
# ## Usage
#
# `${NAME} [<flags>] (command [<arg>, <name=value>...])`
#
# ${NAME} -h # Short, usage help text.
# ${NAME} help # All help text. Warning: long!
# ${NAME} help command # Command-specific help text.
# ${NAME} command # Run a command with and without args.
# ${NAME} command foo bar baz=Baz qux='Qux arg here'
#
# Flag | Description
# ---- | -----------
# -V | Show version.
# -h | Show this screen.
# -j | Output raw JSON; don't process with jq.
# -q | Quiet; don't print to stdout.
# -r | Print current GitHub API rate limit to stderr.
# -v | Logging output; specify multiple times: info, debug, trace.
# -x | Enable xtrace debug logging.
# -y | Answer 'yes' to any prompts.
#
# Flags _must_ be the first argument to `${NAME}`, before `command`.
local cmd
local ret
local opt
local OPTARG
local OPTIND
local quiet=0
local temp_dir="${TMPDIR-/tmp}/${NAME}.${$}.$(awk \
'BEGIN {srand(); printf "%d\n", rand() * 10^10}')"
local summary_fifo="${temp_dir}/oksh_summary.fifo"
# shellcheck disable=SC2154
trap '
excode=$?; trap - EXIT;
exec 4>&-
exec 5>&-
exec 6>&-
rm -rf '"$temp_dir"'
exit $excode
' INT TERM EXIT
while getopts Vhjqrvxy opt; do
case $opt in
V) printf 'Version: %s\n' $VERSION
exit;;
h) help __main
printf '\nAvailable commands:\n\n'
_all_funcs private=0 | _cols
printf '\n'
exit;;
j) NO_JQ=1;;
q) quiet=1;;
r) OK_SH_RATE_LIMIT=1;;
v) OK_SH_VERBOSE=$(( OK_SH_VERBOSE + 1 ));;
x) set -x;;
y) OK_SH_DESTRUCTIVE=1;;
esac
done
shift $(( OPTIND - 1 ))
if [ -z "$1" ] ; then
printf 'No command given. Available commands:\n\n%s\n' \
"$(_all_funcs private=0 | _cols)" 1>&2
exit 1
fi
[ $OK_SH_VERBOSE -gt 0 ] && exec 4>&2
[ $OK_SH_VERBOSE -gt 1 ] && exec 5>&2
if [ $quiet -eq 1 ]; then
exec 1>/dev/null 2>/dev/null
fi
if [ "$OK_SH_RATE_LIMIT" -eq 1 ] ; then
mkdir -m 700 "$temp_dir" || {
printf 'failed to create temp_dir\n' >&2; exit 1;
}
mkfifo "$summary_fifo"
# Hold the fifo open so it will buffer input until emptied.
exec 6<>"$summary_fifo"
fi
# Run the command.
cmd="$1" && shift
_log debug "Running command ${cmd}."
"$cmd" "$@"
ret=$?
_log debug "Command ${cmd} exited with ${?}."
# Output any summary messages.
if [ "$OK_SH_RATE_LIMIT" -eq 1 ] ; then
cat "$summary_fifo" 1>&2 &
exec 6>&-
fi
exit $ret
}
_log() {
# A lightweight logging system based on file descriptors
#
# Usage:
#
# _log debug 'Starting the combobulator!'
#
# Positional arguments
#
local level="${1:?Level is required.}"
# The level for a given log message. (info or debug)
local message="${2:?Message is required.}"
# The log message.
shift 2
local lname
case "$level" in
info) lname='INFO'; level=$LINFO ;;
debug) lname='DEBUG'; level=$LDEBUG ;;
*) printf 'Invalid logging level: %s\n' "$level" ;;
esac
printf '%s %s: %s\n' "$NAME" "$lname" "$message" 1>&$level
}
_helptext() {
# Extract contiguous lines of comments and function params as help text
#
# Indentation will be ignored. She-bangs will be ignored. Local variable
# declarations and their default values can also be pulled in as
# documentation. Exits upon encountering the first blank line.
#
# Exported environment variables can be used for string interpolation in
# the extracted commented text.
#
# Input
#
# * (stdin)
# The text of a function body to parse.
awk '
NR != 1 && /^\s*#/ {
line=$0
while(match(line, "[$]{[^}]*}")) {
var=substr(line, RSTART+2, RLENGTH -3)
gsub("[$]{"var"}", ENVIRON[var], line)
}
gsub(/^\s*#\s?/, "", line)
print line
}
/^\s*local/ {
sub(/^\s*local /, "")
sub(/\$\{/, "$", $0)
sub(/:.*}/, "", $0)
print "* `" $0 "`\n"
}
!NF { exit }'
}
# ### Request-response
# Functions for making HTTP requests and processing HTTP responses.
_format_json() {
# Create formatted JSON from name=value pairs
#
# Usage:
# ```
# ok.sh _format_json foo=Foo bar=123 baz=true qux=Qux=Qux quux='Multi-line
# string' quuz=\'5.20170918\' \
# corge="$(ok.sh _format_json grault=Grault)" \
# garply="$(ok.sh _format_json -a waldo true 3)"
# ```
#
# Return:
# ```
# {
# "garply": [
# "waldo",
# true,
# 3
# ],
# "foo": "Foo",
# "corge": {
# "grault": "Grault"
# },
# "baz": true,
# "qux": "Qux=Qux",
# "quux": "Multi-line\nstring",
# "quuz": "5.20170918",
# "bar": 123
# }
# ```
#
# Tries not to quote numbers, booleans, nulls, or nested structures.
# Note, nested structures must be quoted since the output contains spaces.
#
# The `-a` option will create an array instead of an object. This option
# must come directly after the _format_json command and before any
# operands. E.g., `_format_json -a foo bar baz`.
#
# If jq is installed it will also validate the output.
#
# Positional arguments
#
# * $1 - $9
#
# Each positional arg must be in the format of `name=value` which will be
# added to a single, flat JSON object.
local opt
local OPTIND
local is_array=0
local use_env=1
while getopts a opt; do
case $opt in
a) is_array=1; unset use_env;;
esac
done
shift $(( OPTIND - 1 ))
_log debug "Formatting ${#} parameters as JSON."
env -i -- ${use_env+"$@"} awk -v is_array="$is_array" '
function isnum(x){ return (x == x + 0) }
function isnull(x){ return (x == "null" ) }
function isbool(x){ if (x == "true" || x == "false") return 1 }
function isnested(x) { if (substr(x, 0, 1) == "[" \
|| substr(x, 0, 1) == "{") return 1 }
function castOrQuote(val) {
if (!isbool(val) && !isnum(val) && !isnull(val) && !isnested(val)) {
sub(/^('\''|")/, "", val) # Remove surrounding quotes
sub(/('\''|")$/, "", val)
gsub(/"/, "\\\"", val) # Escape double-quotes.
gsub(/\n/, "\\n", val) # Replace newlines with \n text.
val = "\"" val "\""
return val
} else {
return val
}
}
BEGIN {
printf("%s", is_array ? "[" : "{")
for (i = 1; i < length(ARGV); i += 1) {
arg = ARGV[i]
if (is_array == 1) {
val = castOrQuote(arg)
printf("%s%s", sep, val)
} else {
name = substr(arg, 0, index(arg, "=") - 1)
val = castOrQuote(ENVIRON[name])
printf("%s\"%s\": %s", sep, name, val)
}
sep = ", "
ARGV[i] = ""
}
printf("%s", is_array ? "]" : "}")
}' "$@"
}
_format_urlencode() {
# URL encode and join name=value pairs
#
# Usage:
# ```
# _format_urlencode foo='Foo Foo' bar='<Bar>&/Bar/'
# ```
#
# Return:
# ```
# foo=Foo%20Foo&bar=%3CBar%3E%26%2FBar%2F
# ```
#
# Ignores pairs if the value begins with an underscore.
_log debug "Formatting ${#} parameters as urlencoded"
env -i -- "$@" awk '
function escape(str, c, i, len, res) {
len = length(str)
res = ""
for (i = 1; i <= len; i += 1) {
c = substr(str, i, 1);
if (c ~ /[0-9A-Za-z]/)
res = res c
else
res = res "%" sprintf("%02X", ord[c])
}
return res
}
BEGIN {
for (i = 0; i <= 255; i += 1) ord[sprintf("%c", i)] = i;
for (j = 1; j < length(ARGV); j += 1) {
arg = ARGV[j]
name = substr(arg, 0, index(arg, "=") - 1)
if (substr(name, 1, 1) == "_") continue
val = ENVIRON[name]
printf("%s%s=%s", sep, name, escape(val))
sep = "&"
ARGV[j] = ""
}
}' "$@"
}
_filter_json() {
# Filter JSON input using jq; outputs raw JSON if jq is not installed
#
# Usage:
#
# printf '[{"foo": "One"}, {"foo": "Two"}]' | \
# ok.sh _filter_json '.[] | "\(.foo)"'
#
# * (stdin)
# JSON input.
local _filter="$1"
# A string of jq filters to apply to the input stream.
_log debug 'Filtering JSON.'
if [ $NO_JQ -ne 0 ] ; then
_log debug 'Bypassing jq processing.'
cat
return
fi
"${OK_SH_JQ_BIN}" -c -r "${_filter}"
[ $? -eq 0 ] || printf 'jq parse error; invalid JSON.\n' 1>&2
}
_get_mime_type() {
# Guess the mime type for a file based on the file extension
#
# Usage:
#
# local mime_type
# _get_mime_type "foo.tar"; printf 'mime is: %s' "$mime_type"
#
# Sets the global variable `mime_type` with the result. (If this function
# is called from within a function that has declared a local variable of
# that name it will update the local copy and not set a global.)
#
# Positional arguments
#
local filename="${1:?Filename is required.}"
# The full name of the file, with extension.
# Taken from Apache's mime.types file (public domain).
case "$filename" in
*.bz2) mime_type=application/x-bzip2 ;;
*.exe) mime_type=application/x-msdownload ;;
*.tar.gz | *.gz | *.tgz) mime_type=application/x-gzip ;;
*.jpg | *.jpeg | *.jpe | *.jfif) mime_type=image/jpeg ;;
*.json) mime_type=application/json ;;
*.pdf) mime_type=application/pdf ;;
*.png) mime_type=image/png ;;
*.rpm) mime_type=application/x-rpm ;;
*.svg | *.svgz) mime_type=image/svg+xml ;;
*.tar) mime_type=application/x-tar ;;
*.txt) mime_type=text/plain ;;
*.yaml) mime_type=application/x-yaml ;;
*.apk) mime_type=application/vnd.android.package-archive ;;
*.zip) mime_type=application/zip ;;
*.jar) mime_type=application/java-archive ;;
*.war) mime_type=application/zip ;;
esac
_log debug "Guessed mime type of '${mime_type}' for '${filename}'."
}
_get_confirm() {
# Prompt the user for confirmation
#
# Usage:
#
# local confirm; _get_confirm
# [ "$confirm" -eq 1 ] && printf 'Good to go!\n'
#
# If global confirmation is set via `$OK_SH_DESTRUCTIVE` then the user
# is not prompted. Assigns the user's confirmation to the `confirm` global
# variable. (If this function is called within a function that has a local
# variable of that name, the local variable will be updated instead.)
#
# Positional arguments
#
local message="${1:-Are you sure?}"
# The message to prompt the user with.
local answer
if [ "$OK_SH_DESTRUCTIVE" -eq 1 ] ; then
confirm=$OK_SH_DESTRUCTIVE
return
fi
printf '%s ' "$message"
read -r answer
! printf '%s\n' "$answer" | grep -Eq "$(locale yesexpr)"
confirm=$?
}
_opts_filter() {
# Extract common jq filter keyword options and assign to vars
#
# Usage:
#
# local filter
# _opts_filter "$@"
for arg in "$@"; do
case $arg in
(_filter=*) _filter="${arg#*=}";;
esac
done
}
_opts_pagination() {
# Extract common pagination keyword options and assign to vars
#
# Usage:
#
# local _follow_next
# _opts_pagination "$@"
for arg in "$@"; do
case $arg in
(_follow_next=*) _follow_next="${arg#*=}";;
(_follow_next_limit=*) _follow_next_limit="${arg#*=}";;
esac
done
}
_opts_qs() {
# Extract common query string keyword options and assign to vars
#
# Usage:
#
# local qs
# _opts_qs "$@"
# _get "/some/path${qs}"
local querystring=$(_format_urlencode "$@")
qs="${querystring:+?$querystring}"
}
_request() {
# A wrapper around making HTTP requests with curl
#
# Usage:
# ```
# # Get JSON for all issues:
# _request /repos/saltstack/salt/issues
#
# # Send a POST request; parse response using jq:
# printf '{"title": "%s", "body": "%s"}\n' "Stuff" "Things" \
# | _request /some/path | jq -r '.[url]'
#
# # Send a PUT request; parse response using jq:
# printf '{"title": "%s", "body": "%s"}\n' "Stuff" "Things" \
# | _request /repos/:owner/:repo/issues method=PUT | jq -r '.[url]'
#
# # Send a conditional-GET request:
# _request /users etag=edd3a0d38d8c329d3ccc6575f17a76bb
# ```
#
# Input
#
# * (stdin)
# Data that will be used as the request body.
#
# Positional arguments
#
local path="${1:?Path is required.}"
# The URL path for the HTTP request.
# Must be an absolute path that starts with a `/` or a full URL that
# starts with http(s). Absolute paths will be append to the value in
# `$OK_SH_URL`.
#
# Keyword arguments
#
local method='GET'
# The method to use for the HTTP request.
local content_type='application/json'
# The value of the Content-Type header to use for the request.
local etag
# An optional Etag to send as the If-None-Match header.
shift 1
local cmd
local arg
local has_stdin
local trace_curl
case $path in
(http*) : ;;
*) path="${OK_SH_URL}${path}" ;;
esac
for arg in "$@"; do
case $arg in
(method=*) method="${arg#*=}";;
(content_type=*) content_type="${arg#*=}";;
(etag=*) etag="${arg#*=}";;
esac
done
case "$method" in
POST | PUT | PATCH) has_stdin=1;;
esac
[ $OK_SH_VERBOSE -eq 3 ] && trace_curl=1
[ "$OK_SH_VERBOSE" -eq 1 ] && set -x
# shellcheck disable=SC2086
curl -nsSig \
-H "Accept: ${OK_SH_ACCEPT}" \
-H "Content-Type: ${content_type}" \
${GITHUB_TOKEN:+-H "Authorization: token ${GITHUB_TOKEN}"} \
${etag:+-H "If-None-Match: \"${etag}\""} \
${has_stdin:+--data-binary @-} \
${trace_curl:+--trace-ascii /dev/stderr} \
-X "${method}" \
"${path}"
set +x
}
_response() {
# Process an HTTP response from curl
#
# Output only headers of interest followed by the response body. Additional
# processing is performed on select headers to make them easier to parse
# using shell tools.
#
# Usage:
# ```
# # Send a request; output the response and only select response headers:
# _request /some/path | _response status_code ETag Link_next
#
# # Make request using curl; output response with select response headers;
# # assign response headers to local variables:
# curl -isS example.com/some/path | _response status_code status_text | {
# local status_code status_text
# read -r status_code
# read -r status_text
# }
# ```
#
# Header reformatting
#
# * HTTP Status
#
# The HTTP line is split into separate `http_version`, `status_code`, and
# `status_text` variables.
#
# * ETag
#
# The surrounding quotes are removed.
#
# * Link
#
# Each URL in the Link header is expanded with the URL type appended to
# the name. E.g., `Link_first`, `Link_last`, `Link_next`.
#
# Positional arguments
#
# * $1 - $9
#
# Each positional arg is the name of an HTTP header. Each header value is
# output in the same order as each argument; each on a single line. A
# blank line is output for headers that cannot be found.
local hdr
local val
local http_version
local status_code=100
local status_text
local headers output
_log debug 'Processing response.'
while [ "${status_code}" = "100" ]; do
read -r http_version status_code status_text
status_text="${status_text%${crlf}}"
http_version="${http_version#HTTP/}"
_log debug "Response status is: ${status_code} ${status_text}"
if [ "${status_code}" = "100" ]; then
_log debug "Ignoring response '${status_code} ${status_text}', skipping to real response."
while IFS=": " read -r hdr val; do
# Headers stop at the first blank line.
[ "$hdr" = "$crlf" ] && break
val="${val%${crlf}}"
_log debug "Unexpected additional header: ${hdr}: ${val}"
done
fi
done
headers="http_version: ${http_version}
status_code: ${status_code}
status_text: ${status_text}
"
while IFS=": " read -r hdr val; do
# Headers stop at the first blank line.
[ "$hdr" = "$crlf" ] && break
val="${val%${crlf}}"
# Process each header; reformat some to work better with sh tools.
case "$hdr" in
# Update the GitHub rate limit trackers.
X-RateLimit-Remaining)
printf 'GitHub remaining requests: %s\n' "$val" 1>&$LSUMMARY ;;
X-RateLimit-Reset)
awk -v gh_reset="$val" 'BEGIN {
srand(); curtime = srand()
print "GitHub seconds to reset: " gh_reset - curtime
}' 1>&$LSUMMARY ;;
# Remove quotes from the etag header.
ETag) val="${val#\"}"; val="${val%\"}" ;;
# Split the URLs in the Link header into separate pseudo-headers.
Link) headers="${headers}$(printf '%s' "$val" | awk '
BEGIN { RS=", "; FS="; "; OFS=": " }
{
sub(/^rel="/, "", $2); sub(/"$/, "", $2)
sub(/^ *</, "", $1); sub(/>$/, "", $1)
print "Link_" $2, $1
}')
" # need trailing newline
;;
esac
headers="${headers}${hdr}: ${val}
" # need trailing newline
done
# Output requested headers in deterministic order.
for arg in "$@"; do
_log debug "Outputting requested header '${arg}'."
output=$(printf '%s' "$headers" | while IFS=": " read -r hdr val; do
[ "$hdr" = "$arg" ] && printf '%s' "$val"
done)
printf '%s\n' "$output"
done
# Output the response body.
cat
}
_get() {
# A wrapper around _request() for common GET patterns
#
# Will automatically follow 'next' pagination URLs in the Link header.
#
# Usage:
#
# _get /some/path
# _get /some/path _follow_next=0
# _get /some/path _follow_next_limit=200 | jq -c .
#
# Positional arguments
#
local path="${1:?Path is required.}"
# The HTTP path or URL to pass to _request().
#
# Keyword arguments
#
# * _follow_next=1
#
# Automatically look for a 'Links' header and follow any 'next' URLs.
#
# * _follow_next_limit=50
#
# Maximum number of 'next' URLs to follow before stopping.
shift 1
local status_code
local status_text
local next_url
# If the variable is unset or empty set it to a default value. Functions
# that call this function can pass these parameters in one of two ways:
# explicitly as a keyword arg or implicitly by setting variables of the same
# names within the local scope.
# shellcheck disable=SC2086
if [ -z ${_follow_next+x} ] || [ -z "${_follow_next}" ]; then
local _follow_next=1
fi
# shellcheck disable=SC2086
if [ -z ${_follow_next_limit+x} ] || [ -z "${_follow_next_limit}" ]; then
local _follow_next_limit=50
fi
_opts_pagination "$@"
_request "$path" | _response status_code status_text Link_next | {
read -r status_code
read -r status_text
read -r next_url
case "$status_code" in
20*) : ;;
4*) printf 'Client Error: %s %s\n' \
"$status_code" "$status_text" 1>&2; exit 1 ;;
5*) printf 'Server Error: %s %s\n' \
"$status_code" "$status_text" 1>&2; exit 1 ;;
esac
# Output response body.
cat
[ "$_follow_next" -eq 1 ] || return
_log info "Remaining next link follows: ${_follow_next_limit}"
if [ -n "$next_url" ] && [ $_follow_next_limit -gt 0 ] ; then
_follow_next_limit=$(( _follow_next_limit - 1 ))
_get "$next_url" "_follow_next_limit=${_follow_next_limit}"
fi
}
}
_post() {
# A wrapper around _request() for common POST / PUT patterns
#
# Usage:
#
# _format_json foo=Foo bar=Bar | _post /some/path
# _format_json foo=Foo bar=Bar | _post /some/path method='PUT'
# _post /some/path filename=somearchive.tar
# _post /some/path filename=somearchive.tar mime_type=application/x-tar
# _post /some/path filename=somearchive.tar \
# mime_type=$(file -b --mime-type somearchive.tar)
#
# Input
#
# * (stdin)
# Optional. See the `filename` argument also.
# Data that will be used as the request body.
#
# Positional arguments
#
local path="${1:?Path is required.}"
# The HTTP path or URL to pass to _request().
#
# Keyword arguments
#
local method='POST'
# The method to use for the HTTP request.
local filename
# Optional. See the `stdin` option above also.
# Takes precedence over any data passed as stdin and loads a file off the
# file system to serve as the request body.
local mime_type
# The value of the Content-Type header to use for the request.
# If the `filename` argument is given this value will be guessed from the
# file extension. If the `filename` argument is not given (i.e., using
# stdin) this value defaults to `application/json`. Specifying this
# argument overrides all other defaults or guesses.
shift 1
for arg in "$@"; do
case $arg in
(method=*) method="${arg#*=}";;
(filename=*) filename="${arg#*=}";;
(mime_type=*) mime_type="${arg#*=}";;
esac
done
# Make either the file or stdin available as fd7.
if [ -n "$filename" ] ; then
if [ -r "$filename" ] ; then
_log debug "Using '${filename}' as POST data."
[ -n "$mime_type" ] || _get_mime_type "$filename"
: ${mime_type:?The MIME type could not be guessed.}
exec 7<"$filename"
else
printf 'File could not be found or read.\n' 1>&2
exit 1
fi
else
_log debug "Using stdin as POST data."
mime_type='application/json'
exec 7<&0
fi
_request "$path" method="$method" content_type="$mime_type" 0<&7 \
| _response status_code status_text \
| {
read -r status_code
read -r status_text
case "$status_code" in
20*) : ;;
4*) printf 'Client Error: %s %s\n' \
"$status_code" "$status_text" 1>&2; exit 1 ;;
5*) printf 'Server Error: %s %s\n' \
"$status_code" "$status_text" 1>&2; exit 1 ;;
esac
# Output response body.
cat
}
}
_delete() {
# A wrapper around _request() for common DELETE patterns
#
# Usage: