Skip to content

Commit 973467f

Browse files
committed
Fix masking of f-strings
1 parent eeda4a9 commit 973467f

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

pyqt_code_editor/utils/languages/python/_mask_str_in_code.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,17 @@ def mask_str_in_code(code: str, mask_char: str = 'X') -> str:
4040
"""
4141
# First handle f-strings separately using regex
4242
# This regex matches f-strings with their content
43-
fstring_pattern = r'(f)(""".*?"""|\'\'\'.*?\'\'\'|".*?"|\'.*?\')'
43+
# Make sure 'f' is preceded by something that indicates start of a new token
44+
fstring_pattern = r'(?:^|[^a-zA-Z0-9_"\'])(f)(""".*?"""|\'\'\'.*?\'\'\'|".*?"|\'.*?\')'
4445

4546
def mask_fstring(match):
46-
prefix = match.group(1)
47+
# Get the character before 'f' (if any)
48+
full_match = match.group(0)
49+
prefix_char = ''
50+
if not full_match.startswith('f'):
51+
prefix_char = full_match[0]
52+
53+
prefix = match.group(1) # 'f'
4754
full_string = match.group(2)
4855
quote = ''
4956
content = ''
@@ -57,7 +64,7 @@ def mask_fstring(match):
5764

5865
# Mask everything in f-string content
5966
masked_content = mask_char * len(content)
60-
return prefix + quote + masked_content + quote
67+
return prefix_char + prefix + quote + masked_content + quote
6168

6269
# Apply f-string masking
6370
code = re.sub(fstring_pattern, mask_fstring, code, flags=re.DOTALL)
@@ -76,7 +83,6 @@ def mask_fstring(match):
7683
if token.type == tokenize.STRING:
7784
# Get the string content including quotes
7885
string_value = token.string
79-
8086
# Skip if it looks like an f-string (already handled)
8187
if string_value.startswith(('f"', "f'", 'f"""', "f'''")):
8288
# Add any code between last token and this one
@@ -182,4 +188,4 @@ def mask_fstring(match):
182188
masked_parts.append('\n')
183189
masked_parts.extend('\n'.join(lines[end_line:]))
184190

185-
return ''.join(masked_parts)
191+
return ''.join(masked_parts)

tests/test_python_mask_str.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,21 @@ def test_f_string():
3939
expected = '''name = "XXXX"
4040
print(f"XXXXXXXXXXXXX")'''
4141
assert result == expected
42+
43+
def test_non_f_string():
44+
code = 'call(".2f")\n"""test"""'
45+
result = mask_str_in_code(code)
46+
assert result == 'call("XXX")\n"""XXXX"""'
4247

4348
def test_raw_string():
4449
code = r'path = r"C:\Users\test"'
4550
result = mask_str_in_code(code)
4651
assert result == r'path = r"XXXXXXXXXXXXX"'
52+
53+
def test_non_r_string():
54+
code = 'call(".2r")\n"""test"""'
55+
result = mask_str_in_code(code)
56+
assert result == 'call("XXX")\n"""XXXX"""'
4757

4858
def test_custom_mask_char():
4959
code = "print('secret')"

0 commit comments

Comments
 (0)