There was an error while loading. Please reload this page.
1 parent 6cad770 commit f27ee31Copy full SHA for f27ee31
2 files changed
pre_commit_hooks/string_fixer.py
@@ -3,9 +3,16 @@
3
import argparse
4
import io
5
import re
6
+import sys
7
import tokenize
8
from typing import Sequence
9
10
+if sys.version_info >= (3, 12): # pragma: >=3.12 cover
11
+ FSTRING_START = tokenize.FSTRING_START
12
+ FSTRING_END = tokenize.FSTRING_END
13
+else: # pragma: <3.12 cover
14
+ FSTRING_START = FSTRING_END = -1
15
+
16
START_QUOTE_RE = re.compile('^[a-zA-Z]*"')
17
18
@@ -40,11 +47,17 @@ def fix_strings(filename: str) -> int:
40
47
# Basically a mutable string
41
48
splitcontents = list(contents)
42
49
50
+ fstring_depth = 0
51
43
52
# Iterate in reverse so the offsets are always correct
44
53
tokens_l = list(tokenize.generate_tokens(io.StringIO(contents).readline))
45
54
tokens = reversed(tokens_l)
46
55
for token_type, token_text, (srow, scol), (erow, ecol), _ in tokens:
- if token_type == tokenize.STRING:
56
+ if token_type == FSTRING_START: # pragma: >=3.12 cover
57
+ fstring_depth += 1
58
+ elif token_type == FSTRING_END: # pragma: >=3.12 cover
59
+ fstring_depth -= 1
60
+ elif fstring_depth == 0 and token_type == tokenize.STRING:
61
new_text = handle_match(token_text)
62
splitcontents[
63
line_offsets[srow] + scol:
tests/string_fixer_test.py
@@ -37,6 +37,12 @@
37
1,
38
),
39
('"foo""bar"', "'foo''bar'", 1),
+ pytest.param(
+ "f'hello{\"world\"}'",
+ 0,
+ id='ignore nested fstrings',
+ ),
)
0 commit comments