#!/bin/sh
# Copyright (c) 2010, Chris Packham
# Wrapper for git grep that is submodule aware

SUBDIRECTORY_OK="yes"
. git-sh-setup

submodule_root_relative()
{
	ceiling="$HOME"
	while test ! -e "$cdup.gitmodules"; do
		cdup="$cdup../"
		if test "$(cd $cdup && pwd)" == "$ceiling"; then
			echo >&2 "fatal: failed to find superproject root,"
			echo >&2 "       stopped searching at $ceiling."
			exit 1
		fi
	done
	echo "$cdup"
}

submodule_root()
{
	(cd "$(submodule_root_relative)" && pwd)
}

# we don't do anything with the arg but we should check that we
# have something to pass to git grep
test $# -lt 1 && die "fatal: no pattern given."

prefix="$(submodule_root_relative)" || exit 1
(cd "./$prefix"; \
	git submodule --quiet foreach \
		"git --no-pager grep $@ | sed s\"|.*|$prefix\$path/&|\" || true") \
			| git_pager

