Skip to content

Instantly share code, notes, and snippets.

@ptaylor
Created January 20, 2017 14:12
Show Gist options
  • Save ptaylor/8b52e9ccff05682acbe5c886867661a7 to your computer and use it in GitHub Desktop.
Save ptaylor/8b52e9ccff05682acbe5c886867661a7 to your computer and use it in GitHub Desktop.
Run git grep for all repositories under the current directory
#!/bin/sh
#
# Grep all git repos under the current directory.
#
# Usage: git-grep-all <exp>
#
# Examples:
#
# git-grep-all Foo
#
# git-grep-all -i foo
#
# git-grep-all -l bar
#
# How long in days before refreshing the cached git repo list
CACHE_EXPIRY=10
# How deep to go when looking for git repos
DEPTH=10
# File to store a cache of git repos
GIT_REPO_CACHE=.git-grep-all-repo-list
current_branch () {
git rev-parse --abbrev-ref HEAD
}
msg () {
BOLD_START='\033[1m'
BOLD_END='\033[0m'
if [ -t 1 ] ; then
echo "${BOLD_START}[$*]${BOLD_END}"
else
echo "[$*]"
fi
}
if [ ! -f "${GIT_REPO_CACHE}" -o "`find ${GIT_REPO_CACHE} -mtime +${CACHE_EXPIRY} -print 2>/dev/null`" = "${GIT_REPO_CACHE}" ] ; then
msg "searching for git repos"
find . -type d -name .git -exec dirname {} \; -depth ${DEPTH} > "${GIT_REPO_CACHE}"
r=`cat ${GIT_REPO_CACHE} | wc -l | sed -e 's/ //g'`
msg "found ${r} git repos; cached in ${GIT_REPO_CACHE}"
fi
TMP_GREP=/tmp/grep$$.txt
for i in `cat ${GIT_REPO_CACHE}` ; do
if [ -d "${i}" ] ; then
(cd $i; git grep "$@" > ${TMP_GREP})
if [ -s ${TMP_GREP} ]; then
branch=`cd $i; current_branch`
msg repository: $i, branch: $branch
cat ${TMP_GREP} | sed -e "s#^#$i/#"
fi
rm -f ${TMP_GREP}
else
msg "cannot find directory ${i}; skipping and deleting repo cache"
rm -f "${GIT_REPO_CACHE}"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment