From e47e31565d2cc2033bc6ea60082e567700c62029 Mon Sep 17 00:00:00 2001 From: getzze Date: Wed, 4 Dec 2024 16:14:38 +0000 Subject: [PATCH] allow string input --- rexi/cli.py | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/rexi/cli.py b/rexi/cli.py index 35d60ae..ae8e98a 100644 --- a/rexi/cli.py +++ b/rexi/cli.py @@ -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[ @@ -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: @@ -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)