class PreCommit::Checks::Grep

Public Class Methods

new(*) click to toggle source
Calls superclass method
# File lib/pre-commit/checks/grep.rb, line 10
def initialize(*)
  super

  @extra_grep = nil
  @message = nil
  @pattern = nil
end

Public Instance Methods

call(staged_files) click to toggle source

general code:

# File lib/pre-commit/checks/grep.rb, line 48
def call(staged_files)
  staged_files = files_filter(staged_files)
  return if staged_files.empty?

  result =
  in_groups(staged_files).map do |files|
    args = grep + [pattern] + files
    args += ["|", "grep"] + extra_grep if !extra_grep.nil? and !extra_grep.empty?

    results = [
      execute(args, success_status: false),
      extra_execute(files)
    ].compact

    results.empty? ? nil : results.join('')
  end.compact

  result.empty? ? nil : parse_errors(message, result)
end
extra_grep() click to toggle source
# File lib/pre-commit/checks/grep.rb, line 30
def extra_grep
  @extra_grep or []
end
extra_pattern() click to toggle source
# File lib/pre-commit/checks/grep.rb, line 42
def extra_pattern
  @extra_pattern
end
files_filter(staged_files) click to toggle source

overwrite those:

# File lib/pre-commit/checks/grep.rb, line 26
def files_filter(staged_files)
  staged_files
end
message() click to toggle source
# File lib/pre-commit/checks/grep.rb, line 34
def message
  @message or ""
end
pattern() click to toggle source
# File lib/pre-commit/checks/grep.rb, line 38
def pattern
  @pattern or raise PaternNotSet.new
end

Private Instance Methods

detect_grep_version() click to toggle source
# File lib/pre-commit/checks/grep.rb, line 95
def detect_grep_version
  Open3.popen3('grep', '--version') do |_, stdout, _|
    return '' if stdout.eof?

    first_line = stdout.readline
    return first_line.sub(/^[^0-9.]*\([0-9.]*\)$/, '\1')
  end
end
extra_execute(files) click to toggle source
# File lib/pre-commit/checks/grep.rb, line 104
def extra_execute(files)
  return nil if extra_pattern.nil? or extra_pattern.empty?
  args = grep + [extra_pattern] + files

  execute(args, success_status: false)
end
grep(grep_version = nil) click to toggle source
# File lib/pre-commit/checks/grep.rb, line 86
def grep(grep_version = nil)
  grep_version ||= detect_grep_version
  if grep_version =~ /FreeBSD/
    %w{grep -EnIH}
  else
    %w{grep -PnIH}
  end
end
parse_error(line) click to toggle source
# File lib/pre-commit/checks/grep.rb, line 81
def parse_error(line)
  matches = /^([^:]+):([[:digit:]]+):(.*)$/.match(line)
  matches and matches.captures
end
parse_errors(message, list) click to toggle source
# File lib/pre-commit/checks/grep.rb, line 70
def parse_errors(message, list)
  result = PreCommit::ErrorList.new(message)
  result.errors +=
  list.map do |group|
    group.split(/\n/)
  end.flatten.compact.map do |line|
    PreCommit::Line.new(nil, *parse_error(line))
  end
  result
end