Untitled

mail@pastecode.io avatar
unknown
python
a year ago
2.9 kB
2
Indexable
Never
class State:
    def parse(self, context, input_string):
        pass

class CommandState(State):
    def parse(self, context, input_string):
        parts = input_string.split(' ', 1)
        command = parts[0]
        context.set_command(command)

        if len(parts) > 1:
            context.set_next_state(ParameterState())

class ParameterState(State):
    def parse(self, context, input_string):
        if input_string.startswith('"'):
            end_quote_index = input_string[1:].index('"') + 1
            parameter = input_string[1:end_quote_index + 1].replace('_', ' ')
            remaining_string = input_string[end_quote_index + 3:]
        else:
            parts = input_string.split(' ', 1)
            parameter = parts[0]
            remaining_string = parts[1] if len(parts) > 1 else ''

        context.add_parameter(parameter.strip())

        if remaining_string:
            if remaining_string.startswith('-'):
                context.set_next_state(KeyState())
            else:
                context.set_next_state(ParameterState())

            context.parse(remaining_string)

class QuoteState(State):
    def parse(self, context, input_string):
        end_quote_index = input_string.index('"')
        parameter = input_string[:end_quote_index].replace('_', ' ')
        remaining_string = input_string[end_quote_index + 2:]

        context.add_parameter(parameter)

        if remaining_string:
            if remaining_string.startswith('-'):
                context.set_next_state(KeyState())
            else:
                context.set_next_state(ParameterState())

            context.parse(remaining_string)

class KeyState(State):
    def parse(self, context, input_string):
        parts = input_string.split(' ', 1)
        key = parts[0]
        context.add_key(key)

        if len(parts) > 1:
            remaining_string = parts[1]
            if remaining_string.startswith('"'):
                context.set_next_state(QuoteState())
            else:
                context.set_next_state(ParameterState())

            context.parse(remaining_string)

class StateContext:
    def __init__(self):
        self.command = ''
        self.parameters = []
        self.keys = []
        self.current_state = CommandState()

    def set_command(self, command):
        self.command = command

    def add_parameter(self, parameter):
        self.parameters.append(parameter)

    def add_key(self, key):
        self.keys.append(key)

    def set_next_state(self, state):
        self.current_state = state

    def parse(self, input_string):
        self.current_state.parse(self, input_string)

    def print_result(self):
        print("Command:", self.command)
        print("Parameters:", self.parameters)
        print("Keys:", self.keys)

input_string = input("Enter a command: ")
context = StateContext()
context.parse(input_string)
context.print_result()