Allow not interpreting backslashes in the repl

Without this, if append or prepend is used with file.replace, the backslashes
will not be interpreted when appending the file, but the next time the state is
run, the backslashes could be interpreted and removed from the line.
This commit is contained in:
Daniel Wallace 2017-07-24 11:54:42 -06:00
parent 53e25760be
commit cc4e45656d
2 changed files with 29 additions and 5 deletions

View file

@ -1884,6 +1884,7 @@ def replace(path,
show_changes=True,
ignore_if_missing=False,
preserve_inode=True,
backslash_literal=False,
):
'''
.. versionadded:: 0.17.0
@ -1984,6 +1985,14 @@ def replace(path,
filename. Hard links will then share an inode with the backup, instead
(if using ``backup`` to create a backup copy).
backslash_literal : False
.. versionadded:: 2016.11.7
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
@ -2080,7 +2089,10 @@ def replace(path,
if re.search(cpattern, r_data):
return True # `with` block handles file closure
else:
result, nrepl = re.subn(cpattern, repl, r_data, count)
result, nrepl = re.subn(cpattern,
repl.replace('\\', '\\\\') if backslash_literal else repl,
r_data,
count)
# found anything? (even if no change)
if nrepl > 0:
@ -2138,8 +2150,10 @@ def replace(path,
r_data = mmap.mmap(r_file.fileno(),
0,
access=mmap.ACCESS_READ)
result, nrepl = re.subn(cpattern, repl,
r_data, count)
result, nrepl = re.subn(cpattern,
repl.replace('\\', '\\\\') if backslash_literal else repl,
r_data,
count)
try:
w_file.write(salt.utils.to_str(result))
except (OSError, IOError) as exc:

View file

@ -3261,7 +3261,8 @@ def replace(name,
not_found_content=None,
backup='.bak',
show_changes=True,
ignore_if_missing=False):
ignore_if_missing=False,
backslash_literal=False):
r'''
Maintain an edit in a file.
@ -3351,6 +3352,14 @@ def replace(name,
state will display an error raised by the execution module. If set to
``True``, the state will simply report no changes.
backslash_literal : False
.. versionadded:: 2016.11.7
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
For complex regex patterns, it can be useful to avoid the need for complex
quoting and escape sequences by making use of YAML's multiline string
syntax.
@ -3399,7 +3408,8 @@ def replace(name,
backup=backup,
dry_run=__opts__['test'],
show_changes=show_changes,
ignore_if_missing=ignore_if_missing)
ignore_if_missing=ignore_if_missing,
backslash_literal=backslash_literal)
if changes:
ret['pchanges']['diff'] = changes