Lineinfile must not insert lines multiples times with insertbefore/insertafter (#49409)

* Change test suite to fit expected behaviour

This reverts some changes from ansible/ansible@723daf3
If a line is found in the file, exactly or via regexp matching, it must 
not be added again.
insertafter/insertbefore options are used only when a line is to be 
inserted, to specify where it must be added.

* Implement the change in behaviour mentioned in the previous commit

* Fix comment to reflect what the code does

* Set the correct return message.

In these cases, the lines are added, not replaced.

* Add a changelog
This commit is contained in:
Jérémy Lecour 2018-12-17 22:42:24 +01:00 committed by Sam Doran
commit 2fb9b46752
3 changed files with 54 additions and 23 deletions

View file

@ -302,7 +302,7 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create,
msg = ''
changed = False
b_linesep = to_bytes(os.linesep, errors='surrogate_or_strict')
# Regexp matched a line in the file
# Exact line or Regexp matched a line in the file
if index[0] != -1:
if backrefs:
b_new_line = m.expand(b_line)
@ -313,9 +313,9 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create,
if not b_new_line.endswith(b_linesep):
b_new_line += b_linesep
# If no regexp was given and a line match is found anywhere in the file,
# If no regexp was given and no line match is found anywhere in the file,
# insert the line appropriately if using insertbefore or insertafter
if regexp is None and m:
if regexp is None and m is None:
# Insert lines
if insertafter and insertafter != 'EOF':
@ -342,12 +342,12 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create,
if index[1] <= 0:
if b_lines[index[1]].rstrip(b('\r\n')) != b_line:
b_lines.insert(index[1], b_line + b_linesep)
msg = 'line replaced'
msg = 'line added'
changed = True
elif b_lines[index[1] - 1].rstrip(b('\r\n')) != b_line:
b_lines.insert(index[1], b_line + b_linesep)
msg = 'line replaced'
msg = 'line added'
changed = True
elif b_lines[index[0]] != b_new_line: