Skip to content

Commit fe2c663

Browse files
ggiesendwoz
authored andcommitted
Add encoding and encoding_errors params to file comment/append/prepend
Replace the hardcoded errors="replace" in the file.comment, file.append and file.prepend states with configurable encoding and encoding_errors parameters, mirroring file.managed. The default encoding_errors is "strict" (Python's own default); a file whose bytes are not valid in the system encoding is handled by setting encoding_errors=replace or a matching encoding, rather than the state aborting while building the change diff. Addresses review feedback on #50903.
1 parent 5ea5f95 commit fe2c663

5 files changed

Lines changed: 217 additions & 44 deletions

File tree

‎changelog/50903.fixed.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Fixed the file.comment, file.append, and file.prepend states failing with UnicodeDecodeError when the target file contains bytes that are not valid in the system encoding.
1+
Added ``encoding`` and ``encoding_errors`` parameters to the file.comment, file.append, and file.prepend states, mirroring file.managed. A file whose bytes are not valid in the system encoding can now be handled by setting ``encoding_errors: replace`` (or a matching ``encoding``) instead of the state aborting with a UnicodeDecodeError while building the change diff.

‎salt/states/file.py‎

Lines changed: 100 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6226,7 +6226,15 @@ def blockreplace(
62266226
return ret
62276227

62286228

6229-
def comment(name, regex, char="#", backup=".bak", ignore_missing=False):
6229+
def comment(
6230+
name,
6231+
regex,
6232+
char="#",
6233+
backup=".bak",
6234+
ignore_missing=False,
6235+
encoding=None,
6236+
encoding_errors="strict",
6237+
):
62306238
"""
62316239
.. versionadded:: 0.9.5
62326240
.. versionchanged:: 3005
@@ -6262,6 +6270,28 @@ def comment(name, regex, char="#", backup=".bak", ignore_missing=False):
62626270
62636271
.. versionadded:: 3005
62646272
6273+
encoding
6274+
If specified, this encoding is used to decode the file when building
6275+
the diff used for change detection. Otherwise the system locale
6276+
encoding (usually UTF-8) is used. This does not affect the file's
6277+
contents, which are modified as raw bytes by the underlying execution
6278+
module. See
6279+
https://docs.python.org/3/library/codecs.html#standard-encodings for
6280+
the list of available encodings.
6281+
6282+
.. versionadded:: 3006.28
6283+
6284+
encoding_errors
6285+
Error handling scheme used when decoding the file for the diff.
6286+
Default is ``'strict'``, matching Python's default, which raises a
6287+
``UnicodeDecodeError`` if the file contains bytes that are not valid in
6288+
the chosen encoding. Set to ``'replace'`` / ``'ignore'`` (or supply the
6289+
correct ``encoding``) to handle such files. See
6290+
https://docs.python.org/3/library/codecs.html#error-handlers for the
6291+
list of available schemes.
6292+
6293+
.. versionadded:: 3006.28
6294+
62656295
Usage:
62666296
62676297
.. code-block:: yaml
@@ -6308,15 +6338,19 @@ def comment(name, regex, char="#", backup=".bak", ignore_missing=False):
63086338

63096339
with salt.utils.files.fopen(name, "rb") as fp_:
63106340
slines = fp_.read()
6311-
slines = slines.decode(__salt_system_encoding__, errors="replace")
6341+
slines = slines.decode(
6342+
encoding or __salt_system_encoding__, errors=encoding_errors
6343+
)
63126344
slines = slines.splitlines(True)
63136345

63146346
# Perform the edit
63156347
__salt__["file.comment_line"](name, regex, char, True, backup)
63166348

63176349
with salt.utils.files.fopen(name, "rb") as fp_:
63186350
nlines = fp_.read()
6319-
nlines = nlines.decode(__salt_system_encoding__, errors="replace")
6351+
nlines = nlines.decode(
6352+
encoding or __salt_system_encoding__, errors=encoding_errors
6353+
)
63206354
nlines = nlines.splitlines(True)
63216355

63226356
# Check the result
@@ -6445,6 +6479,8 @@ def append(
64456479
defaults=None,
64466480
context=None,
64476481
ignore_whitespace=True,
6482+
encoding=None,
6483+
encoding_errors="strict",
64486484
):
64496485
"""
64506486
Ensure that some text appears at the end of a file.
@@ -6536,6 +6572,28 @@ def append(
65366572
appending content, one space or multiple tabs are the same for salt.
65376573
Set this option to ``False`` if you want to change this behavior.
65386574
6575+
encoding
6576+
If specified, this encoding is used to decode the file when building
6577+
the diff used for change detection. Otherwise the system locale
6578+
encoding (usually UTF-8) is used. This does not affect the file's
6579+
contents, which are modified as raw bytes by the underlying execution
6580+
module. See
6581+
https://docs.python.org/3/library/codecs.html#standard-encodings for
6582+
the list of available encodings.
6583+
6584+
.. versionadded:: 3006.28
6585+
6586+
encoding_errors
6587+
Error handling scheme used when decoding the file for the diff.
6588+
Default is ``'strict'``, matching Python's default, which raises a
6589+
``UnicodeDecodeError`` if the file contains bytes that are not valid in
6590+
the chosen encoding. Set to ``'replace'`` / ``'ignore'`` (or supply the
6591+
correct ``encoding``) to handle such files. See
6592+
https://docs.python.org/3/library/codecs.html#error-handlers for the
6593+
list of available schemes.
6594+
6595+
.. versionadded:: 3006.28
6596+
65396597
Multi-line example:
65406598
65416599
.. code-block:: yaml
@@ -6645,7 +6703,9 @@ def append(
66456703

66466704
with salt.utils.files.fopen(name, "rb") as fp_:
66476705
slines = fp_.read()
6648-
slines = slines.decode(__salt_system_encoding__, errors="replace")
6706+
slines = slines.decode(
6707+
encoding or __salt_system_encoding__, errors=encoding_errors
6708+
)
66496709
slines = slines.splitlines()
66506710

66516711
append_lines = []
@@ -6691,7 +6751,9 @@ def append(
66916751

66926752
with salt.utils.files.fopen(name, "rb") as fp_:
66936753
nlines = fp_.read()
6694-
nlines = nlines.decode(__salt_system_encoding__, errors="replace")
6754+
nlines = nlines.decode(
6755+
encoding or __salt_system_encoding__, errors=encoding_errors
6756+
)
66956757
nlines = nlines.splitlines()
66966758

66976759
if slines != nlines:
@@ -6718,6 +6780,8 @@ def prepend(
67186780
defaults=None,
67196781
context=None,
67206782
header=None,
6783+
encoding=None,
6784+
encoding_errors="strict",
67216785
):
67226786
"""
67236787
Ensure that some text appears at the beginning of a file
@@ -6809,6 +6873,28 @@ def prepend(
68096873
appending content, one space or multiple tabs are the same for salt.
68106874
Set this option to ``False`` if you want to change this behavior.
68116875
6876+
encoding
6877+
If specified, this encoding is used to decode the file when building
6878+
the diff used for change detection. Otherwise the system locale
6879+
encoding (usually UTF-8) is used. This does not affect the file's
6880+
contents, which are modified as raw bytes by the underlying execution
6881+
module. See
6882+
https://docs.python.org/3/library/codecs.html#standard-encodings for
6883+
the list of available encodings.
6884+
6885+
.. versionadded:: 3006.28
6886+
6887+
encoding_errors
6888+
Error handling scheme used when decoding the file for the diff.
6889+
Default is ``'strict'``, matching Python's default, which raises a
6890+
``UnicodeDecodeError`` if the file contains bytes that are not valid in
6891+
the chosen encoding. Set to ``'replace'`` / ``'ignore'`` (or supply the
6892+
correct ``encoding``) to handle such files. See
6893+
https://docs.python.org/3/library/codecs.html#error-handlers for the
6894+
list of available schemes.
6895+
6896+
.. versionadded:: 3006.28
6897+
68126898
Multi-line example:
68136899
68146900
.. code-block:: yaml
@@ -6930,7 +7016,9 @@ def prepend(
69307016

69317017
with salt.utils.files.fopen(name, "rb") as fp_:
69327018
slines = fp_.read()
6933-
slines = slines.decode(__salt_system_encoding__, errors="replace")
7019+
slines = slines.decode(
7020+
encoding or __salt_system_encoding__, errors=encoding_errors
7021+
)
69347022
slines = slines.splitlines(True)
69357023

69367024
count = 0
@@ -6978,7 +7066,9 @@ def prepend(
69787066
with salt.utils.files.fopen(name, "rb") as fp_:
69797067
# read as many lines of target file as length of user input
69807068
contents = fp_.read()
6981-
contents = contents.decode(__salt_system_encoding__, errors="replace")
7069+
contents = contents.decode(
7070+
encoding or __salt_system_encoding__, errors=encoding_errors
7071+
)
69827072
contents = contents.splitlines(True)
69837073
target_head = contents[0 : len(preface)]
69847074
target_lines = []
@@ -6997,7 +7087,9 @@ def prepend(
69977087

69987088
with salt.utils.files.fopen(name, "rb") as fp_:
69997089
nlines = fp_.read()
7000-
nlines = nlines.decode(__salt_system_encoding__, errors="replace")
7090+
nlines = nlines.decode(
7091+
encoding or __salt_system_encoding__, errors=encoding_errors
7092+
)
70017093
nlines = nlines.splitlines(True)
70027094

70037095
if slines != nlines:

‎tests/pytests/unit/states/file/test_append.py‎

Lines changed: 58 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,13 @@ def configure_loader_modules():
2121
}
2222

2323

24-
def test_append_file_encoding_mismatch(tmp_path):
24+
def test_append_encoding_mismatch_strict_raises_50903(tmp_path):
2525
"""
26-
file.append must not raise UnicodeDecodeError when the target file
27-
contains bytes that are not valid in the system encoding. The decoded
28-
contents are only used to build the diff, so undecodable bytes should
29-
be tolerated rather than aborting the state.
30-
31-
Regression test for #50903.
26+
With the default encoding_errors="strict" (matching Python's own default),
27+
file.append aborts with a UnicodeDecodeError when the target file contains
28+
bytes that are not valid in the encoding used to build the diff. This
29+
documents the default behaviour for #50903; encoding_errors="replace" (or a
30+
matching encoding) is the supported escape hatch, covered below.
3231
"""
3332
name = tmp_path / "bugfile"
3433
# 0xed is not valid ASCII and not valid UTF-8 on its own
@@ -43,19 +42,65 @@ def test_append_file_encoding_mismatch(tmp_path):
4342
with patch.object(builtins, "__salt_system_encoding__", "ascii"), patch.dict(
4443
filestate.__salt__, salt_mock
4544
), patch.dict(filestate.__utils__, utils_mock):
46-
result = filestate.append(name=str(name), text="cheese")
45+
with pytest.raises(UnicodeDecodeError):
46+
filestate.append(name=str(name), text="cheese")
47+
48+
49+
def test_append_encoding_mismatch_replace_50903(tmp_path):
50+
"""
51+
Setting encoding_errors="replace" lets file.append proceed on a file whose
52+
bytes are not valid in the diff encoding, instead of aborting. This is the
53+
#50903 escape hatch, called with the production-exact argument shape.
54+
"""
55+
name = tmp_path / "bugfile"
56+
name.write_bytes(b"abc\xedxyz\n")
57+
58+
salt_mock = {
59+
"file.search": MagicMock(return_value=False),
60+
"file.append": MagicMock(return_value=None),
61+
}
62+
utils_mock = {"files.is_text": MagicMock(return_value=True)}
63+
64+
with patch.object(builtins, "__salt_system_encoding__", "ascii"), patch.dict(
65+
filestate.__salt__, salt_mock
66+
), patch.dict(filestate.__utils__, utils_mock):
67+
result = filestate.append(
68+
name=str(name), text="cheese", encoding_errors="replace"
69+
)
70+
71+
assert result["result"] is True
72+
salt_mock["file.append"].assert_called_once()
73+
74+
75+
def test_append_encoding_override_handles_mismatch_50903(tmp_path):
76+
"""
77+
Supplying an encoding that can decode the file (latin-1 maps every byte) is
78+
an alternative to encoding_errors: the state proceeds under strict errors.
79+
"""
80+
name = tmp_path / "bugfile"
81+
name.write_bytes(b"abc\xedxyz\n")
82+
83+
salt_mock = {
84+
"file.search": MagicMock(return_value=False),
85+
"file.append": MagicMock(return_value=None),
86+
}
87+
utils_mock = {"files.is_text": MagicMock(return_value=True)}
88+
89+
with patch.object(builtins, "__salt_system_encoding__", "ascii"), patch.dict(
90+
filestate.__salt__, salt_mock
91+
), patch.dict(filestate.__utils__, utils_mock):
92+
result = filestate.append(name=str(name), text="cheese", encoding="latin-1")
4793

4894
assert result["result"] is True
4995
salt_mock["file.append"].assert_called_once()
5096

5197

5298
def test_append_clean_encoding_unaffected_50903(tmp_path):
5399
"""
54-
Guard against overcorrection of the #50903 fix: decoding with
55-
errors="replace" must not change behaviour for files that decode
56-
cleanly in the system encoding. The diff must still be generated,
57-
contain the original non-ASCII text unmangled, and hold no U+FFFD
58-
replacement characters. This test passes with and without the fix.
100+
Adding the encoding params must not change behaviour for files that decode
101+
cleanly under the default strict handling. The diff is still generated,
102+
contains the original non-ASCII text unmangled, and holds no U+FFFD
103+
replacement characters. This test passes with and without the change.
59104
"""
60105
name = tmp_path / "cleanfile"
61106
# Valid UTF-8 content that decodes cleanly with the utf-8 system encoding

‎tests/pytests/unit/states/file/test_comment.py‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -116,32 +116,50 @@ def test_comment():
116116
assert filestate.comment(name, regex) == ret
117117

118118

119-
def test_comment_file_encoding_mismatch_50903(tmp_path):
119+
def test_comment_encoding_mismatch_strict_raises_50903(tmp_path):
120120
"""
121-
file.comment must not raise UnicodeDecodeError when the target file
122-
contains bytes that are not valid in the system encoding. The decoded
123-
contents are only used to build the diff, so undecodable bytes should
124-
be tolerated rather than aborting the state.
125-
126-
Regression test for #50903.
121+
With the default encoding_errors="strict" (matching Python's own default),
122+
file.comment aborts with a UnicodeDecodeError when the target file contains
123+
bytes not valid in the encoding used to build the diff. This documents the
124+
#50903 default; encoding_errors="replace" is the escape hatch, covered next.
127125
"""
128126
name = tmp_path / "fstab"
129127
# 0xed is not valid ASCII and not valid UTF-8 on its own
130128
name.write_bytes(b"bind 127.0.0.1\nabc\xedxyz\n")
131129

130+
salt_mock = {
131+
"file.search": MagicMock(side_effect=[True, True]),
132+
"file.comment_line": MagicMock(return_value=True),
133+
}
134+
135+
with patch.object(builtins, "__salt_system_encoding__", "ascii"), patch.dict(
136+
filestate.__salt__, salt_mock
137+
):
138+
with pytest.raises(UnicodeDecodeError):
139+
filestate.comment(str(name), "^bind 127.0.0.1")
140+
141+
142+
def test_comment_encoding_mismatch_replace_50903(tmp_path):
143+
"""
144+
Setting encoding_errors="replace" lets file.comment proceed on a file whose
145+
bytes are not valid in the diff encoding, instead of aborting. The #50903
146+
escape hatch, called with the production-exact argument shape.
147+
"""
148+
name = tmp_path / "fstab"
149+
name.write_bytes(b"bind 127.0.0.1\nabc\xedxyz\n")
150+
132151
salt_mock = {
133152
# First search: uncommented pattern found; second: commented after edit
134153
"file.search": MagicMock(side_effect=[True, True]),
135154
"file.comment_line": MagicMock(return_value=True),
136155
}
137156

138-
# Production callers (the state compiler running an SLS file.comment)
139-
# pass name and regex; __salt_system_encoding__ is the locale-derived
140-
# builtin read by the decode sites, so it is patched rather than passed.
141157
with patch.object(builtins, "__salt_system_encoding__", "ascii"), patch.dict(
142158
filestate.__salt__, salt_mock
143159
):
144-
result = filestate.comment(str(name), "^bind 127.0.0.1")
160+
result = filestate.comment(
161+
str(name), "^bind 127.0.0.1", encoding_errors="replace"
162+
)
145163

146164
assert result["result"] is True
147165
assert result["comment"] == "Commented lines successfully"

0 commit comments

Comments
 (0)