diff --git a/mrblib/rf/00filter/text.rb b/mrblib/rf/00filter/text.rb index 72c5135..a727838 100644 --- a/mrblib/rf/00filter/text.rb +++ b/mrblib/rf/00filter/text.rb @@ -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) @@ -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 diff --git a/spec/filter/text_spec.rb b/spec/filter/text_spec.rb index f436a16..149ff88 100644 --- a/spec/filter/text_spec.rb +++ b/spec/filter/text_spec.rb @@ -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 diff --git a/spec/help_spec.rb b/spec/help_spec.rb index fa96e50..2d88716 100644 --- a/spec/help_spec.rb +++ b/spec/help_spec.rb @@ -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