Skip to content

Commit

Permalink
feat: process fstring when python version gte 3.12
Browse files Browse the repository at this point in the history
  • Loading branch information
iFurySt committed Apr 15, 2024
1 parent 0d20f18 commit 2b9a457
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
11 changes: 11 additions & 0 deletions pre_commit_hooks/string_fixer.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,26 @@ def fix_strings(filename: str) -> int:
splitcontents = list(contents)

fstring_depth = 0
fstring_content = ''
f_erow = f_ecol = -1

# Iterate in reverse so the offsets are always correct
tokens_l = list(tokenize.generate_tokens(io.StringIO(contents).readline))
tokens = reversed(tokens_l)
for token_type, token_text, (srow, scol), (erow, ecol), _ in tokens:
if token_type == FSTRING_START: # pragma: >=3.12 cover
fstring_depth += 1
splitcontents[
line_offsets[srow] + scol:
line_offsets[f_erow] + f_ecol
] = handle_match(token_text + fstring_content)
fstring_content = ''
elif token_type == FSTRING_END: # pragma: >=3.12 cover
fstring_depth -= 1
fstring_content = token_text + fstring_content
f_erow, f_ecol = erow, ecol
elif fstring_depth != 0: # pragma: >=3.12 cover
fstring_content = token_text + fstring_content
elif fstring_depth == 0 and token_type == tokenize.STRING:
new_text = handle_match(token_text)
splitcontents[
Expand Down
6 changes: 6 additions & 0 deletions tests/string_fixer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@
0,
id='ignore nested fstrings',
),
pytest.param(
'f"Error during task loop"',
"f'Error during task loop'",
1,
id='replace the fstrings when python version is greater than and equal to 3.12',
),
)


Expand Down

0 comments on commit 2b9a457

Please sign in to comment.