Last active
October 8, 2024 13:53
-
-
Save brunobord/140e099829060334fee55707456d3404 to your computer and use it in GitHub Desktop.
Git case-insensitive search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
A case-insensitive git search tool. | |
This Python script emulates the following shell command:: | |
git grep -i term1 [ | grep -i term2 [ | grep -i term3 ] ...] | |
I was unable to do it using bash, so I made it in Python. | |
On the plus side, it highlights all terms, not just the last one you've grepped. | |
As long as you have put this file in you ``$PATH``, it should be available as | |
a git subcommand. | |
Basic usage:: | |
git search term1 [term2 [term3] ...] | |
Options: | |
* ``--case-sensitive``: Activate the case sensitive mode | |
* ``--no-color``: Will render the found lines without highlighting. More convenient | |
:x | |
""" | |
import re | |
import subprocess | |
import argparse | |
RED = "\033[0;31m" | |
END = "\033[0m" | |
BOLD = "\033[1m" | |
# FOR DEBUG | |
# RED = "R" | |
# END = "E" | |
# BOLD = "B" | |
def highlight_word(sentence, word, case_sensitive=False, colors=True): | |
if case_sensitive: | |
occurences = re.findall(word, sentence) | |
else: | |
occurences = re.findall(word, sentence, re.IGNORECASE) | |
occurences = set(occurences) | |
if colors: | |
for occurence in occurences: | |
sentence = sentence.replace(occurence, f"{RED}{BOLD}{occurence}{END}") | |
return sentence | |
def main(terms, case_sensitive=False, colors=True): | |
git_cmd = "git grep -i" | |
grep_cmd = "grep -i" | |
if case_sensitive: | |
git_cmd = "git grep" | |
grep_cmd = "grep" | |
cmd = [f"{git_cmd} {terms[0]}"] | |
if len(terms) > 1: | |
for term in terms[1:]: | |
cmd.append(f"{grep_cmd} {term}") | |
try: | |
output = subprocess.check_output(" | ".join(cmd), shell=True) | |
except subprocess.CalledProcessError: | |
print("[nothing]") | |
return | |
lines = output.decode().split("\n") | |
for line in lines: | |
if not line: | |
continue | |
for term in args.terms: | |
line = highlight_word(line, term, case_sensitive, colors) | |
print(line) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser( | |
description="Case-insensitive search in a git repository" | |
) | |
parser.add_argument("terms", nargs="+") | |
parser.add_argument("--case-sensitive", "-s", action="store_true", default=False) | |
parser.add_argument("--no-color", action="store_true", default=False) | |
args = parser.parse_args() | |
colors = not args.no_color | |
main(args.terms, args.case_sensitive, colors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment