1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2025-2026 Benjamin Abendroth <braph93@gmx.de>
'''Functions for parsing the `when` attribute.'''
from . import shell_parser
from .errors import CrazyError
# pylint: disable=too-few-public-methods
class OptionIs:
'''Class for holding `option_is`.'''
def __init__(self, args):
self.options = []
self.values = []
has_end_of_options = False
for arg in args:
if arg == '--':
has_end_of_options = True
elif not has_end_of_options:
self.options.append(arg)
elif has_end_of_options:
self.values.append(arg)
if not self.options:
raise CrazyError('OptionIs: Empty options')
if not self.values:
raise CrazyError('OptionIs: Empty values')
class HasOption:
'''Class for holding `has_option`.'''
def __init__(self, args):
self.options = args
if not self.options:
raise CrazyError('HasOption: Empty options')
def replace_commands(tokens):
'''Replaced `shell_parser.Command` objects by condition objects.'''
r = []
for token in tokens:
if isinstance(token, shell_parser.Command):
cmd, *args = token.args
if cmd == 'option_is':
r.append(OptionIs(args))
elif cmd == 'has_option':
r.append(HasOption(args))
else:
raise CrazyError(f"Invalid command: {cmd!r}")
else:
r.append(token)
return r
def needs_braces(tokens):
'''Check if we need braces around our tokens.
We don't need braces if:
- We only have one token (single command)
- We only have two tokens (negated single command)
- We don't have an OR inside the tokens
'''
return len(tokens) > 2 and '||' in tokens
def parse_when(s):
'''Parse `when` string and return an object.'''
tokens = shell_parser.parse(s)
return replace_commands(tokens)
|