From f1254cd06bf0aacd6a0bf71d9e6cd0bd6e0cf06b Mon Sep 17 00:00:00 2001 From: nicholasmhughes Date: Tue, 14 Nov 2023 16:25:13 -0500 Subject: [PATCH] fixes saltstack/salt#65501 file.comment ignore_missing not working with multiline char (cherry picked from commit c5fbfa1fe74da3aa6a736653635cb857a74e8bc0) # Conflicts: # salt/states/file.py --- changelog/65501.fixed.md | 1 + salt/states/file.py | 2 +- .../functional/states/file/test_comment.py | 15 ++++++++++++++- 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 changelog/65501.fixed.md diff --git a/changelog/65501.fixed.md b/changelog/65501.fixed.md new file mode 100644 index 000000000000..31592c67e701 --- /dev/null +++ b/changelog/65501.fixed.md @@ -0,0 +1 @@ +Fix file.comment ignore_missing not working with multiline char diff --git a/salt/states/file.py b/salt/states/file.py index 9508a4c2faf2..d6082ebdeb1b 100644 --- a/salt/states/file.py +++ b/salt/states/file.py @@ -6158,7 +6158,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 = r"^(?!\s*{}).*".format(char) + unanchor_regex + uncomment_regex = rf"^(?!\s*{char})\s*" + 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 index 377e6b1b0e60..b7a7c8a7c951 100644 --- a/tests/pytests/functional/states/file/test_comment.py +++ b/tests/pytests/functional/states/file/test_comment.py @@ -106,7 +106,7 @@ def test_issue_2401_file_comment(modules, tmp_path): tmp_file.write_text("hello\nworld\n") # create the sls template template_lines = [ - "{}:".format(tmp_file), + f"{tmp_file}:", " file.comment:", " - regex: ^world", ] @@ -122,3 +122,16 @@ def test_issue_2401_file_comment(modules, tmp_path): for state_run in ret: assert state_run.result is True assert "Pattern already commented" in state_run.comment + + +def test_issue_65501(file, tmp_path): + tmp_file = tmp_path / "issue-65501.txt" + tmp_file.write_text("first\n#PermitRootLogin prohibit-password\nlast") + ret = file.comment( + name=str(tmp_file), + regex="^PermitRootLogin[ \t]+.*$", + char="# NEXT LINE COMMENT SALTSTACK openssh-server_comment_permitrootlogin_sshd_config\n# ", + ignore_missing=True, + ) + assert ret.result is True + assert ret.comment == "Pattern not found and ignore_missing set to True"