Last active
December 18, 2024 21:40
-
-
Save Apocryphon-X/1ab72990362bb91c237e2eb09a0000e0 to your computer and use it in GitHub Desktop.
`parse_argument_list` accepts a flags "register" as second argument to handle things like -h / --help or things like --debug flags!
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
""" | |
The MIT License (MIT) | |
Copyright (c) 2024 - Present, @Apocryphon-X (Dante Mendoza Leyva) | |
Permission is hereby granted, free of charge, to any person obtaining a | |
copy of this software and associated documentation files (the "Software"), | |
to deal in the Software without restriction, including without limitation | |
the rights to use, copy, modify, merge, publish, distribute, sublicense, | |
and/or sell copies of the Software, and to permit persons to whom the | |
Software is furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | |
DEALINGS IN THE SOFTWARE. | |
""" | |
from sys import argv | |
from dataclasses import dataclass | |
from typing import Optional, Tuple, List, Set | |
try: | |
from rich import print | |
except ModuleNotFoundError: | |
pass | |
@dataclass | |
class Option: | |
name: str | |
value: Optional[str] | |
def get_prefix(raw_argument: str) -> Optional[str]: | |
# Order matters! | |
for prefix in ["--", "-"]: | |
if raw_argument.startswith(prefix): | |
return prefix | |
return None | |
# raw_option_str refers to the option string | |
# with prefix included (i.e: "--hello", "-s") | |
def as_option(prefix: str, raw_option_str: str) -> Option: | |
value = None | |
no_prefix_str = raw_option_str[len(prefix) :] | |
if prefix == "-": | |
if len(no_prefix_str) > 1: | |
value = no_prefix_str[1:] | |
return Option(no_prefix_str[0], value) | |
# Check for '=' in long option | |
equals_idx = no_prefix_str.find("=") | |
option_name = "" | |
if equals_idx != -1: | |
option_name = no_prefix_str[:equals_idx] | |
value = no_prefix_str[equals_idx + 1 :] | |
else: | |
option_name = no_prefix_str | |
return Option(option_name, value) | |
# Returns a 2-tuple of parsed options and arguments | |
def parse_argument_list( | |
arg_list: List[str], flag_set: Optional[Set[str]] = set() | |
) -> Tuple[List[Option], List[str]]: | |
options_list = [] | |
arguments_list = [] | |
expecting_option_value = False | |
parsed_option = Option("", None) | |
for argument in argv[1:]: | |
if expecting_option_value: | |
expecting_option_value = False | |
parsed_option.value = argument | |
options_list.append(parsed_option) | |
continue | |
option_prefix = get_prefix(argument) | |
# Check for raw arguments | |
if option_prefix is None: | |
expecting_option_value = False | |
arguments_list.append(argument) | |
continue | |
parsed_option = as_option(option_prefix, argument) | |
# Check for flags | |
if parsed_option.name in flag_set: | |
if parsed_option.value is None: | |
expecting_option_value = False | |
options_list.append(parsed_option) | |
continue | |
# Flags should not receive any values | |
option_repr = f"{option_prefix}{parsed_option.name}" | |
raise ValueError(f"{option_repr} does not receive any values.") | |
# Check for partial options - If no value is received | |
# then we expect to capture it in the next iteration | |
if parsed_option.value is None: | |
expecting_option_value = True | |
continue | |
options_list.append(parsed_option) | |
# Check if the last option is incomplete | |
if expecting_option_value: | |
option_repr = f"{option_prefix}{parsed_option.name}" | |
raise ValueError(f"{option_repr} expects a value.") | |
return (options_list, arguments_list) | |
if __name__ == "__main__": | |
opt_list, arg_list = parse_argument_list(argv[1:]) | |
print(f"{opt_list = }") | |
print(f"{arg_list = }") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: Handle cases like
-
or--