Skip to content

Commit

Permalink
fixes #62121 file.comment state picks up comments after config in the…
Browse files Browse the repository at this point in the history
… line
  • Loading branch information
nicholasmhughes authored and Megan Wilhite committed May 31, 2022
1 parent 5a18c14 commit 03f913c
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/62121.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix broken file.comment functionality introduced in #62045
2 changes: 1 addition & 1 deletion salt/states/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
54 changes: 54 additions & 0 deletions tests/pytests/functional/states/file/test_comment.py
Original file line number Diff line number Diff line change
@@ -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(source) as _fp:
assert reg_cmp.findall(_fp.read())

file.comment(name=str(source), regex=regex)

with salt.utils.files.fopen(source) as _fp:
assert not reg_cmp.findall(_fp.read())
_fp.seek(0)
assert cmt_cmp.findall(_fp.read())

0 comments on commit 03f913c

Please sign in to comment.