Skip to content

Commit

Permalink
Merge pull request #114 from buty4649/add-color-option
Browse files Browse the repository at this point in the history
Add --color option to text filter
  • Loading branch information
buty4649 authored Nov 6, 2023
2 parents 8ca8f37 + 8b7ec7b commit 0c847b0
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 17 deletions.
26 changes: 18 additions & 8 deletions mrblib/rf/00filter/text.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@ module Filter
class Text < Base
class << self
def config
@config ||= Struct.new(:fs).new
@config ||= Struct.new(:fs, :color).new.tap do |c|
c.color = true
end
end

def configure(opt)
opt.on('-F VAL', '--filed-separator', 'set the field separator(regexp)') do |v|
config.fs = v
end
opt.on('--[no-]color', '[no] colorized output (default: --color)') do |v|
config.color = v
end
end

def format(val, record)
Expand All @@ -19,19 +24,24 @@ def format(val, record)
when true
record
when Regexp
return unless m = val.match(record)

[
m.pre_match,
m.to_s.red,
m.post_match
].join
regexp_to_text(val, record)
when Array
val.map(&:to_s).join("\n")
else
val.to_s
end
end

def regexp_to_text(regexp, record)
return unless m = regexp.match(record)

text = m.to_s.then { |s| config.color ? s.red : s }
[
m.pre_match,
text,
m.post_match
].join
end
end

def config
Expand Down
38 changes: 29 additions & 9 deletions spec/filter/text_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,17 +113,37 @@
end

describe 'Output only the lines that match the regexp' do
let(:output) do
<<~OUTPUT
1 \e[31mfoo\e[0m
4 \e[31mfoo\e[0mbar
OUTPUT
where do
{
'default' => {
option: '',
output: <<~OUTPUT
1 \e[31mfoo\e[0m
4 \e[31mfoo\e[0mbar
OUTPUT
},
'--color' => {
option: '--color',
output: <<~OUTPUT
1 \e[31mfoo\e[0m
4 \e[31mfoo\e[0mbar
OUTPUT
},
'--no-color' => {
option: '--no-color',
output: <<~OUTPUT
1 foo
4 foobar
OUTPUT
}
}
end
with_them do
before { run_rf("#{option} /foo/", input) }

before { run_rf('/foo/', input) }

it { expect(last_command_started).to be_successfully_executed }
it { expect(last_command_started).to have_output_on_stdout output_string_eq output }
it { expect(last_command_started).to be_successfully_executed }
it { expect(last_command_started).to have_output_on_stdout output_string_eq output }
end
end

describe 'Output only the substring that matches the regexp' do
Expand Down
1 change: 1 addition & 0 deletions spec/help_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
text options:
-F, --filed-separator VAL set the field separator(regexp)
--[no-]color [no] colorized output (default: --color)
json options:
-r, --raw-string output raw strings
Expand Down

0 comments on commit 0c847b0

Please sign in to comment.