albertyw/dotfiles

View on GitHub
bin/heregrep

Summary

Maintainability
Test Coverage
#!/bin/bash

# This script runs git grep through all git repositories directly underneath
# the current directory

set -euo pipefail
IFS=$'\n\t'

if [[ -z "${1+x}" ]] || [[ "$1" == "-h" ]]; then
    echo "Runs a grep operation under each git repository underneath the current pwd"
    exit
fi
yellow='\e[1;33m'
reset='\e[0m'

flags=()
terms=()
for g in "$@"; do
    if [[ $g == -* ]]; then
        flags+=("$g")
    else
        terms+=("$g")
    fi
done
# flags="$(echo "$flags" | xargs)"

for f in ./*; do
    if [ ! -d "$f/.git" ]; then
        continue
    fi

    result="$(git -C "$f" --no-pager grep "${flags[@]}" "${terms[0]}" || true)"
    for t in "${terms[@]}"; do
        result="$(echo "$result" | grep "${flags[@]}" "$t" || true)"
    done
    if [[ -n "$result" ]]; then
        echo -e "${yellow}$f${reset}"
        tput rmam  # Disable line wrapping in terminal
        echo "$result"
        tput smam  # Reenable line wrapping in terminal
    fi
done