-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathyarn-extra-completion.plugin.zsh
112 lines (87 loc) · 2.4 KB
/
yarn-extra-completion.plugin.zsh
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
#compdef yarn
_yc_run_default() {
if (( ${+YARN_EXTRA_COMPLETION_DEFAULT} )); then
$YARN_EXTRA_COMPLETION_DEFAULT "$@"
elif type _yarn &> /dev/null; then
_yarn "$@"
fi
}
_yc_yarn_command() {
echo "${words[2]}"
}
_yc_yarn_command_arg() {
echo "${words[3]}"
}
_yc_no_of_yarn_args() {
echo "$#words"
}
_yc_check_jq() {
(( ${+commands[jq]} )) || echo "\nyarn-completion needs jq\n"
}
_yc_recursively_look_for() {
local filename="$1"
local dir=$PWD
while [ ! -e "$dir/$filename" ]; do
dir=${dir%/*}
[[ "$dir" = "" ]] && break
done
[[ ! "$dir" = "" ]] && echo "$dir/$filename"
}
_yc_yarn_add_completion() {
# Only run on `yarn add ?`
[[ ! "$(_yc_no_of_yarn_args)" = "3" ]] && return
local packages=($(yarn cache list --json | jq --raw-output '.data.body[] | .[0]' 2> /dev/null))
# Return if we don't have any cached modules
[[ "$#packages" = 0 ]] && return
# If we do, recommend them
_values 'packages' $packages
}
_yc_yarn_remove_completion() {
# Use default yarn completion to recommend global modules
[[ "$(_yc_yarn_command_arg)" = "-g" ]] || [[ "$(_yc_yarn_command_arg)" = "--global" ]] && return
# Look for a package.json file
local package_json="$(_yc_recursively_look_for package.json)"
# Return if we can't find package.json
[[ "$package_json" = "" ]] && return
local values=($(jq --raw-output '(.devDependencies, .dependencies) | keys[]' $package_json 2> /dev/null))
[[ "$#values" = 0 ]] && return
_values 'installed' $values
}
_yc_yarn_run_completion() {
# Only run on `yarn run ?`
[[ ! "$(_yc_no_of_yarn_args)" = "3" ]] && return
# Look for a package.json file
local package_json="$(_yc_recursively_look_for package.json)"
# Return if we can't find package.json
[[ "$package_json" = "" ]] && return
local -a scripts
scripts=(${(f)"$(
jq --raw-output '
.scripts | to_entries[] | "\(.key):\(.value | gsub("\n";"\\\\n"))"
' $package_json 2> /dev/null
)"})
[[ "$#scripts" = 0 ]] && return
_describe 'scripts' scripts
}
_yc_zsh_yarn_extra_completion() {
# Show yarn commands if not typed yet
[[ $(_yc_no_of_yarn_args) -le 2 ]] && _yc_run_default "$@" && return
# Load custom completion commands
case "$(_yc_yarn_command)" in
add)
_yc_check_jq
_yc_yarn_add_completion
;;
remove)
_yc_check_jq
_yc_yarn_remove_completion
;;
run)
_yc_check_jq
_yc_yarn_run_completion
;;
*)
_yc_run_default "$@"
esac
}
_yc_zsh_yarn_extra_completion "$@"