sneak/tools/scripts/bcs.sh
Colin McMillen 5210ef7398 bcs: add ability to set context lines; clean up some expansions
GitOrigin-RevId: 718fc9bb92eb9a2643f262739a2017a6341cde1f
2020-02-13 23:30:31 -05:00

71 lines
1.7 KiB
Bash

#!/bin/bash
# Bad Code Search, with syntax highlighting.
#
# Sample usage:
# bcs.sh --file "\.cs$" Vector3
# bcs.sh -i new vector3
# bcs.sh -C 10 new Vector3
# https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash
POSITIONAL=()
GREP_FLAGS=""
CONTEXT=3
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-f|--file)
FILE="$2"
shift # past argument
shift # past value
;;
-i|--ignore-case)
GREP_FLAGS="-i"
shift # past argument
;;
-C|--context)
CONTEXT="$2"
shift # past argument
shift # past value
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift # past argument
;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters
if [[ -z $@ ]]; then
echo 'Usage: bcs.sh [-i] [-f/--file FILE_PATTERN] [-C/--context NUM_LINES] QUERY'
exit 1
fi
# highlight(1) sticks some ANSI cruft into the output.
# We just turn spaces into "match anything", which kinda ignores the cruft.
QUERY=`echo $@ | sed -e "s/ /.*/g"`
if [[ -n $FILE ]]; then
files=$(git ls-tree -r master --name-only | grep "${FILE}")
if [[ -z $files ]]; then
echo "no files matched"
exit 0
fi
for file in `grep -l ${GREP_FLAGS} "${QUERY}" $files`;
do
echo $file:
highlight --force --line-numbers -O xterm256 --stdout $file | \
grep -C ${CONTEXT} ${GREP_FLAGS} "${QUERY}" --label=$file | perl -pne s%^--\$%$file:%
done
else
for file in `grep -l ${GREP_FLAGS} "${QUERY}" $(git ls-tree -r master --name-only)`
do
echo $file:
highlight --force --line-numbers -O xterm256 --stdout $file | \
grep -C ${CONTEXT} ${GREP_FLAGS} "${QUERY}" --label=$file | perl -pne s%^--\$%$file:%
done
fi