-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathparser.py
More file actions
279 lines (230 loc) · 8.11 KB
/
parser.py
File metadata and controls
279 lines (230 loc) · 8.11 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
from dataclasses import fields, is_dataclass
from pathlib import Path
from typing import Dict, List, Tuple, Type, TypeVar, get_args, get_origin
import click
import yaml
from typing_extensions import Annotated
from latch.types.directory import LatchDir
from latch.types.file import LatchFile
from latch_cli.snakemake.utils import reindent
from latch_cli.utils import best_effort_display_name, identifier_from_str
from .utils import (
JSONValue,
get_preamble,
is_list_type,
is_primitive_type,
parse_type,
parse_value,
type_repr,
)
T = TypeVar("T")
def parse_config(
config_path: Path,
*,
infer_files: bool = False,
) -> Dict[str, Tuple[Type[T], T]]:
if not config_path.exists():
click.secho(
f"No config file found at {config_path}.",
fg="red",
)
raise click.exceptions.Exit(1)
if config_path.is_dir():
click.secho(
f"Path {config_path} points to a directory.",
fg="red",
)
raise click.exceptions.Exit(1)
try:
res: JSONValue = yaml.safe_load(config_path.read_text())
except yaml.YAMLError as e:
click.secho(
reindent(
f"""
Error loading config from {config_path}:
{e}
""",
0,
),
fg="red",
)
raise click.exceptions.Exit(1) from e
if not isinstance(res, dict):
# ayush: this case doesn't matter bc a non-dict .yaml file isn't valid snakemake
return {"snakemake_parameter": (parse_type(res, infer_files=infer_files), res)}
parsed: Dict[str, Type] = {}
for k, v in res.items():
try:
typ = parse_type(v, k, infer_files=infer_files)
except ValueError as e:
click.secho(
f"WARNING: Skipping parameter {k}. Failed to parse type: {e}.",
fg="yellow",
)
continue
val, default = parse_value(typ, v)
parsed[k] = (typ, (val, default))
return parsed
def file_metadata_str(typ: Type, value: JSONValue, level: int = 0) -> str:
if get_origin(typ) is Annotated:
args = get_args(typ)
assert len(args) > 0
return file_metadata_str(args[0], value, level)
if is_primitive_type(typ):
return ""
if typ in {LatchFile, LatchDir}:
return reindent(
f"""\
SnakemakeFileMetadata(
path={repr(value)},
config=True,
),\n""",
level,
)
metadata: List[str] = []
if is_list_type(typ):
template = """
[
__metadata__],\n"""
args = get_args(typ)
assert len(args) > 0
for val in value:
metadata_str = file_metadata_str(get_args(typ)[0], val, level + 1)
if metadata_str == "":
continue
metadata.append(metadata_str)
else:
template = """
{
__metadata__},\n"""
assert is_dataclass(typ)
for field in fields(typ):
metadata_str = file_metadata_str(
field.type, getattr(value, field.name), level
)
if metadata_str == "":
continue
metadata_str = f"{repr(identifier_from_str(field.name))}: {metadata_str}"
metadata.append(reindent(metadata_str, level + 1))
if len(metadata) == 0:
return ""
return reindent(
template,
level,
).replace("__metadata__", "".join(metadata), level + 1)
# todo(ayush): print informative stuff here ala register
def generate_metadata(
config_path: Path,
metadata_root: Path,
*,
skip_confirmation: bool = False,
generate_defaults: bool = False,
infer_files: bool = False,
):
parsed = parse_config(config_path, infer_files=infer_files)
preambles: List[str] = []
params: List[str] = []
file_metadata: List[str] = []
for k, (typ, (val, default)) in parsed.items():
preambles.append(get_preamble(typ))
param_str = reindent(
f"""\
{repr(identifier_from_str(k))}: SnakemakeParameter(
display_name={repr(best_effort_display_name(k))},
type={type_repr(typ)},
__default__),""",
0,
)
default_str = ""
if generate_defaults and default is not None:
default_str = f" default={repr(default)},\n"
param_str = param_str.replace("__default__", default_str)
param_str = reindent(param_str, 1)
params.append(param_str)
metadata_str = file_metadata_str(typ, val)
if metadata_str == "":
continue
metadata_str = f"{repr(identifier_from_str(k))}: {metadata_str}"
file_metadata.append(reindent(metadata_str, 1))
if metadata_root.is_file():
if not click.confirm(f"A file exists at `{metadata_root}`. Delete it?"):
raise click.exceptions.Exit(0)
metadata_root.unlink()
metadata_root.mkdir(exist_ok=True)
metadata_path = metadata_root / Path("__init__.py")
old_metadata_path = Path("latch_metadata.py")
if old_metadata_path.exists() and not metadata_path.exists():
if click.confirm(
"Found legacy `latch_metadata.py` file in current directory. This is"
" deprecated and will be ignored in future releases. Move to"
f" `{metadata_path}`? (This will not change file contents)"
):
old_metadata_path.rename(metadata_path)
elif old_metadata_path.exists() and metadata_path.exists():
click.secho(
"Warning: Found both `latch_metadata.py` and"
f" `{metadata_path}` in current directory."
" `latch_metadata.py` will be ignored.",
fg="yellow",
)
if not metadata_path.exists():
metadata_path.write_text(
reindent(
r"""
from latch.types.metadata import SnakemakeMetadata, LatchAuthor, EnvironmentConfig
from latch.types.directory import LatchDir
from .parameters import generated_parameters, file_metadata
SnakemakeMetadata(
output_dir=LatchDir("latch:///your_output_directory"),
display_name="Your Workflow Name",
author=LatchAuthor(
name="Your Name",
),
env_config=EnvironmentConfig(
use_conda=False,
use_container=False,
),
cores=4,
# Add more parameters
parameters=generated_parameters,
file_metadata=file_metadata,
)
""",
0,
)
)
click.secho(f"Generated `{metadata_path}`.", fg="green")
params_path = metadata_root / Path("parameters.py")
if (
params_path.exists()
and not skip_confirmation
and not click.confirm(f"File `{params_path}` already exists. Overwrite?")
):
raise click.exceptions.Exit(0)
params_path.write_text(
reindent(
r"""
from dataclasses import dataclass
import typing
import typing_extensions
from flytekit.core.annotation import FlyteAnnotation
from latch.types.metadata import SnakemakeParameter, SnakemakeFileParameter, SnakemakeFileMetadata
from latch.types.file import LatchFile
from latch.types.directory import LatchDir
__preambles__
# Import these into your `__init__.py` file:
#
# from .parameters import generated_parameters, file_metadata
generated_parameters = {
__params__
}
file_metadata = {
__file_metadata__}
""",
0,
)
.replace("__preambles__", "".join(preambles))
.replace("__params__", "\n".join(params))
.replace("__file_metadata__", "".join(file_metadata))
)
click.secho(f"Generated `{params_path}`.", fg="green")