| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
import re |
| 18 |
|
| 19 |
|
| 20 |
REC_CONDITIONALS = re.compile("([&|()])") |
| 21 |
|
| 22 |
|
| 23 |
def listify(message): |
| 24 |
"""Convert a string containing a logical expression to a list |
| 25 |
|
| 26 |
Examples: |
| 27 |
>>> listify('(foo)') |
| 28 |
['foo'] |
| 29 |
|
| 30 |
>>> listify('foo & (bar | baz)') |
| 31 |
['foo', '&', ['bar', '|', 'baz']] |
| 32 |
|
| 33 |
>>> listify('(a&b)|(c|d)&(e|f)') |
| 34 |
[['a', '&', 'b'], '|', ['c', '|', 'd'], '&', ['e', '|', 'f']] |
| 35 |
|
| 36 |
>>> listify('a & (b & c)') |
| 37 |
['a', '&', ['b', '&', 'c']] |
| 38 |
|
| 39 |
>>> listify('a & b') |
| 40 |
['a', '&', 'b'] |
| 41 |
|
| 42 |
>>> listify('a & (b)') |
| 43 |
['a', '&', 'b'] |
| 44 |
|
| 45 |
>>> listify('((foo)') |
| 46 |
Traceback (most recent call last): |
| 47 |
ValueError: ((foo) |
| 48 |
|
| 49 |
>>> listify('(foo))') |
| 50 |
Traceback (most recent call last): |
| 51 |
ValueError: (foo)) |
| 52 |
|
| 53 |
""" |
| 54 |
message = message.replace("'", "\"") |
| 55 |
|
| 56 |
ret_list = [] |
| 57 |
stack = [ret_list] |
| 58 |
for item in REC_CONDITIONALS.split(message): |
| 59 |
item = item.strip() |
| 60 |
if item and item not in ["(", ")"]: |
| 61 |
stack[-1].append(item) |
| 62 |
elif item == "(": |
| 63 |
stack[-1].append([]) |
| 64 |
stack.append(stack[-1][-1]) |
| 65 |
elif item == ")": |
| 66 |
stack.pop() |
| 67 |
if not stack: |
| 68 |
raise ValueError(message) |
| 69 |
if isinstance(stack[-1][-1], list) and len(stack[-1][-1]) == 1: |
| 70 |
stack[-1][-1] = stack[-1][-1][0] |
| 71 |
if len(stack) > 1: |
| 72 |
raise ValueError(message) |
| 73 |
return ret_list |