LVPWB/lvpwb/prompts.py

54 lines
1.7 KiB
Python

from __future__ import annotations
import re
from typing import Any
import lvpwb as app
def ask(prompt: str, default: str | None = None) -> str:
suffix = f" [{default}]" if default is not None else ""
answer = input(f"{prompt}{suffix}: ").strip()
return answer if answer else (default or "")
def ask_yes_no(prompt: str, default: bool | None = None) -> bool:
suffix = " [Y/n]" if default is True else " [y/N]" if default is False else " [y/n]"
while True:
answer = input(f"{prompt}{suffix}: ").strip().casefold()
if not answer and default is not None:
return default
if answer in ("y", "yes"):
return True
if answer in ("n", "no"):
return False
print("Enter y/yes or n/no.")
def ask_choice(
prompt: str,
choices: list[Any],
default: int | None = None,
labels: list[str] | None = None,
) -> int:
labels = labels or [str(choice) for choice in choices]
if len(labels) != len(choices):
raise ValueError("Choice labels must match the number of choices.")
while True:
print(f"\n{prompt}:")
for number, label in enumerate(labels, 1):
print(f" {number}. {label}")
raw = app.ask("Selection", str(default) if default is not None else None)
try:
choice = int(raw)
if 1 <= choice <= len(choices):
return choice - 1
except ValueError:
pass
print(f"Enter a number from 1 to {len(choices)}.")
def slugify(value: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
return slug or "smackdown-show"
__all__ = ['ask', 'ask_choice', 'ask_yes_no', 'slugify']