-
Notifications
You must be signed in to change notification settings - Fork 1
/
git-clone-completion.bash
executable file
·1592 lines (1395 loc) · 45.4 KB
/
git-clone-completion.bash
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
# intelligent bash completion support for 'git clone' from github
#
# Copyright (C) 2019 Mario Juric <[email protected]>
# and others, as specified.
#
# Distributed under the GNU General Public License, version 2.0.
#
# This script complements the autocompletion scripts that ship
# with git, but can be used standalone as well.
#
#
# configuration
#
__gg_setup()
{
local xdg_config_home=${XDG_CONFIG_HOME:-$HOME/.config}
local xdg_cache_home=${XDG_CACHE_HOME:-$HOME/.cache}
GG_CFGDIR=${GG_CFGDIR:-$xdg_config_home/git-clone-completion}
GG_CACHEDIR=${GG_CACHEDIR:-$xdg_cache_home/git-clone-completion}
}
__gg_setup
unset -f __gg_setup
#############################
# #
# Completion utilities #
# #
#############################
####
# The following utility functions have been based on code from:
#
# bash/zsh completion support for core Git.
#
# Copyright (C) 2006,2007 Shawn O. Pearce <[email protected]>
# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/).
# Distributed under the GNU General Public License, version 2.0.
#
# parts of which were itself based on code from:
#
# bash_completion - programmable completion functions for bash 3.2+
#
# Copyright © 2006-2008, Ian Macdonald <[email protected]>
# © 2009-2010, Bash Completion Maintainers
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
#
# The latest version of this software can be obtained here:
#
# http://bash-completion.alioth.debian.org/
#
# RELEASE: 2.x
__mj_reassemble_comp_words_by_ref()
{
local exclude i j first
# Which word separators to exclude?
exclude="${1//[^$COMP_WORDBREAKS]}"
cword_=$COMP_CWORD
if [ -z "$exclude" ]; then
words_=("${COMP_WORDS[@]}")
return
fi
# List of word completion separators has shrunk;
# re-assemble words to complete.
for ((i=0, j=0; i < ${#COMP_WORDS[@]}; i++, j++)); do
# Append each nonempty word consisting of just
# word separator characters to the current word.
first=t
while
[ $i -gt 0 ] &&
[ -n "${COMP_WORDS[$i]}" ] &&
# word consists of excluded word separators
[ "${COMP_WORDS[$i]//[^$exclude]}" = "${COMP_WORDS[$i]}" ]
do
# Attach to the previous token,
# unless the previous token is the command name.
if [ $j -ge 2 ] && [ -n "$first" ]; then
((j--))
fi
first=
words_[$j]=${words_[j]}${COMP_WORDS[i]}
if [ $i = "$COMP_CWORD" ]; then
cword_=$j
fi
if ((i < ${#COMP_WORDS[@]} - 1)); then
((i++))
else
# Done.
return
fi
done
words_[$j]=${words_[j]}${COMP_WORDS[i]}
if [ $i = "$COMP_CWORD" ]; then
cword_=$j
fi
done
}
#
# copied from a version of git-completion.bash
#
_mj_get_comp_words_by_ref ()
{
local exclude cur_ words_ cword_
if [ "$1" = "-n" ]; then
exclude=$2
shift 2
fi
__mj_reassemble_comp_words_by_ref "$exclude"
cur_=${words_[cword_]}
# shellcheck disable=SC2034
while [ $# -gt 0 ]; do
case "$1" in
cur)
cur=$cur_
;;
prev)
prev=${words_[$cword_-1]}
;;
words)
words=("${words_[@]}")
;;
cword)
cword=$cword_
;;
esac
shift
done
}
# #
############################################################
#
# Get a list of positional arguments, and the index of the
# current word within that list, if the current word is a
# positional argument.
#
# If $cword is a positional argument sets %_argidx to its index
# ignoring any options that may have been specified before it.
# If $cword is not a positional argument (e.g., it's an option
# or an option's argument), sets %_argidx to empty
#
# arguments: list of options that admit an argument, suffixed by '='
#
# example:
# * assuming competion of `git clone --test foo`
# __arg_index --foo= --bar= --baz=
# sets argidx=2
# * assuming competion of `git clone --test foo`
# __arg_index --test=
# sets argidx=
# * assuming competion of `git clone --test foo -k`
# __arg_index --test=
# sets argidx=
# * assuming competion of `git clone --test foo -k bar`
# __arg_index --test=
# sets argidx=2
#
# author: [email protected]
#
__arg_index()
{
# returned list of positional arguments
_posargs=( "${words[0]}" )
local c p i o idx=0
for i in $(seq 1 $cword); do
p=${words[i-1]} # previous word
c=${words[i]} # current word
o=1 # was this word an option (begin by assuming it was)?
# an option
[[ $c == -* ]] && continue
# an argument of a previously specified option
[[ $p == -* && $p != -*=* ]] && (echo "$@" | grep -qw -- "$p=") && continue
# a positional argument
o=0
idx=$((idx+1))
_posargs+=( "$c" )
done
# set %_argidx only if the current word was an argument
[[ $o == 0 ]] && _argidx=$idx || _argidx=
}
# find and echo the common prefix of passed arguments
# inspired by https://stackoverflow.com/a/28647824
__mj_common_prefix()
{
[[ $# -eq 0 ]] && return 0
local first prefix v
first="$1"
shift
for ((i = 0; i < ${#first}; ++i)); do
prefix=${first:0:i+1}
_dbg "PREFIX: $prefix"
for v; do
if [[ ${v:0:i+1} != "$prefix" ]]; then
echo "${first:0:i}"
return
fi
done
done
echo "$first"
}
#
# debugging utility. set GG_DEBUG="$HOME/_completion.log" and run
# `tail -f $GG_DEBUG` to observe what's going on.
#
_dbg()
{
[[ -n $GG_DEBUG ]] && echo "[$(date)]" "$@" >> "$GG_DEBUG"
}
# _msg <warning|error> <text>
__msg_cnt=1
_msg()
{
[[ -n $GG_SILENT ]] && return
local _type="$1"
[[ ${__msg_cnt} -ne 1 ]] && echo 1>&2
sed -e "s/^/$_type $__msg_cnt: *** /" 1>&2
(( __msg_cnt++ ))
}
#
# __readlines <var> < <file>
#
# read all lines from stdin into an array. need this for bash 3.2 (could
# otherwise use mapfile)
#
__readlines()
{
# read will return nonzero if EOF is encountred (which it always is)
# so we can't use the exit code to tell if anything was read. we
# therefore set $1=() before we start
eval "$1=()"
IFS=$'\n' read -r -d '' -a "$1" 2>/dev/null
}
#
# trim completions to the substring bash expects to see.
#
# details: bash tokenizes the input string by breaking it on characters
# found in $COMP_WORDBREAKS. The resulting tokenized list is placed into
# the ${COMP_WORDS[@]} array for autocompletion functions to use. This is
# fragile for our purposes as a) the user can override the characters, and
# b) is known to be horribly buggy in older versions of bash (spcifically
# v3.2 that is included with macOS). We therefore don't use this tokenization,
# but re-tokenize the line (see _mj_get_comp_words_by_ref) to get tokens
# broken up on "sane" characters (though that's not entirely foolproof).
#
# The COMPREPLY that we construct generates replies in reference to that
# re-tokenized array. For example, 'git@gi' may get suggestions such as
# COMPREPLY=('[email protected]:' '[email protected]:'). However, bash expects to
# get suggestions to replace only the last token as *it* generated (which,
# if $COMP_WORDBREAKS included '@', would only be 'gi' in the example above.
# So we have to change COMPREPLY to return what bash expects, by removing
# the longest prefix from the input token (e.g., 'git@gi' above) that ends
# in one of the delimiters we chose to ignore when re-tokenizing (typically
# @, :, and =. So this function would change COMPREPLY to
# COMPREPLY=('github.com:' 'gitlab.com:')
#
# Notes: bash 3.2 has two rather nasty bugs we have to take care of:
# - a) when not splitting on ':', it leaves the delimiter as a part
# of the input string (e.g., 'git@gi' gets split into 'git' '@gi'),
# so our suggestions must include the delimiter (i.e., example
# above would have COMPREPLY=('@github.com:' '@gitlab.com:') ).
# - b) to make matters more confusing, while the tokenization is done
# on all characters it $COMP_WORDBREAKS, the ${COMP_WORDS[@]}
# array ends up being tokenized on just the spaces! E.g., in
# the example above COMP_WORDS=('git' 'clone' 'git@gi') on bash 3.2
# whereas on 4.0 and newer it would (correctly) be equal to
# COMP_WORDS=('git' 'clone' 'git' '@' 'gi')
#
# inputs and outputs are passed via environmental variables.
#
# inputs:
# $1: the current word (as returned by _mj_get_comp_words_by_ref)
# ${COMPREPLY[@]}: the completions relative to re-tokenized line (input)
#
# outputs:
# ${COMPREPLY[@]}: completions that can be passed back to bash to
# correctly auto-complete the word.
#
# author: [email protected]
#
__mj_ltrim_completions()
{
# characters that readline breaks on, but we don't
local nobreak='@:='
# find the longest prefix delimited by a char in $nobreak
# that also appears in $COMP_WORDBREAKS
local prefix=
local c char
while read -r -n1 c; do
[[ "$COMP_WORDBREAKS" != *"$c"* ]] && continue
local try=${1%"${1##*$c}"} # "
[[ "${#try}" -gt "${#prefix}" ]] && { prefix="$try"; char=$c; }
done < <(echo -n "$nobreak")
# bugfix for bash 3.2 (macOS): leave the delimiter if it's not ':'
[[ "$char" != ':' ]] && prefix=${prefix%"$char"}
# Remove the prefix from COMPREPLY items
local i=${#COMPREPLY[*]}
while [[ $((--i)) -ge 0 ]]; do
COMPREPLY[$i]=${COMPREPLY[$i]#"$prefix"}
done
_dbg "input=$1 || prefix=$prefix || char=$char"
_dbg COMPREPLY="${COMPREPLY[*]}"
}
#
# complete words that may contain $COMP_WORDBREAKS characters.
# also allows one to show human-readable completions different
# from actual completions (e.g. with extra information).
#
# inputs and outputs are passed via environmental variables.
#
# inputs:
# ${compreply[@]}: the human-readable completions (input)
# ${COMPREPLY[@]}: the completions as expected by bash (input)
# $cur: the current word (as returned by _mj_get_comp_words_by_ref)
#
# outputs:
# ${COMPREPLY[@]}: the human-readable completions (if bash
# will show them), or completions as expected
# by bash (if bash will complete them)
#
# author: [email protected]
#
_fancy_autocomplete()
{
# a single or no completions: bash will autocomplete
[[ ${#COMPREPLY[@]} -le 1 ]] && return
# check if the completions share a common prefix, and if
# that prefix is longer than what's been typed so far. if so,
# bash will autocomplete up to that prefix and not show the
# suggestions (so send it the autocompletion text).
local prefix
prefix=$(__mj_common_prefix "${COMPREPLY[@]}")
# bugfix for bash 3.2 (macOS): the delimiter is a part of the word if it's not ':'
local curtrm="${cur#*[$COMP_WORDBREAKS]}"
local len="${#curtrm}"
local char="${cur:(-len-1):1}"
[[ "$char" != ':' ]] && curtrm="$char$curtrm"
#
[[ "$prefix" != "$curtrm" ]] && return
# Not possible to autocomplete beyond what's currently been
# typed, so bash will show suggestions. Send the human-readable
# form.
#
# Note: the appended character is the UTF-8 non-breaking space,
# which sorts to the end. It's needed to prevent bash from trying
# to autocomplete a common prefix in the human-readable options, if
# any.
COMPREPLY=("${compreply[@]}" " ")
}
#
# complete words that may contain $COMP_WORDBREAKS characters.
#
# inputs and outputs are passed via environmental variables.
#
# inputs:
# ${COMPREPLY[@]}: the completions (input)
# $cur: the current word (as returned by _mj_get_comp_words_by_ref)
#
# outputs:
# ${COMPREPLY[@]}: the completions with $COMP_WORDBREAKS characters (if
# bash will show them to the user), or completions as
# expected by bash (if bash will complete them)
#
# author: [email protected]
#
_colon_autocomplete()
{
# save the human form
local compreply=("${COMPREPLY[@]}")
__mj_ltrim_completions "$cur"
_fancy_autocomplete
}
################
# #
# Spinner UI #
# #
################
#
# Show a fancy spinner until stopped from the main thread. Use it as:
#
# start_spinner
# ... potentially long running code ...
# stop_spinner
#
# The spinner won't show immediately, but only after about ~1 second has
# passed since the start_spinner call. If stop_spinner is called before
# this point, nothing will be shown to the user. This allows one to enclose
# code that only occasionally runs slow, w/o worrying that the uer will
# be annoyed by a brief flash of the spinner when the code runs fast (e.g.
# when it gets the results from the cache).
#
# the directory where the spinner will create start/stop flags
__spinflagdir="$GG_CACHEDIR"
__spinflag="${__spinflagdir}/spinflag.$$"
__inspin="${__spinflagdir}/inspin.$$"
# The function that draws the spinner, run in a subprocess.
# Properties:
# - begins showing the spinner only after a ~second has passed
# - runs as long as $__spinflag is set (set by start_spinner, removed by stop_spinner)
# - signals it's finished running by removing $__inspin (checked by stop_spinner)
spin_wait()
{
# wait with spinner (pattern from https://github.com/swelljoe/spinner/blob/master/spinner.sh)
local -a marks=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
local i=0
local spinstart=10
while [[ -f "${__spinflag}" ]]; do
if [[ $i -ge $spinstart ]]; then
# show the spinner if we've waited for longer than a second
[[ $i -eq $spinstart ]] && printf ' ' >&2
printf '\b\b%s ' "${marks[i % ${#marks[@]}]}" >&2
fi
sleep 0.1
(( i++ ))
done
[[ $i -gt $spinstart ]] && printf '\b\b \b\b' >&2
rm -f "${__inspin}"
}
# Starts the spinner by launching it in a background subprocess which will
# spin as long as $__spinflag file exists
start_spinner()
{
mkdir -p "${__spinflagdir}"
touch "${__spinflag}" "${__inspin}"
( spin_wait & )
}
# Stops the spinner by removing $__spinflag, then spinning until spin_wait()
# signals it exited by the removal of $__inspin
stop_spinner()
{
# signal the spinner to stop
rm -f "${__spinflag}"
# wait for the spinner to stop
while [[ -f "${__inspin}" ]]; do
sleep 0.01;
done
}
###################################################
# #
# REST and GraphQL Call Utilities #
# #
###################################################
# call an endpoint and retrieve the full result.
# reads all pages if the result is paginated and has the
# standard Link: header.
#
# _rest_call <curl_with_auth> <url>
#
_rest_call()
{
local curl="$1"
local url="$2"
local tmp
tmp=$(mktemp)
while [[ -n "$url" ]]; do
# download page
$curl -f -s -D "$tmp" "$url" || { rm -f "$tmp"; return 1; }
# find the next URL
url=$(sed -En 's/^Link: (.*)/\1/p' "$tmp" | tr ',' '\n' | grep 'rel="next"' | sed -nE 's/^.*<(.*)>.*$/\1/p')
done
rm -f "$tmp"
}
#
# Store a graphql query into a variable $varname in a format
# that's ready to be sent as a javascript string (w/o newlines)
#
# usage: defgraphql <varname> <<-'EOF' ... query text ... EOF
#
defgraphql()
{
# squash the graphql text into a single line (as Javascript
# doesn't allow multiline strings) and assign it to
# variable $1
read -r -d '' "$1" < <(tr -s ' \t\n' ' ')
}
########################################################################
#
# Repository hosting services
#
########################################################################
__SERVICES=()
##########################
#
# GitLab support
#
##########################
__SERVICES+=( gitlab )
# shellcheck disable=SC2034 # used by _complete_url
{
__gitlab_PREFIXES="https://gitlab.com/ [email protected]:"
GG_AUTH_gitlab="$GG_CFGDIR/gitlab.auth.curl"
GG_CANONICAL_HOST_gitlab="gitlab.com"
}
#
# acquire credentials for GitLab API access. the user
# is prompted to call this from the command line.
#
init-gitlab-completion()
{
local GLUSER TOKEN
if [[ $# != 2 ]]; then
echo "Logging into GitLab so we can list repositories..."
echo "Please visit:"
echo
echo " https://gitlab.com/profile/personal_access_tokens"
echo
echo "and generate a new personal access token:"
echo
echo " 1. Under 'Name', write 'git-clone-completion access for $USER@$(hostname)'"
echo " 2. Leave 'Expires at' empty"
echo " 3. Under 'Scopes', check 'api' and leave others unchecked."
echo
echo "Then click the 'Create personal access token' button (below the form)."
echo
echo "The PAT is equivalent to a password we can use to list repositories in your GitLab account."
echo "Copy the newly generated token and paste it here."
echo ""
read -rsp "Token (note: the typed characters won't show): " TOKEN; echo
read -rp "Your GitLab username: " GLUSER
else
GLUSER="$1"
TOKEN="$2"
fi
# securely (and atomically) store the token and user to a netrc-formatted file
local tmpname="$GG_AUTH_gitlab.$$.tmp"
mkdir -p "$(dirname "$tmpname")"
rm -f "$tmpname"
touch "$tmpname"
chmod 600 "$tmpname"
# note: echo is a builtin so this is secure (https://stackoverflow.com/a/15229498)
echo "header \"Authorization: Bearer $TOKEN\"" >> "$tmpname"
mv "$tmpname" "$GG_AUTH_gitlab"
# verify that the token works
if ! _gitlab_call "users/$GLUSER/projects" >/dev/null; then
_gitlab_curl -s "https://gitlab.com/api/v4/users/$GLUSER/projects"; echo
echo
echo "Hmm, something went wrong -- check the token for typos and/or proper scope. Then try again."
rm -f "$GG_AUTH_gitlab"
return 1
else
echo
echo "Authentication setup complete; token stored to '$GG_AUTH_gitlab'"
fi
}
# curl call with github authentication
_gitlab_curl()
{
curl --config "$GG_AUTH_gitlab" "$@"
}
# _gitlab_call <endpoint> <options>
#
# example: _gitlab_call groups/gitlab-org/projects simple=true
#
_gitlab_call()
{
local endpoint="$1"
local options="$2"
_rest_call _gitlab_curl "https://gitlab.com/api/v4/$endpoint?per_page=100&$options"
}
# download the repository list of <user|org>
_gitlab_repo_list()
{
# GitLab doesn't have a unified API for both users and orgs
# ('groups' in GitLab parlance). We try users then groups.
( _gitlab_call users/"$1"/projects simple=true || _gitlab_call groups/"$1"/projects simple=true ) | jq -r '.[].path'
}
##########################
#
# GitHub support
#
##########################
__SERVICES+=( github )
# shellcheck disable=SC2034 # used by _complete_url
{
__github_PREFIXES="https://github.com/ [email protected]:"
GG_AUTH_github="$GG_CFGDIR/github.auth.netrc"
GG_CANONICAL_HOST_github="github.com"
}
#
# acquire credentials for GitHub API access. the user
# is prompted to call this from the command line.
#
init-github-completion()
{
local GHUSER TOKEN
if [[ $# != 2 ]]; then
echo "Logging into github so we can list repositories..."
echo "Please visit:"
echo
echo " https://github.com/settings/tokens/new"
echo
echo "and generate a new personal access token:"
echo
echo " 1. Under 'Note', write 'git-clone-completion access for $USER@$(hostname)'"
echo " 2. Under 'Select scopes', check 'repo' and leave otherwise unchecked."
echo
echo "Then click the 'Generate Token' green button (bottom of the page)."
echo
echo "The PAT is equivalent to a password we can use to list repositories in your github account."
echo "Copy the newly generated token and paste it here."
echo ""
read -rsp "Token (note: the typed characters won't show): " TOKEN; echo
read -rp "Your GitHub username: " GHUSER
else
GHUSER="$1"
TOKEN="$2"
fi
# securely (and atomically) store the token and user to a netrc-formatted file
local tmpname="$GG_AUTH_github.$$.tmp"
mkdir -p "$(dirname "$tmpname")"
rm -f "$tmpname"
touch "$tmpname"
chmod 600 "$tmpname"
# note: echo is a builtin so this is secure (https://stackoverflow.com/a/15229498)
echo "machine api.github.com login $GHUSER password $TOKEN" >> "$tmpname"
mv "$tmpname" "$GG_AUTH_github"
# verify that the token works
if ! curl -I -f -s --netrc-file "$GG_AUTH_github" "https://api.github.com/user" >/dev/null; then
curl -s "https://api.github.com/user"
echo "Hmm, something went wrong -- most likely you've typed the token incorretly. Rerun and try again."
rm -f "$GG_AUTH_github"
return 1
else
echo
echo "Authentication setup complete; token stored to '$GG_AUTH_github'"
fi
}
#
# Try extracting authentication credentials from hub's configuration file
#
_github_auto_auth()
{
# try to grab credentials from the 'hub' tool
[[ -f ~/.config/hub ]] || return 1
# extract token and user
local token user
user=$(sed -En 's/[ \t-]*user: (.*)/\1/p' ~/.config/hub 2>/dev/null)
token=$(sed -En 's/[ \t]*oauth_token: ([a-z0-9]+)/\1/p' ~/.config/hub 2>/dev/null)
# attempt auth if we managed to get something useful
if [[ -n "$user" && ${#token} == 40 ]]; then
init-github-completion "$user" "$token" >/dev/null 2>&1
fi
}
#
# GraphQL query returning all repositories with given user/org.
# used by _github_repo_list()
#
defgraphql __github_list_repos_query <<-'EOF'
query list_repos($queryString: String!, $first: Int = 100, $after: String) {
search(query: $queryString, type:REPOSITORY, first:$first, after: $after) {
repositoryCount
pageInfo {
endCursor
hasNextPage
}
edges {
node {
... on Repository {
name
}
}
}
}
}
EOF
# download the repository list of <user|org>
_github_repo_list()
{
local after="null"
local hasNextPage="true"
local data result
while [[ $hasNextPage == true ]]; do
# __github_list_repos_query is defined using defgraphql:
# shellcheck disable=SC2154
read -r -d '' data <<-EOF
{
"query": "$__github_list_repos_query",
"variables": {
"queryString": "user:$1 fork:true",
"after": $after
}
}
EOF
# execute the query
result=$(curl \
-s \
--netrc-file "$GG_AUTH_github" \
-X POST \
--data "$data" \
--url https://api.github.com/graphql)
# get information about the enxt page
IFS=$'\t' read -r hasNextPage endCursor < <(jq -r '.data.search.pageInfo | [.hasNextPage, .endCursor] | @tsv' <<<"$result")
after="\"$endCursor\""
# write out the desired result
jq -r '.data.search.edges[].node.name' <<<"$result"
done
}
##########################
#
# Bitbucket support
#
##########################
__SERVICES+=( bitbucket )
# shellcheck disable=SC2034 # used by _complete_url
{
__bitbucket_PREFIXES="https://bitbucket.org/ [email protected]:"
GG_AUTH_bitbucket="$GG_CFGDIR/bitbucket.auth.curl"
GG_CANONICAL_HOST_bitbucket="bitbucket.org"
}
#
# acquire credentials for Bitbucket API access. the user
# is prompted to call this from the command line.
#
init-bitbucket-completion()
{
local BBUSER BBPASS
if [[ $# != 2 ]]; then
echo "Logging into Bitbucket so we can list repositories..."
echo
read -rp "Your Bitbucket username: " BBUSER
echo
echo "Now please visit:"
echo
echo " https://bitbucket.org/account/user/$BBUSER/app-passwords/new"
echo
echo "to generate a new 'app password':"
echo
echo " 1. Under 'Label', write 'git-clone-completion access for $USER@$(hostname)'"
echo " 2. Under 'Permissions', check:"
echo " a) 'Read' under 'Account'"
echo " b) 'Read' under 'Projects'"
echo
echo "and leave others unchecked. Then click the 'Create' button."
echo
echo "This is an app-specific password which we will use to list repositories"
echo "in your GitLab account."
echo
echo "Copy the newly generated password and paste it here."
echo ""
read -rsp "Password (note: the typed characters won't show): " BBPASS; echo
else
BBUSER="$1"
BBPASS="$2"
fi
# securely store the token and user to a netrc-formatted file
# FIXME: make the creation of this file atomic
mkdir -p "$(dirname "$GG_AUTH_bitbucket")"
rm -f "$GG_AUTH_bitbucket"
touch "$GG_AUTH_bitbucket"
chmod 600 "$GG_AUTH_bitbucket"
# note: echo is a builtin so this is secure (https://stackoverflow.com/a/15229498)
echo "user \"$BBUSER:$BBPASS\"" >> "$GG_AUTH_bitbucket"
# verify that the token works
if ! _bitbucket_call "2.0/repositories/$BBUSER" >/dev/null; then
echo
echo "Hmm, something went wrong -- check the token for typos and/or proper scope. Then try again."
rm -f "$GG_AUTH_bitbucket"
return 1
else
echo
echo "Authentication setup complete; token stored to '$GG_AUTH_bitbucket'"
fi
}
# curl call with bitbucket authentication
_bitbucket_curl()
{
curl --config "$GG_AUTH_bitbucket" "$@"
}
# _bitbucket_call <endpoint> <options>
#
# example: _bitbucket_call 2.0/repositories/atlassian simple=true
#
_bitbucket_call()
{
local endpoint="$1"
local options="$2"
local url="https://api.bitbucket.org/$endpoint?pagelen=100&$options"
local tmp
tmp=$(mktemp)
while [[ -n "$url" ]]; do
# download page
_bitbucket_curl -f -s "$url" > "$tmp" || { rm -f "$tmp"; return 1; }
# echo the content
jq -r '.values' "$tmp"
# find next page (jq trick from https://github.com/stedolan/jq/issues/354#issuecomment-43147898)
url=$(jq -r '.next // empty' "$tmp")
done
rm -f "$tmp"
}
# download the repository list of <user|org>
_bitbucket_repo_list()
{
_bitbucket_call 2.0/repositories/"$1" | jq -r '.[].name'
}
############################
#
# Remote host via ssh
#
############################
#
# SSH utils
#
#
# ... | _timeout <seconds> | <target_command>
#
# exits if no input has been received in <seconds>; otherwise act like cat
# (passing input through). We use this to automatically drop cached SSH
# connections.
#
_timeout()
{
local seconds="$1"
while read -t "$seconds" -r line; do
echo "$line"
done
_dbg "exiting _timeout"
}
# variables holding the global state for SSH connections
__ssh_msg_sentinel=
__ssh_fifo=
__ssh_host=
# __mj_ssh_start <host>
__mj_ssh_start()
{
_dbg "in __mj_ssh_start"
local host="$1"
__ssh_host="$host"
__ssh_msg_sentinel="--mj-git-cl-comp-$RANDOM-$RANDOM-$RANDOM--"
__ssh_fifo="$(mktemp -d)/fifo"
# create the pipe for ssh output
_dbg "__ssh_fifo=$__ssh_fifo"
mkfifo "${__ssh_fifo}"
# we'll write commands to descriptor 217, and read output on descriptor 218
# we trap the SIGINT to stop the user's CTRL-C in the terminal from killing the
# background ssh connection. e.g.,, imagine the scenario like:
#
# $ git clone epyc.astro.washington.edu:<TAB> (...and then <CTRL-C>...)
# $ ... user looks something up ...
# # git clone epyc.astro.washington.edu:<TAB>
#
# we want the second invocation to re-use the background connection. w/o
# trapping SIGINT, the <CTRL-C> would kill it.
exec 217> >( trap '' SIGINT; _timeout 120 | ssh -o 'Batchmode yes' "$host" 2>/dev/null >"${__ssh_fifo}"; rm -f "${__ssh_fifo}"; _dbg "== ssh to $__ssh_host exited." )
exec 218< "${__ssh_fifo}"
}
# stop the currently running SSH connection, deleting the FIFO
__mj_ssh_stop()
{
_dbg "in __mj_ssh_stop"
exec 217>&-
exec 218<&-
[[ -n "${__ssh_fifo}" ]] && rm -f "${__ssh_fifo}"
__ssh_host=
}
# __mj_ssh_write <commands>
#
# writes to the SSH pipe, adding a command to echo a sentinel at the end
# which read_ssh uses to recognize the end of message.
#
# WARNING: if you're pairing write/read in the same process, the command
# being written should be small enough to fit into the pipe capacity on your
# OS (16k for macOS, 64k for Linux), or otherwise your code _may_ hang.
#
__mj_ssh_write()
{
# https://www.gnu.org/software/bash/manual/html_node/Special-Builtins.html
# https://unix.stackexchange.com/questions/206786/testing-if-a-file-descriptor-is-valid
/bin/echo "$@" "; echo ${__ssh_msg_sentinel}" 2>/dev/null >&217
}
# __mj_ssh_read
#
# reads output from the SSH pipe, echoing them to stdout, until the
# sentinel is encountered.
__mj_ssh_read()
{
local IFS=$'\n'
while read -r line <&218; do
if [[ $line == "${__ssh_msg_sentinel}" ]]; then
return