Skip to content

Commit

Permalink
[Fix rubocop#12843] Fix an error for Lint/MixedCaseRange
Browse files Browse the repository at this point in the history
Fixes rubocop#12843.

This PR fixes an error for `Lint/MixedCaseRange`
when a character between `Z` and `a` is used in the regexp range.
  • Loading branch information
koic committed Apr 15, 2024
1 parent c6e0d4b commit 015e249
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_lint_mixed_case_range.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12843](https://github.com/rubocop/rubocop/issues/12843): Fix an error for `Lint/MixedCaseRange` when a character between `Z` and `a` is used in the regexp range. ([@koic][])
13 changes: 9 additions & 4 deletions lib/rubocop/cop/lint/mixed_case_range.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ def on_irange(node)

def on_regexp(node)
each_unsafe_regexp_range(node) do |loc|
next unless (replacement = regexp_range(loc.source))

add_offense(loc) do |corrector|
corrector.replace(loc, rewrite_regexp_range(loc.source))
corrector.replace(loc, replacement)
end
end
end
Expand Down Expand Up @@ -99,10 +101,13 @@ def skip_range?(range_start, range_end)
end
end

def rewrite_regexp_range(source)
def regexp_range(source)
open, close = source.split('-')
first = [open, range_for(open).end]
second = [range_for(close).begin, close]
return unless (open_range = range_for(open))
return unless (close_range = range_for(close))

first = [open, open_range.end]
second = [close_range.begin, close]
"#{first.uniq.join('-')}#{second.uniq.join('-')}"
end
end
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/lint/mixed_case_range_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,18 @@
RUBY
end

it 'does not register an offense when a character between `Z` and `a` is at the start of range.' do
expect_no_offenses(<<~RUBY)
foo = /[_-a]/
RUBY
end

it 'does not register an offense when a character between `Z` and `a` is at the end of range.' do
expect_no_offenses(<<~RUBY)
foo = /[A-_]/
RUBY
end

it 'does not register an offense with invalid byte sequence in UTF-8' do
expect_no_offenses(<<~'RUBY')
foo = /[\–]/
Expand Down

0 comments on commit 015e249

Please sign in to comment.