-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnpm-scripts-auto.sh
102 lines (87 loc) · 3.13 KB
/
npm-scripts-auto.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
#!/bin/zsh
# Configuration - set your preferred package manager (npm, pnpm, or yarn)
PACKAGE_MANAGER=${PACKAGE_MANAGER:-"pnpm"}
# Autoload the chpwd hook
autoload -U add-zsh-hook
# Associative array to track dynamically created commands
typeset -A _npm_script_cmds
# Function to show interactive script selection
scripts() {
if [[ ! -f package.json ]]; then
echo "❌ No package.json found in current directory"
return 1
fi
local scripts
scripts=("${(@f)$(jq -r '.scripts | keys[]' package.json 2>/dev/null)}")
if [[ ${#scripts[@]} -eq 0 ]]; then
echo "❌ No scripts found in package.json"
return 1
fi
echo "📦 Available ${PACKAGE_MANAGER} scripts:"
echo "Type script name or number to run. \n"
PS3=$'\nSelect a script to run: '
select script in "${scripts[@]}" "Cancel"; do
case $script in
"Cancel")
echo "Operation cancelled"
return 0
;;
*)
# Check if input is a number or script name
if [[ -n $script ]]; then
# Number was selected from menu
echo "\nRunning: ${PACKAGE_MANAGER} run $script\n"
$PACKAGE_MANAGER run $script
return 0
elif [[ " ${scripts[@]} " =~ " $REPLY " ]]; then
# Script name was typed directly
echo "\nRunning: ${PACKAGE_MANAGER} run $REPLY\n"
$PACKAGE_MANAGER run $REPLY
return 0
else
echo "Invalid selection. Please try again."
fi
;;
esac
done
}
# Function to generate completions for a command
_generate_npm_script_completion() {
local cmd=$1
eval "_${cmd}_completion() {
local -a commands
commands=(\$(jq -r '.scripts | keys[]' package.json 2>/dev/null))
_describe 'command' commands
}"
compdef "_${cmd}_completion" "$cmd"
}
# Function to detect package.json scripts and create commands
npm_scripts_update() {
# Clear previous functions and completions
for cmd in "${(@k)_npm_script_cmds}"; do
unfunction "$cmd" 2>/dev/null
unset "_npm_script_cmds[$cmd]"
unfunction "_${cmd}_completion" 2>/dev/null
done
# Check for package.json in the current directory
if [[ -f package.json ]]; then
local scripts
scripts=("${(@f)$(jq -r '.scripts | keys[]' package.json 2>/dev/null)}")
# Dynamically create functions and completions
for script in $scripts; do
# Create the function
eval "function $script() { $PACKAGE_MANAGER run $script \$@ }"
_npm_script_cmds[$script]=1
_generate_npm_script_completion "$script"
done
# Display loaded scripts
if [[ ${#scripts[@]} -gt 0 ]]; then
echo "⚡ ${PACKAGE_MANAGER} scripts loaded! \n💡 Type 'scripts' to view all."
echo
fi
fi
}
# Hook to trigger when changing directories
add-zsh-hook chpwd npm_scripts_update
# Trigger on shell startup
npm_scripts_update