diff --git a/salt/states/file.py b/salt/states/file.py index 8ec79382dd5c..a37ca008d1fb 100644 --- a/salt/states/file.py +++ b/salt/states/file.py @@ -5186,15 +5186,9 @@ def comment(name, regex, char='#', backup='.bak'): comment_regex = char + unanchor_regex - # Check if the line is already commented - if __salt__['file.search'](name, comment_regex, multiline=True): - commented = True - else: - commented = False - # Make sure the pattern appears in the file before continuing - if commented or not __salt__['file.search'](name, regex, multiline=True): - if __salt__['file.search'](name, unanchor_regex, multiline=True): + if not __salt__['file.search'](name, regex, multiline=True): + if __salt__['file.search'](name, comment_regex, multiline=True): ret['comment'] = 'Pattern already commented' ret['result'] = True return ret @@ -5292,18 +5286,18 @@ def uncomment(name, regex, char='#', backup='.bak'): # Make sure the pattern appears in the file if __salt__['file.search']( + name, + '{0}[ \t]*{1}'.format(char, regex.lstrip('^')), + multiline=True): + # Line exists and is commented + pass + elif __salt__['file.search']( name, '^[ \t]*{0}'.format(regex.lstrip('^')), multiline=True): ret['comment'] = 'Pattern already uncommented' ret['result'] = True return ret - elif __salt__['file.search']( - name, - '{0}[ \t]*{1}'.format(char, regex.lstrip('^')), - multiline=True): - # Line exists and is commented - pass else: return _error(ret, '{0}: Pattern not found'.format(regex)) diff --git a/tests/unit/states/test_file.py b/tests/unit/states/test_file.py index 546b209a147e..94f5a80d6b83 100644 --- a/tests/unit/states/test_file.py +++ b/tests/unit/states/test_file.py @@ -1468,7 +1468,7 @@ def test_comment(self): with patch.object(os.path, 'isabs', mock_t): with patch.dict(filestate.__salt__, - {'file.search': MagicMock(side_effect=[True, True, True, False, False])}): + {'file.search': MagicMock(side_effect=[False, True, False, False])}): comt = ('Pattern already commented') ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.comment(name, regex), ret) @@ -1478,7 +1478,7 @@ def test_comment(self): self.assertDictEqual(filestate.comment(name, regex), ret) with patch.dict(filestate.__salt__, - {'file.search': MagicMock(side_effect=[False, True, False, True, True]), + {'file.search': MagicMock(side_effect=[True, True, True]), 'file.comment': mock_t, 'file.comment_line': mock_t}): with patch.dict(filestate.__opts__, {'test': True}): @@ -1516,7 +1516,9 @@ def test_uncomment(self): mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) - mock = MagicMock(side_effect=[True, False, False, False, True, False, + mock = MagicMock(side_effect=[False, True, + False, False, + True, True, True]) with patch.object(os.path, 'isabs', mock_f): comt = ('Specified file {0} is not an absolute path'.format(name))