Skip to content
This repository has been archived by the owner on Apr 19, 2018. It is now read-only.

Commit

Permalink
Merge pull request #19 from jacargentina/grep
Browse files Browse the repository at this point in the history
Implemented grep support
  • Loading branch information
dzaporozhets committed Apr 30, 2013
2 parents 42297cd + cea676f commit e873bb8
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/grit.rb
Expand Up @@ -47,6 +47,7 @@
require 'grit/submodule'
require 'grit/blame'
require 'grit/merge'
require 'grit/grep'

module Grit
VERSION = '2.5.0'
Expand Down
21 changes: 21 additions & 0 deletions lib/grit/grep.rb
@@ -0,0 +1,21 @@
module Grit

class Grep

attr_reader :repo
attr_reader :filename
attr_reader :startline
attr_reader :content
attr_reader :is_binary

def initialize(repo, filename, startline, content, is_binary)
@repo = repo
@filename = filename
@startline = startline.to_i
@content = content
@is_binary = is_binary
end

end

end
38 changes: 38 additions & 0 deletions lib/grit/repo.rb
Expand Up @@ -713,6 +713,44 @@ def rename(name)
end
end

def grep(searchtext, contextlines = 3, branch = 'master')
context_arg = '-C ' + contextlines.to_s
result = git.native(:grep, {}, '-n', '-E', '-i', '-z', '--heading', '--break', context_arg, searchtext, branch).force_encoding('UTF-8')
greps = []
filematches = result.split("\n\n")
filematches.each do |filematch|
binary = false
file = ''
matches = filematch.split("--\n")
matches.each_with_index do |match, i|
content = []
startline = 0
lines = match.split("\n")
if i == 0
text = lines.first
lines.slice!(0)
file = text[/^Binary file (.+) matches$/]
if file
binary = true
else
text.slice! /^#{branch}:/
file = text
end
end
lines.each_with_index do |line, j|
line.chomp!
number, text = line.split("\0", 2)
if j == 0
startline = number.to_i
end
content << text
end
greps << Grit::Grep.new(self, file, startline, content, binary)
end
end
greps
end

# Pretty object inspection
def inspect
%Q{#<Grit::Repo "#{@path}">}
Expand Down
8 changes: 8 additions & 0 deletions test/test_repo.rb
Expand Up @@ -416,4 +416,12 @@ def test_select_existing_objects
after = ['634396b2f541a9f2d58b00be1a07f0c358b999b3']
assert_equal after, @r.git.select_existing_objects(before)
end

def test_grep
res = @r.grep('def test_select_existing_objects', 1, 'master')
assert_equal 1, res.length
assert_equal 413, res.first.startline
assert_equal 'test/test_repo.rb', res.first.filename
assert_equal ' def test_select_existing_objects', res.first.content[1]
end
end

0 comments on commit e873bb8

Please sign in to comment.