Skip to content

Commit

Permalink
Fix Style/CommandLiteral autocorrection when %x is not configured
Browse files Browse the repository at this point in the history
It crashed with undefined method 'split' for nil:NilClass when
PreferredDelimiters for %x was not configured.
This commit changed the behavior to use the default PreferredDelimiters
when %x does not exist.
  • Loading branch information
ChrisBr authored and bbatsov committed May 14, 2018
1 parent 8f311a3 commit 6f0ae69
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/rubocop/cop/style/command_literal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def autocorrect(node)
return if contains_backtick?(node)

replacement = if backtick_literal?(node)
['%x', ''].zip(preferred_delimiters).map(&:join)
['%x', ''].zip(preferred_delimiter).map(&:join)
else
%w[` `]
end
Expand Down Expand Up @@ -169,9 +169,21 @@ def backtick_literal?(node)
node.loc.begin.source == '`'
end

def preferred_delimiters
def preferred_delimiter
(command_delimiter || default_delimiter).split(//)
end

def command_delimiter
preferred_delimiters_config['%x']
end

def default_delimiter
preferred_delimiters_config['default']
end

def preferred_delimiters_config
config.for_cop('Style/PercentLiteralDelimiters') \
['PreferredDelimiters']['%x'].split(//)
['PreferredDelimiters']
end
end
end
Expand Down
24 changes: 24 additions & 0 deletions spec/rubocop/cop/style/command_literal_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@
end
end

describe 'when PercentLiteralDelimiters only has a default' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
let(:percent_literal_delimiters_config) do
{ 'PreferredDelimiters' => { 'default' => '()' } }
end

it 'respects the configuration when auto-correcting' do
new_source = autocorrect_source('`ls`')
expect(new_source).to eq('%x(ls)')
end
end

describe 'when PercentLiteralDelimiters is configured and a default exists' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
let(:percent_literal_delimiters_config) do
{ 'PreferredDelimiters' => { '%x' => '[]', 'default' => '()' } }
end

it 'ignores the default when auto-correcting and' do
new_source = autocorrect_source('`ls`')
expect(new_source).to eq('%x[ls]')
end
end

describe 'heredoc commands' do
let(:cop_config) { { 'EnforcedStyle' => 'backticks' } }

Expand Down

0 comments on commit 6f0ae69

Please sign in to comment.