Skip to content

Instantly share code, notes, and snippets.

@fitzterra
Last active July 13, 2018 05:51
Show Gist options
  • Select an option

  • Save fitzterra/f011864aaa94e6f29d802a1ebd96f510 to your computer and use it in GitHub Desktop.

Select an option

Save fitzterra/f011864aaa94e6f29d802a1ebd96f510 to your computer and use it in GitHub Desktop.
See history of a sepcific change (identified via regex) in a file.

This script helps you to answers questions like:

How did this variable in this file come to have the value it has now?

Or just to see how a certain line became what it is now in a file. This is helpful when working on code from others and it is not clear why a certain "something" is as it is in a file.

See the script for more details.

#!/bin/bash
#
# Script that can be used to show all commits where a specific regex is matched
# for a single file.
# This can be used for example to see the history of how a single variable or
# pattern had evolved to what it current state is.
#
# This is an expansion of: https://stackoverflow.com/a/9935417
#
# For example I have a piece of code that sets a variable to specifc value, but
# no one knows why it has that value. If the variable is called 'foobar' for
# example and it is in a file baz.py this script can help find every commit
# where this name occured in the commit diff:
#
# gitRegexHistory 'foobar' baz.py
#
# Be as specific as possible with the regex search to limit the hits more
# precisely.
ME=$(basename $0)
SEARCH="$1"
shift
FILE="$1"
shift
function showhelp() {
cat - << __HERE__
Usage: $ME 'search-string-regex' file [args]
where:
'search-string-regex': regex passed to the -G arg for 'git log' to search
file: the file name to show the history for
[args]: any further args are passed to 'git log' as args verbatim
__HERE__
}
# Validate params
[ -z "$SEARCH" ] && showhelp && exit 1
[ -z "$FILE" ] && showhelp && exit 1
[ ! -f "$FILE" ] && showhelp && exit 1
# Find all commits where the patch text contains add/remove lines that matches
# the search pattern
for c in $(git log -G "$SEARCH" --format=%H -- $FILE); do
# Grep the commit for this file for the same pattern
git --no-pager grep -e "$SEARCH" --heading $* $c -- $FILE
echo
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment