Repository navigation
Expand file tree
/
Copy pathplugin.py
More file actions
360 lines (304 loc) · 13.5 KB
/
Copy pathplugin.py
File metadata and controls
360 lines (304 loc) · 13.5 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2022, Johannes Köster, Vanessa Sochat"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import field, fields, Field
from dataclasses import MISSING, dataclass
import os
from pathlib import Path
from typing import (
Any,
Dict,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
TYPE_CHECKING,
TypeVar,
Generic,
cast,
)
import typing
from snakemake_interface_common.exceptions import WorkflowError
from snakemake_interface_common.exceptions import InvalidPluginException
from snakemake_interface_common._common import (
dataclass_field_to_argument_args,
)
if TYPE_CHECKING:
from argparse import ArgumentParser
# Valid Argument types (to distinguish from empty dataclasses)
ArgTypes = (str, int, float, bool, list, Path)
@dataclass
class SettingsBase:
"""Base class for plugin settings."""
def get_items_by_category(self, category: str) -> typing.Iterator[Tuple[str, Any]]:
"""Yield all items (name, value) of the given group (as defined by the)
optional subgroup field in the metadata.
"""
for thefield in fields(self.__class__):
if thefield.metadata.get("subgroup") == category:
yield thefield.name, getattr(self, thefield.name)
@dataclass
class TaggedSettings:
_inner: Dict[Optional[str], SettingsBase] = field(default_factory=dict, init=False)
def register_settings(
self, settings: SettingsBase, tag: Optional[str] = None
) -> None:
self._inner[tag] = settings
def get_settings(self, tag: Optional[str] = None) -> Optional[SettingsBase]:
settings = self._inner.get(tag)
if tag is not None and settings is None:
# no settings specifically for this tag, just use untagged defaults
settings = self._inner.get(None)
return settings
def get_field_settings(self, field_name: str) -> Dict[Optional[str], Sequence[Any]]:
"""Return a dictionary of tag -> value for the given field name."""
return {
tag: getattr(settings, field_name) for tag, settings in self._inner.items()
}
def __iter__(self) -> typing.Iterator[SettingsBase]:
return iter(self._inner.values())
TSettingsBase = TypeVar("TSettingsBase", bound="SettingsBase")
class PluginBase(ABC, Generic[TSettingsBase]):
@property
@abstractmethod
def name(self) -> str: ...
@property
@abstractmethod
def cli_prefix(self) -> str: ...
@property
@abstractmethod
def settings_cls(self) -> Optional[Type[TSettingsBase]]: ...
@property
def support_tagged_values(self) -> bool:
return False
def has_settings_cls(self) -> bool:
"""Determine if a plugin defines custom settings"""
return self.settings_cls is not None
def get_settings_info(self) -> List[Dict[str, Any]]:
if self.settings_cls is None:
return []
else:
def fmt_default(thefield: Field) -> Any:
if thefield.default is not MISSING:
if callable(thefield.default):
return "<function>"
return thefield.default
else:
return None
return [
{
"name": thefield.name,
"cliarg": self.get_cli_arg(thefield.name),
"help": thefield.metadata["help"],
"required": thefield.metadata.get("required", False),
"default": fmt_default(thefield),
"type": thefield.metadata.get("type", None),
"choices": thefield.metadata.get("choices", None),
"nargs": thefield.metadata.get("nargs", None),
"env_var": self.get_envvar(thefield.name)
if thefield.metadata.get("env_var", None)
else None,
"metavar": thefield.metadata.get("metavar", None),
}
for thefield in fields(self.settings_cls)
]
def register_cli_args(self, argparser: "ArgumentParser", plugin_type: str) -> None:
"""Add arguments derived from self.executor_settings to given
argparser."""
# Cut out early if we don't have custom parameters to add
if self.settings_cls is None:
return
# Convenience handle
params = self.settings_cls
for thefield in fields(params):
if "help" not in thefield.metadata:
raise InvalidPluginException(
self.name, "Fields of ExecutorSettings must have a help string."
)
if thefield.default is MISSING and thefield.default_factory is MISSING:
raise InvalidPluginException(
self.name, "Fields of ExecutorSettings must have a default value."
)
settings = argparser.add_argument_group(
f"{self.name} {plugin_type} plugin settings"
)
for thefield in fields(params):
prefixed_name = self._get_prefixed_name(thefield.name).replace("-", "_")
args, kwargs = dataclass_field_to_argument_args(
thefield, name=prefixed_name
)
if thefield.metadata.get("env_var"):
kwargs["env_var"] = self.get_envvar(thefield.name)
if "metavar" not in kwargs:
kwargs["metavar"] = "VALUE"
if thefield.type == Path:
kwargs["help"] += (
" User dir (~) and environment variables are properly interpreted."
)
if thefield.type == bool:
# boolean args may not have a metavar
del kwargs["metavar"]
elif self.support_tagged_values:
if thefield.metadata.get("nargs", None) is not None:
raise ValueError(
f"Plugin {self.name} supports tagged values but specifies args "
"with multiple values in its settings class. This is not "
"supported and a bug in the plugin. Please file an issue in "
"the plugin repository."
)
kwargs["nargs"] = "+"
kwargs["type"] = str
kwargs["help"] += (
" Can be specified multiple times to set different "
"values for different tags."
)
kwargs["metavar"] = f"[TAG::]{kwargs['metavar']}"
if thefield.metadata.get("parse_func"):
kwargs["type"] = str
settings.add_argument(*args, **kwargs)
def validate_settings(self, settings: TSettingsBase) -> None:
def get_description(thefield: Field) -> str:
envvar = (
f" (or environment variable {self.get_envvar(thefield.name)})"
if thefield.metadata.get("env_var", None)
else ""
)
return f"{self.get_cli_arg(thefield.name)}{envvar}"
# rewrite for settings
missing = [
thefield
for thefield in fields(settings)
if thefield.metadata.get("required")
and getattr(settings, thefield.name) is None
]
if missing:
cli_args = [get_description(thefield) for thefield in missing]
raise WorkflowError(
f"The following required arguments are missing for "
f"plugin {self.name}: {', '.join(cli_args)}."
)
def get_settings(self, args: Any) -> Union[TSettingsBase, TaggedSettings]:
"""Return an instance of self.executor_settings with values from args.
This helper function will select executor plugin namespaces arguments
for a dataclass. It allows us to pass them from the custom executor ->
custom argument parser -> back into dataclass -> snakemake.
"""
dc = self.settings_cls
if dc is None:
if self.support_tagged_values:
return TaggedSettings()
else:
return cast(TSettingsBase, SettingsBase())
# We will parse the args from snakemake back into the dataclass
def get_name_and_value(field: Field) -> Tuple[str, Any]:
# This is the actual field name without the prefix
prefixed_name = self._get_prefixed_name(field.name).replace("-", "_")
value = getattr(args, prefixed_name)
return field.name, value
kwargs_tagged: Dict[Optional[str], Dict[str, Any]] = defaultdict(dict)
kwargs_all: Dict[str, Any] = dict()
required_args = set()
field_names = dict()
# These fields will have the executor prefix
for thefield in fields(dc):
name, value = get_name_and_value(thefield)
field_names[name] = thefield.name
if thefield.metadata.get("required"):
required_args.add(name)
if value is None:
continue
def extract_values(
value: Any, thefield: Field, name: str, tag: Optional[str] = None
) -> None:
# This will only add instantiated values, and
# skip over dataclasses._MISSING_TYPE and similar
if isinstance(value, ArgTypes):
# If a parsing function is defined, we pass the arg value to it
# in order to get the correct type back.
parse_func = thefield.metadata.get("parse_func")
if parse_func is not None:
if "unparse_func" not in thefield.metadata:
raise InvalidPluginException(
self.name,
f"Field {name} has a parse_func but no unparse_func.",
)
value = parse_func(value)
elif "type" in thefield.metadata:
value = self._parse_type(
thefield, value, thefield.metadata["type"]
)
elif thefield.type != str:
value = self._parse_type(thefield, value, thefield.type)
# expand variables and user dirs in paths
if isinstance(value, Path):
value = Path(os.path.expandvars(str(value.expanduser())))
if tag is None:
kwargs_all[name] = value
else:
kwargs_tagged[tag][name] = value
# for now, bool values cannot be tagged and thereby apply to all instances
if self.support_tagged_values and thefield.type != bool:
if value != MISSING:
for item in value:
splitted = item.split("::", 1)
if len(splitted) == 2: # is tagged
tag, item = splitted
elif len(splitted) == 1: # not tagged
tag = None
extract_values(item, thefield, name, tag=tag)
else:
extract_values(value, thefield, name)
for kwargs in kwargs_tagged.values():
for key, default_value in kwargs_all.items():
if key not in kwargs:
kwargs[key] = default_value
# convert into the dataclass
if self.support_tagged_values:
tagged_settings = TaggedSettings()
for tag, kwargs in kwargs_tagged.items():
settings = dc(**kwargs)
tagged_settings.register_settings(settings, tag=tag)
# untagged settings
settings = dc(**kwargs_all)
tagged_settings.register_settings(settings)
return tagged_settings
else:
settings = dc(**kwargs_all)
return settings
def get_envvar(self, field_name: str) -> str:
prefixed_name = self._get_prefixed_name(field_name).upper().replace("-", "_")
return f"SNAKEMAKE_{prefixed_name}"
def get_cli_arg(self, field_name: str) -> str:
return "--" + self._get_prefixed_name(field_name).replace("_", "-")
def _get_prefixed_name(self, field_name: str) -> str:
return f"{self.cli_prefix}_{field_name}"
def _parse_type(self, thefield: Field, value: Any, thetype: Any) -> Any:
def apply_type(value: Any, thetype: Any) -> Any:
try:
return thetype(value)
except Exception as e:
raise WorkflowError(
f"Failed to interpret value {value} for field {thefield.name} of "
f"plugin {self.name} as {thetype}. "
"Either there is a bug in the plugin settings "
"definition or an invalid value has been passed.",
e,
)
if typing.get_origin(thetype) == typing.Union:
args = typing.get_args(thetype)
if len(args) == 2 and args[1] == None.__class__: # noqa: E711
# Optional type
return apply_type(value, args[0])
else:
raise InvalidPluginException(
self.name,
"Plugin setting types may not use typing.Union. Only plain types "
"and typing.Optional are allowed.",
)
else:
return apply_type(value, thetype)