Is there a Git command that would allow finding the first commit that added a file matching a pattern?
For example, let's say I want to find the commit that first added a file matching the pattern path/prefix/*/subpath/*
. I found out that it can be done by combining git rev-list
to find commits that added files under a fixed path (e.g., path/prefix
), iterate the commits to list the files they added via git diff-tree
, and use grep
to find files matching the given pattern (e.g., /subpath/
):
for COMMIT in $(git rev-list \
--reverse \
--topo-order \
HEAD \
path/prefix)
do
git diff-tree \
--diff-filter A \
--name-only \
--no-commit-id \
-r "${COMMIT}" |
grep -q "/subpath/" && echo "${COMMIT}" && break
done
Is there a better way?
CodePudding user response:
"Better" is in the eye of the ... runner, but you can do this with git log
and either head
or tail
. We start with the basic:
git log <options> --diff-filter=A --format=%H -- 'path/prefix/*/subpath/*'
which dumps out all the hash IDs (add --topo-order
if desired, add --reverse
if desired). Then we just snip out all but the last (if not using --reverse
) or first (if using --reverse
):
(the git log command) | tail -n 1
This will generally be faster since git log
can quickly eliminate the non-candidates, but it could sometimes be slower perhaps.