sneak/tools/scripts/bcs.sh
2020-02-14 00:06:25 -05:00

90 lines
2.1 KiB
Bash

#!/bin/bash
# Bad Code Search, with syntax highlighting.
#
# Sample usage:
# bcs.sh --file "Line" Vector3
# bcs.sh -i new vector3
# bcs.sh -C 10 new Vector3
# bcs.sh -x py sprite
# bcs.sh -i -x cs -f World spritebatch
# bcs.sh --tree develop -x cs -f MonoGame.Framework SpriteBatch
# https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash
POSITIONAL=()
GREP_FLAGS=""
CONTEXT=3
TREE=master
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-f|--file)
FILE="$2"
shift # past argument
shift # past value
;;
-x|--extension)
EXTENSION="\.$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
;;
-t|--tree)
TREE="$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] [-x/--extension EXTENSION] [-C/--context NUM_LINES] [-t/--tree TREE_NAME] 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 $EXTENSION ]]; then
FILE="${FILE}.*${EXTENSION}"
fi
if [[ -n $FILE ]]; then
files=$(git ls-tree -r ${TREE} --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