Debian Codegraph @

lib/ansible/module_utils/splitter.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c), Michael DeHaan <[email protected]>, 2012-2013
8 # All rights reserved.
9 #
10 # Redistribution and use in source and binary forms, with or without modification,
11 # are permitted provided that the following conditions are met:
12 #
13 # * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # * Redistributions in binary form must reproduce the above copyright notice,
16 # this list of conditions and the following disclaimer in the documentation
17 # and/or other materials provided with the distribution.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 from __future__ import annotations
30
31
32 def _get_quote_state(token, quote_char):
33 """
34 the goal of this block is to determine if the quoted string
35 is unterminated in which case it needs to be put back together
36 """
37 # the char before the current one, used to see if
38 # the current character is escaped
39 prev_char = None
40 for idx, cur_char in enumerate(token):
41 if idx > 0:
42 prev_char = token[idx - 1]
43 if cur_char in '"\'' and prev_char != '\\':
44 if quote_char:
45 if cur_char == quote_char:
46 quote_char = None
47 else:
48 quote_char = cur_char
49 return quote_char
50
51
52 def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
53 """
54 this function counts the number of opening/closing blocks for a
55 given opening/closing type and adjusts the current depth for that
56 block based on the difference
57 """
58 num_open = token.count(open_token)
59 num_close = token.count(close_token)
60 if num_open != num_close:
61 cur_depth += (num_open - num_close)
62 if cur_depth < 0:
63 cur_depth = 0
64 return cur_depth
65
66
67 def split_args(args):
68 """
69 Splits args on whitespace, but intelligently reassembles
70 those that may have been split over a jinja2 block or quotes.
71
72 When used in a remote module, we won't ever have to be concerned about
73 jinja2 blocks, however this function is/will be used in the
74 core portions as well before the args are templated.
75
76 example input: a=b c="foo bar"
77 example output: ['a=b', 'c="foo bar"']
78
79 Basically this is a variation shlex that has some more intelligence for
80 how Ansible needs to use it.
81 """
82
83 # the list of params parsed out of the arg string
84 # this is going to be the result value when we are done
85 params = []
86
87 # here we encode the args, so we have a uniform charset to
88 # work with, and split on white space
89 args = args.strip()
90 try:
91 args = args.encode('utf-8')
92 do_decode = True
93 except UnicodeDecodeError:
94 do_decode = False
95 items = args.split('\n')
96
97 # iterate over the tokens, and reassemble any that may have been
98 # split on a space inside a jinja2 block.
99 # ex if tokens are "{{", "foo", "}}" these go together
100
101 # These variables are used
102 # to keep track of the state of the parsing, since blocks and quotes
103 # may be nested within each other.
104
105 quote_char = None
106 inside_quotes = False
107 print_depth = 0 # used to count nested jinja2 {{ }} blocks
108 block_depth = 0 # used to count nested jinja2 {% %} blocks
109 comment_depth = 0 # used to count nested jinja2 {# #} blocks
110
111 # now we loop over each split chunk, coalescing tokens if the white space
112 # split occurred within quotes or a jinja2 block of some kind
113 for itemidx, item in enumerate(items):
114
115 # we split on spaces and newlines separately, so that we
116 # can tell which character we split on for reassembly
117 # inside quotation characters
118 tokens = item.strip().split(' ')
119
120 line_continuation = False
121 for idx, token in enumerate(tokens):
122
123 # if we hit a line continuation character, but
124 # we're not inside quotes, ignore it and continue
125 # on to the next token while setting a flag
126 if token == '\\' and not inside_quotes:
127 line_continuation = True
128 continue
129
130 # store the previous quoting state for checking later
131 was_inside_quotes = inside_quotes
132 quote_char = _get_quote_state(token, quote_char)
133 inside_quotes = quote_char is not None
134
135 # multiple conditions may append a token to the list of params,
136 # so we keep track with this flag to make sure it only happens once
137 # append means add to the end of the list, don't append means concatenate
138 # it to the end of the last token
139 appended = False
140
141 # if we're inside quotes now, but weren't before, append the token
142 # to the end of the list, since we'll tack on more to it later
143 # otherwise, if we're inside any jinja2 block, inside quotes, or we were
144 # inside quotes (but aren't now) concat this token to the last param
145 if inside_quotes and not was_inside_quotes:
146 params.append(token)
147 appended = True
148 elif print_depth or block_depth or comment_depth or inside_quotes or was_inside_quotes:
149 if idx == 0 and not inside_quotes and was_inside_quotes:
150 params[-1] = "%s%s" % (params[-1], token)
151 elif len(tokens) > 1:
152 spacer = ''
153 if idx > 0:
154 spacer = ' '
155 params[-1] = "%s%s%s" % (params[-1], spacer, token)
156 else:
157 spacer = ''
158 if not params[-1].endswith('\n') and idx == 0:
159 spacer = '\n'
160 params[-1] = "%s%s%s" % (params[-1], spacer, token)
161 appended = True
162
163 # if the number of paired block tags is not the same, the depth has changed, so we calculate that here
164 # and may append the current token to the params (if we haven't previously done so)
165 prev_print_depth = print_depth
166 print_depth = _count_jinja2_blocks(token, print_depth, "{{", "}}")
167 if print_depth != prev_print_depth and not appended:
168 params.append(token)
169 appended = True
170
171 prev_block_depth = block_depth
172 block_depth = _count_jinja2_blocks(token, block_depth, "{%", "%}")
173 if block_depth != prev_block_depth and not appended:
174 params.append(token)
175 appended = True
176
177 prev_comment_depth = comment_depth
178 comment_depth = _count_jinja2_blocks(token, comment_depth, "{#", "#}")
179 if comment_depth != prev_comment_depth and not appended:
180 params.append(token)
181 appended = True
182
183 # finally, if we're at zero depth for all blocks and not inside quotes, and have not
184 # yet appended anything to the list of params, we do so now
185 if not (print_depth or block_depth or comment_depth) and not inside_quotes and not appended and token != '':
186 params.append(token)
187
188 # if this was the last token in the list, and we have more than
189 # one item (meaning we split on newlines), add a newline back here
190 # to preserve the original structure
191 if len(items) > 1 and itemidx != len(items) - 1 and not line_continuation:
192 if not params[-1].endswith('\n') or item == '':
193 params[-1] += '\n'
194
195 # always clear the line continuation flag
196 line_continuation = False
197
198 # If we're done and things are not at zero depth or we're still inside quotes,
199 # raise an error to indicate that the args were unbalanced
200 if print_depth or block_depth or comment_depth or inside_quotes:
201 raise Exception("error while splitting arguments, either an unbalanced jinja2 block or quotes")
202
203 # finally, we decode each param back to the unicode it was in the arg string
204 if do_decode:
205 params = [x.decode('utf-8') for x in params]
206
207 return params
208
209
210 def is_quoted(data):
211 return len(data) > 0 and (data[0] == '"' and data[-1] == '"' or data[0] == "'" and data[-1] == "'")
212
213
214 def unquote(data):
215 """ removes first and last quotes from a string, if the string starts and ends with the same quotes """
216 if is_quoted(data):
217 return data[1:-1]
218 return data