1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Fixed subsection replacement with before/after patterns

* using a _named_ capture in our assembled pattern, since before/after could potentially contain their own parenthesized captures
* ensuring we only replace against the named capture in question
* removing some duplication in the regexp replacement, that was introduced in ansible/ansible#22535
* fixed edge case of before/after not matching file content to replace

Fixes ansible/ansible#24840
This commit is contained in:
Evan Kaufman 2017-05-21 12:09:06 -07:00 committed by Toshio Kuratomi
parent 5bd4e01533
commit 3d1701b959

View file

@ -242,28 +242,30 @@ def main():
pattern = u'' pattern = u''
if params['after'] and params['before']: if params['after'] and params['before']:
pattern = u'%s(.*?)%s' % (params['before'], params['after']) pattern = u'%s(?P<subsection>.*?)%s' % (params['before'], params['after'])
elif params['after']: elif params['after']:
pattern = u'%s(.*)' % params['after'] pattern = u'%s(?P<subsection>.*)' % params['after']
elif params['before']: elif params['before']:
pattern = u'(.*)%s' % params['before'] pattern = u'(?P<subsection>.*)%s' % params['before']
if pattern: if pattern:
section_re = re.compile(pattern, re.DOTALL) section_re = re.compile(pattern, re.DOTALL)
match = re.search(section_re, contents) match = re.search(section_re, contents)
if match: if match:
section = match.group(0) section = match.group('subsection')
else:
res_args['msg'] = 'Pattern for before/after params did not match the given file: %s' % pattern
res_args['changed'] = False
module.exit_json(**res_args)
else:
section = contents
mre = re.compile(params['regexp'], re.MULTILINE) mre = re.compile(params['regexp'], re.MULTILINE)
result = re.subn(mre, params['replace'], section, 0) result = re.subn(mre, params['replace'], section, 0)
if result[1] > 0 and section != result[0]: if result[1] > 0 and section != result[0]:
if pattern:
result = (contents.replace(section, result[0]), result[1]) result = (contents.replace(section, result[0]), result[1])
else:
mre = re.compile(params['regexp'], re.MULTILINE)
result = re.subn(mre, params['replace'], contents, 0)
if result[1] > 0 and contents != result[0]:
msg = '%s replacements made' % result[1] msg = '%s replacements made' % result[1]
changed = True changed = True
if module._diff: if module._diff: