Skip to content

Commit 069be94

Browse files
committed
Fix re.subn DeprecationWarning in file.replace
Pass count as a keyword argument to all three re.subn() calls in salt.modules.file.replace to silence the Python 3.12+ DeprecationWarning: 'count' is passed as positional argument. Add regression test and changelog entry.
1 parent b9b3c63 commit 069be94

3 files changed

Lines changed: 18 additions & 3 deletions

File tree

changelog/69497.fixed.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed `DeprecationWarning: 'count' is passed as positional argument` emitted by all three `re.subn` calls in `salt.modules.file.replace` on Python 3.12+.

salt/modules/file.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2543,7 +2543,7 @@ def replace(
25432543
cpattern,
25442544
repl_str.replace("\\", "\\\\") if backslash_literal else repl_str,
25452545
orig_contents,
2546-
count,
2546+
count=count,
25472547
)
25482548

25492549
found = nrepl > 0
@@ -2700,7 +2700,7 @@ def replace(
27002700
cpattern,
27012701
repl.replace(b"\\", b"\\\\") if backslash_literal else repl,
27022702
r_data,
2703-
count,
2703+
count=count,
27042704
)
27052705

27062706
# found anything? (even if no change)
@@ -2759,7 +2759,7 @@ def replace(
27592759
cpattern,
27602760
repl.replace(b"\\", b"\\\\") if backslash_literal else repl,
27612761
r_data,
2762-
count,
2762+
count=count,
27632763
)
27642764
try:
27652765
w_file.write(salt.utils.stringutils.to_str(result))

tests/pytests/functional/modules/file/test_replace.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,17 @@ def test_replace_no_modify_time_update_on_no_change(file, multiline_file):
211211
def test_backslash_literal(file, multiline_file):
212212
file.replace(str(multiline_file), r"Etiam", "Emma", backslash_literal=True)
213213
assert "Emma" in multiline_file.read_text()
214+
215+
216+
def test_replace_count_no_deprecation_warning(file, multiline_file):
217+
"""
218+
Regression test for https://github.com/saltstack/salt/pull/69497.
219+
file.replace must not emit a DeprecationWarning for passing 'count'
220+
as a positional argument to re.subn.
221+
"""
222+
import warnings
223+
224+
with warnings.catch_warnings():
225+
warnings.simplefilter("error", DeprecationWarning)
226+
file.replace(str(multiline_file), r"Etiam", "Salticus", count=1)
227+
assert "Salticus" in multiline_file.read_text()

0 commit comments

Comments
 (0)