|
21 | 21 | import functools |
22 | 22 | import re |
23 | 23 | import sys |
24 | | -from typing import Any, Callable, Dict, Optional, Tuple, Union |
| 24 | +from typing import Callable, Dict, Optional, Tuple, Type, Union |
25 | 25 |
|
| 26 | +from requests.structures import CaseInsensitiveDict |
| 27 | + |
| 28 | +from gitlab.base import RESTObject |
26 | 29 | import gitlab.config |
27 | 30 |
|
28 | | -camel_re = re.compile("(.)([A-Z])") |
| 31 | +# Full credit for this regex goes to: |
| 32 | +# https://github.com/jpvanhal/inflection/blob/master/inflection/__init__.py |
| 33 | +camel_upperlower_regex = re.compile(r"([A-Z]+)([A-Z][a-z])") |
| 34 | +camel_lowerupper_regex = re.compile(r"([a-z\d])([A-Z])") |
29 | 35 |
|
30 | 36 | # custom_actions = { |
31 | 37 | # cls: { |
@@ -75,12 +81,20 @@ def die(msg: str, e: Optional[Exception] = None) -> None: |
75 | 81 | sys.exit(1) |
76 | 82 |
|
77 | 83 |
|
78 | | -def what_to_cls(what: str) -> str: |
79 | | - return "".join([s.capitalize() for s in what.split("-")]) |
| 84 | +def what_to_cls(what: str, namespace: Type) -> RESTObject: |
| 85 | + """Given a kebab-case string from a CLI argument, return a corresponding |
| 86 | + (CamelCase) class in a given namespace with a case-insensitive lookup.""" |
| 87 | + classes = CaseInsensitiveDict(namespace.__dict__) |
| 88 | + lowercase_class = what.replace("-", "") |
| 89 | + |
| 90 | + return classes[lowercase_class] |
80 | 91 |
|
81 | 92 |
|
82 | | -def cls_to_what(cls: Any) -> str: |
83 | | - return camel_re.sub(r"\1-\2", cls.__name__).lower() |
| 93 | +def cls_to_what(cls: RESTObject) -> str: |
| 94 | + """Convert CamelCase class names to kebab-case in two steps, to ensure names |
| 95 | + with whole upper-case words are correctly dash-separated as well.""" |
| 96 | + dash_upper = camel_upperlower_regex.sub(r"\1-\2", cls.__name__) |
| 97 | + return camel_lowerupper_regex.sub(r"\1-\2", dash_upper).lower() |
84 | 98 |
|
85 | 99 |
|
86 | 100 | def _get_base_parser(add_help: bool = True) -> argparse.ArgumentParser: |
|
0 commit comments