Last active
September 26, 2024 21:11
-
-
Save jnhmcknight/9ad6f884bae8599e77e69138272fdeec to your computer and use it in GitHub Desktop.
Regex Parameter handler for Click
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import sys | |
import typing as t | |
import click | |
from click._compat import _get_argv_encoding | |
class RegexOption(click.ParamType): | |
"""A type handler for click command parameters for Regex""" | |
name: str = 'regular-expression' | |
regex_flags: re.RegexFlag = 0 | |
def __init__(self, regex_flags: re.RegexFlag = 0): | |
self.regex_flags = regex_flags | |
def convert( | |
self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None | |
) -> re.Pattern: | |
if isinstance(value, bytes): | |
enc = _get_argv_encoding() | |
try: | |
value = value.decode(enc) | |
except UnicodeError: | |
fs_enc = sys.getfilesystemencoding() | |
if fs_enc != enc: | |
try: | |
value = value.decode(fs_enc) | |
except UnicodeError: | |
value = value.decode("utf-8", "replace") | |
else: | |
value = value.decode("utf-8", "replace") | |
return re.compile(value, self.regex_flags) | |
def __repr__(self) -> str: | |
return "REGEX" | |
@click.command() | |
@click.option( | |
'-p', '--pattern', | |
type=RegexOption(), # Init with any desired flags (ie: re.IGNORECASE) | |
prompt=True, | |
help='The regex to compile', | |
) | |
def example(pattern): | |
"""Receives a compiled regex""" | |
if not pattern.match('It Worked!'): | |
click.echo('Pattern was not matched!') | |
raise click.Abort() | |
click.echo('The pattern was matched!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment