imp/sandbox/cli/prompt.py
2025-06-24 16:42:17 +10:00

66 lines
1.7 KiB
Python

'''
===== Prompt Handling =====
This file implements the Prompt class, allowing for
inheritance and instantiation of Prompt objects.
The CLI class uses these instead of containing the
logic immediately within itself.
'''
from typing import Any
from noether.cli.style import *
from noether.lib.structs import Result
class Prompt:
DEFAULT_PROMPT = 'DEF> '
def __init__(self) -> None:
self._prompt = self.DEFAULT_PROMPT
'''
Prompt and await command via stdin.
'''
def prompt(self):
command = self.__request()
result = self._parse(command)
if result.success:
self._exec(result.value)
else:
self.__parse_error(result)
'''
!! OVERRIDE ON INHERITANCE !!
Handles the parsing of a given command.
'''
def _parse(self, command: str) -> Result:
return Result.succeed(command)
def __parse_error(self, error: Result) -> None:
err = f'{style(error.reason, Effect.ITALICS)}'
print(style(err, Effect.DIM))
'''
!! OVERRIDE ON INHERITANCE !!
Handles the execution of a command that
was successfully parsed by a Prompt inheritor.
'''
def _exec(self, command: Any) -> None:
pass
'''
Internal use only. Handles a raw request with no validation.
'''
def __request(self) -> None:
print(self.__get_prompt(), end='', flush=True)
return input()
'''
!! OVERRIDE ON INHERITANCE !!
'''
def _style_prompt(self, prompt: str) -> str:
return prompt
def __get_prompt(self) -> str:
return self._style_prompt(self._prompt)
def set_prompt(self, prompt: str) -> None:
self._prompt = prompt