Skip to content

Commit

Permalink
allow string input
Browse files Browse the repository at this point in the history
  • Loading branch information
getzze committed Dec 4, 2024
1 parent f1dca8e commit e47e315
Showing 1 changed file with 34 additions and 7 deletions.
41 changes: 34 additions & 7 deletions rexi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,18 @@ def is_stdin_a_tty() -> bool:
# noinspection SpellCheckingInspection
@app.command("rexi")
def rexi_cli(
text: Annotated[
Optional[str],
typer.Argument(
help="String to pass to rexi; if not provided, stdin will be used.",
),
] = None,
input_file: Annotated[
Optional[typer.FileText],
typer.Option(
"--input",
"-i",
help="Input file to pass to rexi; if not provided, stdin will be used.",
help="Input file to pass to rexi; if used, TEXT should be empty.",
),
] = None,
initial_pattern: Annotated[
Expand All @@ -46,8 +52,23 @@ def rexi_cli(
),
] = None,
) -> None:
"""Try regex patterns on a string.
If `--input FILE` is used, read the file content.
"""
# Input file provided
if input_file:
# Incompatible with a string argument
if text:
msg = (
"TEXT argument should be empty if in input is provided with "
"the `-i` flag."
)
raise typer.BadParameter(msg)

input_text = input_file.read()

# Read stdin
elif not is_stdin_a_tty():
input_text = sys.stdin.read()
try:
Expand All @@ -56,14 +77,20 @@ def rexi_cli(
pass
# Windows uses "con:" for stdin device name
sys.stdin = open("con:" if os.name == "nt" else "/dev/tty", "rb") # type: ignore[assignment]

# Incompatible with a string argument
if text:
msg = "TEXT argument should be empty if text is piped through stdin."
raise typer.BadParameter(msg)

# Input string provided or fallback to empty string
else:
raise typer.BadParameter(
"stdin is empty, "
"please provide text thru the stdin "
"or use the `-i` flag"
)
input_text = text or ""

app: RexiApp[int] = RexiApp(
input_text, initial_mode=initial_mode, initial_pattern=initial_pattern
input_text,
initial_mode=initial_mode,
initial_pattern=initial_pattern,
)
app.run()
print(app.pattern)

0 comments on commit e47e315

Please sign in to comment.