Last active
December 5, 2023 21:08
-
-
Save wallentx/57f14e0faba5b9d565e663d338312e24 to your computer and use it in GitHub Desktop.
fzfstr
This file contains 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
#!/usr/bin/env bash | |
set -e | |
# Dependency check | |
RG_VERSION="$(rg --version | head -n1 | cut -d" " -f2)" | |
version_ge() { | |
printf '%s\n%s\n' "$2" "$1" | sort -V -C | |
} | |
if ! [ "$(command -v rg)" ] > /dev/null || [ "$(version_ge "$RG_VERSION" '11.0.0' || echo 1)" ]; then | |
echo "You need to install Ripgrep==^11.0.0" | |
echo "https://github.com/BurntSushi/ripgrep" | |
exit 1 | |
fi | |
usage() { | |
echo "Usage: $0 [options] '<search_string>'" | |
echo "Options:" | |
echo " -t <type> Search only files of a specific type." | |
echo " -f <file> Search only files matching the given filename/glob." | |
echo " -c Disable colored output. Enabled by default." | |
echo "Example:" | |
echo " $0 -t py 'import os'" | |
echo " This searches for the string 'import os' in all Python files." | |
echo "" | |
echo " $0 -f '*.txt' 'Hello World'" | |
echo " This searches for 'Hello World' in all .txt files." | |
echo "" | |
echo " $0 -c 'function'" | |
echo " This searches for 'function' without colored output." | |
} | |
# Options | |
COLOR_OPTS="--colors path:style:bold --colors line:style:bold -p" | |
while getopts "t:f:ch" OPTION; do | |
case $OPTION in | |
t) | |
TYPE=${OPTARG} | |
;; | |
f) | |
FILE=${OPTARG} | |
;; | |
c) | |
COLOR_OPTS="--colors path:none --colors line:none --colors column:none --colors match:none" | |
;; | |
h) | |
usage | |
exit 0 | |
;; | |
*) | |
echo "Unknown command line switch: $OPTION" | |
usage | |
exit 1 | |
;; | |
esac | |
done | |
shift "$((OPTIND-1))" | |
# Check mutual exclusivity of -t and -f | |
if [[ -n ${TYPE} ]] && [[ -n ${FILE} ]]; then | |
echo "Options -t and -f cannot be used together." | |
usage | |
exit 1 | |
fi | |
# Check if no arguments | |
if [ $# -eq 0 ]; then | |
usage | |
exit 1 | |
fi | |
FSTRING=$1 | |
# Base rg command | |
base_rg_command() { | |
rg $COLOR_OPTS \ | |
--hidden \ | |
--no-messages \ | |
-M 200 \ | |
--max-columns-preview \ | |
-j 0 \ | |
"$FSTRING" \ | |
--ignore-file "$HOME"/.ignore \ | |
"$@" | |
} | |
findmatch() { | |
base_rg_command | | |
sed 's/.*:/── Line &/' | | |
sed 's/:/: \n /1' | |
} | |
findmatchtype() { | |
base_rg_command --type "$TYPE" | | |
sed 's/.*:/── Line &/' | | |
sed 's/:/: \n /1' | |
} | |
findmatchfile() { | |
base_rg_command --glob "$FILE" | | |
sed 's/.*:/── Line &/' | | |
sed 's/:/: \n /1' | |
} | |
if [[ -n ${TYPE} ]]; then | |
findmatchtype | |
elif [[ -n ${FILE} ]]; then | |
findmatchfile | |
else | |
findmatch | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment