-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-grep-blame.rb
62 lines (55 loc) · 1.67 KB
/
git-grep-blame.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env ruby
# git-grep-blame : combines `git grep -n` and `git blame`
#
# Used to find out the committer, commit SHA1, filename of lines in the
# repository that match a string we want to grep.
# Output is automatically piped to `less`
#
#
# Usage:
#
# ggb 'some_string'
# ggb '\bstring_with_regex\b'
$: << File.join(ENV['HOME'], 'bin')
require 'git_utils'
def construct_blame_string(commitSHA1, commitTimeStamp, author, filename,
lineNum, textMatched)
"#{commitSHA1} #{commitTimeStamp} [#{author}] #{filename}:#{lineNum} #{textMatched}"
end
def git_grep_blame(argv)
if argv.empty?
puts "#{$0}: please supply a string for git grep"
exit(1)
end
arr = []
# support 1 argument for now
gitGrepOut = `git grep -n '#{argv[0]}'`
gitGrepOut.split("\n").each do |line|
matchObj = /^(.*?):(\d+):(.*)$/.match(line)
next unless matchObj
fname = matchObj[1]
lineNum = matchObj[2].to_i
textMatched = matchObj[3]
gitBlameResult = `git blame -L#{lineNum},#{lineNum} '#{fname}'`
# capture SHA1 hash, committer name, commit timestamp
gitBlameResult.split("\n").each do |gbLine|
mObj = /^([0-9a-fA-F]{1,40}) \((.*)?(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [\+\-]?\d{4})/.match(gbLine)
if not mObj.nil?
commitSHA1 = mObj[1]
author = mObj[2].strip
commitTimeStamp = mObj[3]
arr.push(
construct_blame_string(commitSHA1, commitTimeStamp, author, fname,
lineNum, textMatched)
)
end
end
end
IO.popen("less", "w") do |f|
arr.each do |line|
f.puts line
end
end
end
GitUtils::exit_if_not_in_git_repo $0
git_grep_blame ARGV