Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git log with perl regex

Tags:

git

regex

perl

I'm trying to do a search using git log -G with a regex that includes negative lookbehind. For example:

git log -G "(?<!sup)port" --all

This isn’t working and based on my searches I think it’s because -G uses POSIX regex that don't support negative lookaround.

I think this requires Perl-compatible regex support. git log has a --perl-regexp flag, but from the documentation and examples I only see how to use it to search the commit message for fields like author, not the code.

How can I use Perl regex to search code with git log?

like image 287
Kane Parkinson Avatar asked Dec 11 '14 21:12

Kane Parkinson


1 Answers

You could simulate the capability with the program below. It takes two arguments: a coarse filter that is likely to return more results than you want and then a full Perl pattern to narrow the results to what you want.

For the example in your question, you would run it as in

logrx port '(?<!sup)port'

which assumes the program is in logrx, executable, in your PATH, and so on.

#! /usr/bin/env perl

use strict;
use warnings;
no warnings 'exec';

die "Usage: $0 pickaxe-string perl-pattern\n"
  unless @ARGV == 2;

my($_S,$_G) = @ARGV;

my $filter = eval 'qr/^[-+]' . $_G . "/m"
  or die "$0: invalid perl pattern: $@";

sub filter { local($_) = @_; print if /$filter/ }

open my $log, "-|", "git", "log", "-p", "-S" . $_S, "--all"
  or die "$0: failed to start git log: $!";

my $commit;
while (<$log>) {
  if (/^commit [0-9a-f]{40}$/) {
    filter $commit if defined $commit;
    $commit = $_;
  }
  else {
    $commit .= $_;
  }
}
filter $commit if defined $commit;
like image 67
Greg Bacon Avatar answered Oct 05 '22 09:10

Greg Bacon