Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix file.comment state picks up comments after config in line #62122

Merged
merged 2 commits into from
May 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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(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())