diff --git a/crates/ruff_linter/resources/test/fixtures/refurb/FURB188.py b/crates/ruff_linter/resources/test/fixtures/refurb/FURB188.py index 4593559518..8f58cb9d8f 100644 --- a/crates/ruff_linter/resources/test/fixtures/refurb/FURB188.py +++ b/crates/ruff_linter/resources/test/fixtures/refurb/FURB188.py @@ -197,4 +197,11 @@ def handle_surrogates(): text = "\ud800\udc00heythere" if text.startswith("\ud800\udc00"): text = text[1:] - \ No newline at end of file + +# Regression test for +# https://github.com/astral-sh/ruff/issues/16231 +def func(): + a = "sjdfaskldjfakljklfoo" + if a.endswith("foo"): + a = a[: -len("foo")] + print(a) diff --git a/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs b/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs index c475bc75d1..4623c008c3 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs @@ -365,7 +365,7 @@ fn affix_matches_slice_bound(data: &RemoveAffixData, semantic: &SemanticModel) - range: _, value: string_val, }), - ) => operand.as_number_literal_expr().is_some_and( + ) if operand.is_number_literal_expr() => operand.as_number_literal_expr().is_some_and( |ast::ExprNumberLiteral { value, .. }| { // Only support prefix removal for size at most `u32::MAX` value diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap index 4627dab5ec..70966a24be 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap @@ -313,3 +313,23 @@ FURB188.py:193:5: FURB188 [*] Prefer `str.removeprefix()` over conditionally rep 195 194 | 196 195 | # should not be linted 197 196 | text = "\ud800\udc00heythere" + +FURB188.py:205:5: FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. + | +203 | def func(): +204 | a = "sjdfaskldjfakljklfoo" +205 | / if a.endswith("foo"): +206 | | a = a[: -len("foo")] + | |____________________________^ FURB188 +207 | print(a) + | + = help: Use removesuffix instead of assignment conditional upon endswith. + +ℹ Safe fix +202 202 | # https://github.com/astral-sh/ruff/issues/16231 +203 203 | def func(): +204 204 | a = "sjdfaskldjfakljklfoo" +205 |- if a.endswith("foo"): +206 |- a = a[: -len("foo")] + 205 |+ a = a.removesuffix("foo") +207 206 | print(a)