From f8593cc76b007872d5d590062e26a8c2d1a264c2 Mon Sep 17 00:00:00 2001 From: Jiri Tyr Date: Thu, 2 Jul 2015 14:37:51 +0100 Subject: [PATCH] Adding comment filter --- v1/ansible/runner/filter_plugins/core.py | 80 ++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/v1/ansible/runner/filter_plugins/core.py b/v1/ansible/runner/filter_plugins/core.py index bdf45509c3a..f81da6f8942 100644 --- a/v1/ansible/runner/filter_plugins/core.py +++ b/v1/ansible/runner/filter_plugins/core.py @@ -270,6 +270,83 @@ def get_encrypted_password(password, hashtype='sha512', salt=None): def to_uuid(string): return str(uuid.uuid5(UUID_NAMESPACE_ANSIBLE, str(string))) +def comment(text, style='plain', **kw): + # Predefined comment types + comment_styles = { + 'plain': { + 'decoration': '# ' + }, + 'erlang': { + 'decoration': '% ' + }, + 'c': { + 'decoration': '// ' + }, + 'cblock': { + 'beginning': '/*', + 'decoration': ' * ', + 'end': ' */' + }, + 'xml': { + 'beginning': '' + } + } + + # Pointer to the right comment type + style_params = comment_styles[style] + + if 'decoration' in kw: + prepostfix = kw['decoration'] + else: + prepostfix = style_params['decoration'] + + # Default params + p = { + 'newline': '\n', + 'beginning': '', + 'prefix': (prepostfix).rstrip(), + 'prefix_count': 1, + 'decoration': '', + 'postfix': (prepostfix).rstrip(), + 'postfix_count': 1, + 'end': '' + } + + # Update default params + p.update(style_params) + p.update(kw) + + # Compose substrings for the final string + str_beginning = '' + if p['beginning']: + str_beginning = "%s%s" % (p['beginning'], p['newline']) + str_prefix = str( + "%s%s" % (p['prefix'], p['newline'])) * int(p['prefix_count']) + str_text = ("%s%s" % ( + p['decoration'], + # Prepend each line of the text with the decorator + text.replace( + p['newline'], "%s%s" % (p['newline'], p['decoration'])))).replace( + # Remove trailing spaces when only decorator is on the line + "%s%s" % (p['decoration'], p['newline']), + "%s%s" % (p['decoration'].rstrip(), p['newline'])) + str_postfix = p['newline'].join( + [''] + [p['postfix'] for x in range(p['postfix_count'])]) + str_end = '' + if p['end']: + str_end = "%s%s" % (p['newline'], p['end']) + + # Return the final string + return "%s%s%s%s%s" % ( + str_beginning, + str_prefix, + str_text, + str_postfix, + str_end) + + class FilterModule(object): ''' Ansible core jinja2 filters ''' @@ -348,4 +425,7 @@ class FilterModule(object): # random stuff 'random': rand, 'shuffle': randomize_list, + + # comment-style decoration of string + 'comment': comment, }