Skip to content

Instantly share code, notes, and snippets.

@mceachen
Created November 29, 2023 04:11
Show Gist options
  • Save mceachen/7404dad23e22b40774c9dac747656970 to your computer and use it in GitHub Desktop.
Save mceachen/7404dad23e22b40774c9dac747656970 to your computer and use it in GitHub Desktop.
git addgrep: stage all diff hunks that match a given regexp
#!/bin/bash -e
# Renamed a file or method? Use this to add all files matching that regex pattern.
# Assumes this file lives in $ROOT/bin, so we need to hop up a level (the `/..` bit)
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. >/dev/null 2>&1 && pwd)"
cd "$ROOT"
# Ignore calls to `git add` that have no filenames:
git config advice.addEmptyPathspec false
if [ "${HUNKS:-1}" == 1 ]; then
echo "(staging matching hunks)"
git diff -U0 | grepdiff -E "$*" --output-matching=hunk | git apply --cached --unidiff-zero
else
echo "(staging matching files)"
# -S Looks for differences that change the number of occurrences of the specified
# shellcheck disable=SC2046
git add --ignore-errors -- $(git diff -S"$*" --name-only)
# -G Looks for differences whose patch text contains added/removed lines that match <regex>.
# shellcheck disable=SC2046
git add --ignore-errors -- $(git diff -G"$*" --name-only)
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment