-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path__init__.py
166 lines (135 loc) · 4.95 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""General command-line utilities."""
import argparse
from typing import Optional, Sequence
from datajoint_utilities.version import __version__
class HelpFmtDefaultsDocstring(
argparse.RawDescriptionHelpFormatter,
argparse.ArgumentDefaultsHelpFormatter,
):
"""Combination of different argparse help formatters.
- Use top-level docstring from module in help
- Show default values in help
"""
pass
class HelpFmtDefaultsDocstringMeta(
argparse.RawDescriptionHelpFormatter,
argparse.ArgumentDefaultsHelpFormatter,
argparse.MetavarTypeHelpFormatter,
):
"""Combination of different argparse help formatters.
- Use top-level docstring from module in help
- Show default values in help
- Show types as MetaVar values in help
"""
pass
class MultiplyArg(argparse.Action):
"""Custom action to multiply positive values of a user defined option."""
def __init__(self, option_strings, dest, multiplier=1, nargs=None, *args, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super().__init__(option_strings, dest, *args, **kwargs)
self.multiplier = multiplier
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str,
option_string: str = "",
):
num = float(values)
setattr(namespace, self.dest, self.multiplier * num if num > 0.0 else values)
class CommaSepArgs(argparse.Action):
"""Split comma-separated input arguments."""
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super().__init__(option_strings, dest, nargs="*", **kwargs)
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: list[str],
option_string: str = "",
):
if not option_string:
return
comma_splits = []
[comma_splits.extend(string.split(",")) for string in values]
whitespace_stripped = [string.strip() for string in comma_splits]
keywords = getattr(namespace, self.dest) or []
[keywords.extend(string.split()) for string in whitespace_stripped]
setattr(namespace, self.dest, list(filter(None, set(keywords))))
class EnvVarArgs(argparse.Action):
"""Split KEY=VALUE input arguments."""
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super().__init__(option_strings, dest, **kwargs)
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str,
option_string: str = "",
):
if not option_string:
return
keyval = values.split("=", 1)
key = keyval.pop(0)
if not key:
return
val = keyval.pop() if keyval else ""
kwargs = getattr(namespace, self.dest)
kwargs = {} if kwargs is None else kwargs
kwargs |= {key: val}
setattr(namespace, self.dest, kwargs)
class ArgparseBase:
def __init__(
self,
sysargv: Sequence[str],
name: str,
version: Optional[str] = None,
description: Optional[str] = None,
formatter: Optional[argparse.HelpFormatter] = None,
) -> None:
"""Parse sys argument list using `parse_args` method.
Args:
sysargv (Sequence[str]): List of arguments to be passed in.
formatter (Optional[cmd.T_ArgFmts], optional): A class passed to the
`formatter_class=` argument in `argparse.ArgumentParser()`.
Defaults to `argparse.RawDescriptionHelpFormatter`.
"""
cli_version = version if version is not None else __version__
help_description = (
description if description is not None else "DataJoint command-line utility"
)
help_formatter = formatter if formatter is not None else argparse.HelpFormatter
self.sys_args: Sequence[str] = sysargv
self.parser = argparse.ArgumentParser(
prog=name,
description=str(help_description),
formatter_class=help_formatter,
allow_abbrev=False,
)
self.parser.add_argument(
"-V",
"--version",
action="version",
version=f"%(prog)s {cli_version}",
)
self.parser.add_argument(
"-v",
"--verbose",
action="count",
default=0,
help="increase logging verbosity by specifying multiple",
)
self.make()
self.namespace = self.parser.parse_args(self.sys_args or ["-h"])
self._vars = vars(self.namespace)
def make(self):
"""Add components to the argument parser `self.parser`."""
pass
@property
def args(self):
return self._vars