diff --git a/changelog/62121.fixed b/changelog/62121.fixed new file mode 100644 index 000000000000..927dca23734a --- /dev/null +++ b/changelog/62121.fixed @@ -0,0 +1 @@ +Fix broken file.comment functionality introduced in #62045 diff --git a/salt/states/file.py b/salt/states/file.py index b27907f8b468..41446f4cf6ea 100644 --- a/salt/states/file.py +++ b/salt/states/file.py @@ -6062,7 +6062,7 @@ def comment(name, regex, char="#", backup=".bak", ignore_missing=False): # remove (?i)-like flags, ^ and $ unanchor_regex = re.sub(r"^(\(\?[iLmsux]\))?\^?(.*?)\$?$", r"\2", regex) - uncomment_regex = "^(?!.*{}).*".format(char) + unanchor_regex + uncomment_regex = r"^(?!\s*{}).*".format(char) + unanchor_regex comment_regex = char + unanchor_regex # Make sure the pattern appears in the file before continuing diff --git a/tests/pytests/functional/states/file/test_comment.py b/tests/pytests/functional/states/file/test_comment.py new file mode 100644 index 000000000000..de061b9acec3 --- /dev/null +++ b/tests/pytests/functional/states/file/test_comment.py @@ -0,0 +1,54 @@ +""" +Tests for file.comment state function +""" +import re + +import pytest +import salt.utils.files +from tests.support.helpers import dedent + +pytestmark = [ + pytest.mark.windows_whitelisted, +] + + +@pytest.fixture(scope="module") +def file(states): + return states.file + + +@pytest.fixture(scope="function") +def source(): + with pytest.helpers.temp_file( + name="file.txt", + contents=dedent( + """ + things = stuff + port = 5432 # (change requires restart) + # commented = something + moar = things + """ + ), + ) as source: + yield source + + +def test_issue_62121(file, source): + """ + Test file.comment when the comment character is + later in the line, after the text + """ + regex = r"^port\s*=.+" + reg_cmp = re.compile(regex, re.MULTILINE) + cmt_regex = r"^#port\s*=.+" + cmt_cmp = re.compile(cmt_regex, re.MULTILINE) + + with salt.utils.files.fopen(str(source)) as _fp: + assert reg_cmp.findall(_fp.read()) + + file.comment(name=str(source), regex=regex) + + with salt.utils.files.fopen(str(source)) as _fp: + assert not reg_cmp.findall(_fp.read()) + _fp.seek(0) + assert cmt_cmp.findall(_fp.read())