Last active
August 20, 2024 08:00
-
-
Save benln/353de3c24251976dad650326db4bc7d4 to your computer and use it in GitHub Desktop.
fzf package.json script selector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
yarn() { | |
# Check for required dependencies: jq and fzf | |
local missing_deps=() | |
for dep in jq fzf; do | |
if ! command -v "$dep" &>/dev/null; then | |
missing_deps+=("$dep") | |
fi | |
done | |
if [ ${#missing_deps[@]} -ne 0 ]; then | |
echo "Warning: The following dependencies are missing: ${missing_deps[*]}" | |
return 1 | |
fi | |
# Allow running `yarn` and any of `yarn` subcommands directly | |
if [[ "$1" != "run" ]]; then | |
command yarn "$@" | |
return 0 | |
fi | |
# Allow running a specified `yarn run` script directly | |
if [[ "$#" -ne 1 ]]; then | |
command yarn "$@" | |
return 0 | |
fi | |
# When `yarn run` is not followed by anything, launch fzf to pick a script | |
local package_json="package.json" | |
if ! [[ -f $package_json ]]; then | |
echo "Error: There's no package.json in the current directory" | |
return 1 | |
fi | |
local script_names script_name | |
script_names=$(jq -r '.scripts | keys_unsorted[]' "$package_json") | |
# Use fzf to select a script from package.json and display a preview of the command | |
script_name=$(echo "$script_names" | fzf --cycle --height ~100% --border --info inline --header="Select a script to run with ENTER. ESC to quit." \ | |
--preview="jq -r --arg script {} '.scripts[\$script]' $package_json" \ | |
--color 'border:#778899' \ | |
--preview-window=up:1 --history="$HISTFILE") | |
if [[ -n "$script_name" ]]; then | |
local command_to_run="yarn run $script_name" | |
echo "$command_to_run" | |
print -s "$command_to_run" # Add the command to Zsh history | |
command yarn run "$script_name" | |
else | |
echo "Exit: You haven't selected any script" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation
Personal preferred method
I copy the script in a file called
yarn
inside~/.functions
The file should not have any extension (the name of the file will be use as command name).
Then in my
.zlogin
I load all functions in~/.functions
like soOther methods
Either:
.zshrc
(or.zlogin
).zshrc