Skip to content

Instantly share code, notes, and snippets.

@benln
Last active August 20, 2024 08:00
Show Gist options
  • Save benln/353de3c24251976dad650326db4bc7d4 to your computer and use it in GitHub Desktop.
Save benln/353de3c24251976dad650326db4bc7d4 to your computer and use it in GitHub Desktop.
fzf package.json script selector
#!/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
}
@benln
Copy link
Author

benln commented Aug 5, 2024

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 so

reloadFunctions() {
  local cmdFiles file
  cmdFiles=($(ls $HOME/.functions | sed 's/\.[^.]*$//')) # list all files in $HOME/.functions without an extension
  for file in $cmdFiles; do
    autoload -U $file &&
      unfunction $file &&
      autoload -U $file
  done
}

reloadFunctions

Other methods

Either:

  • Copy the whole script in your .zshrc (or .zlogin)
  • Download the file, put it where you want, then source it in your .zshrc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment