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:
parent
5bd4e01533
commit
3d1701b959
1 changed files with 15 additions and 13 deletions
|
@ -242,28 +242,30 @@ def main():
|
|||
|
||||
pattern = u''
|
||||
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']:
|
||||
pattern = u'%s(.*)' % params['after']
|
||||
pattern = u'%s(?P<subsection>.*)' % params['after']
|
||||
elif params['before']:
|
||||
pattern = u'(.*)%s' % params['before']
|
||||
pattern = u'(?P<subsection>.*)%s' % params['before']
|
||||
|
||||
if pattern:
|
||||
section_re = re.compile(pattern, re.DOTALL)
|
||||
match = re.search(section_re, contents)
|
||||
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)
|
||||
result = re.subn(mre, params['replace'], section, 0)
|
||||
|
||||
if result[1] > 0 and section != result[0]:
|
||||
if pattern:
|
||||
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]
|
||||
changed = True
|
||||
if module._diff:
|
||||
|
|
Loading…
Reference in a new issue