Class: Onlylogs::Grep

Inherits:
Object
  • Object
show all
Defined in:
app/models/onlylogs/grep.rb

Class Method Summary collapse

Class Method Details

.grep(pattern, file_path, start_position: 0, end_position: nil, regexp_mode: false, &block) ⇒ Object



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
# File 'app/models/onlylogs/grep.rb', line 3

def self.grep(pattern, file_path, start_position: 0, end_position: nil, regexp_mode: false, &block)
  # Use the appropriate script based on configuration
  script_name = Onlylogs.ripgrep_enabled? ? "super_ripgrep" : "super_grep"
  super_grep_path = ::File.expand_path("../../../bin/#{script_name}", __dir__)

  command_args = [ super_grep_path ]
  command_args += [ "--max-matches", Onlylogs.max_line_matches.to_s ] if Onlylogs.max_line_matches.present?
  command_args << "--regexp" if regexp_mode

  # Add byte range parameters if specified
  if start_position > 0 || end_position
    command_args << "--start-position" << start_position.to_s
    command_args << "--end-position" << end_position.to_s if end_position
  end

  command_args += [ pattern, file_path ]

  results = []

  IO.popen(command_args, err: "/dev/null") do |io|
    io.each_line do |line|
      # Parse each line as it comes in - super_grep returns grep output with line numbers (format: line_number:content)
      if match = line.strip.match(/^(\d+):(.*)/)
        line_number = match[1].to_i
        content = match[2]

        if block_given?
          yield line_number, content
        else
          results << [ line_number, content ]
        end
      end
    end
  end

  block_given? ? nil : results
end

.match_line?(line, string, regexp_mode: false) ⇒ Boolean

Returns:



41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/models/onlylogs/grep.rb', line 41

def self.match_line?(line, string, regexp_mode: false)
  # Strip ANSI color codes from the line before matching
  stripped_line = line.gsub(/\e\[[0-9;]*m/, "")
  # Normalize multiple spaces to single spaces
  normalized_line = stripped_line.gsub(/\s+/, " ")

  if regexp_mode
    normalized_line.match?(string)
  else
    normalized_line.match?(Regexp.escape(string))
  end
end