Skip to content

Instantly share code, notes, and snippets.

@bdd
Last active April 15, 2023 13:54
Show Gist options
  • Save bdd/f32c70698032dc7e0b9ae5f9b175a2d7 to your computer and use it in GitHub Desktop.
Save bdd/f32c70698032dc7e0b9ae5f9b175a2d7 to your computer and use it in GitHub Desktop.
FZF_DEFAULT_COMMAND utility for fzf
#!/bin/bash
# FZF_DEFAULT_COMMAND utility for fzf
#
# Tries to use Watchman, Ripgrep (rg), The Silver Searcher (ag) in this order.
# ...or falls back the fzf's Unix default.
#
# TODO:
# - Use 'git ls-files -cmod' in Git repositories
has() {
hash "$1" 2>/dev/null
return $?
}
can_use_watchman() {
# When running against fast storage (e.g. ramdisk, PCIe flash, NVMe, etc) it might be worth
# setting FZF_NO_WATCHMAN. Both ripgrep (rg) and The Silver Searcher (ag)
# will be slightly faster than "talk to watchman and parse JSON response".
if ! (has watchman && has jq) || [[ -n $FZF_NO_WATCHMAN ]]; then
return 1
fi
for WATCHED_ROOT in $(watchman watch-list | jq -r '.roots[]'); do
SUBDIR="${PWD##$WATCHED_ROOT/}"
# If expansion worked (above), PWD is a subdirectory of WATCHED_ROOT.
if [[ ${PWD} != "${SUBDIR}" ]]; then
return 0
fi
done
return 1
}
use_watchman() {
local query=$(cat <<EOF
["query", "${WATCHED_ROOT}", {
"path": [{"path": "${SUBDIR}", "depth": -1}],
"expression": ["allof",
["type", "f"],
["not", "empty"]
],
"fields": ["name"]
}]
EOF
)
time watchman -j --no-pretty <<< "${query}" > /dev/null
}
use_rg() {
rg --color auto --files
}
use_ag() {
ag --nocolor -g '' -l
}
use_fzf_default() {
# From https://github.com/junegunn/fzf/blob/master/src/constants_unix.go
find -L . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | sed s/^..//
}
if can_use_watchman; then use_watchman
elif has rg; then use_rg
elif has ag; then use_ag
else use_fzf_default
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment