-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathconfig.py
More file actions
617 lines (572 loc) · 21.1 KB
/
config.py
File metadata and controls
617 lines (572 loc) · 21.1 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
"""Configuration for myst-nb."""
import dataclasses as dc
from enum import Enum
from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple
from myst_parser.config.dc_validators import (
ValidatorType,
deep_iterable,
deep_mapping,
in_,
instance_of,
optional,
validate_fields,
)
from typing_extensions import Literal
def custom_formats_converter(value: dict) -> Dict[str, Tuple[str, dict, bool]]:
"""Convert the custom format dict."""
if not isinstance(value, dict):
raise TypeError(f"`nb_custom_formats` must be a dict: {value}")
output: Dict[str, Tuple[str, dict, bool]] = {}
for suffix, reader in value.items():
if not isinstance(suffix, str):
raise TypeError(f"`nb_custom_formats` keys must be a string: {suffix}")
if isinstance(reader, str):
output[suffix] = (reader, {}, False)
elif not isinstance(reader, Sequence):
raise TypeError(
f"`nb_custom_formats` values must be a string or sequence: {reader}"
)
elif len(reader) == 2:
output[suffix] = (reader[0], reader[1], False)
elif len(reader) == 3:
output[suffix] = (reader[0], reader[1], reader[2])
else:
raise TypeError(
f"`nb_custom_formats` values must be a string, of sequence of length "
f"2 or 3: {reader}"
)
if not isinstance(output[suffix][0], str):
raise TypeError(
f"`nb_custom_formats` values[0] must be a string: {output[suffix][0]}"
)
# TODO check can be loaded as a python object?
if not isinstance(output[suffix][1], dict):
raise TypeError(
f"`nb_custom_formats` values[1] must be a dict: {output[suffix][1]}"
)
if not isinstance(output[suffix][2], bool):
raise TypeError(
f"`nb_custom_formats` values[2] must be a bool: {output[suffix][2]}"
)
return output
def ipywidgets_js_factory() -> Dict[str, Dict[str, str]]:
"""Create a default ipywidgets js dict."""
# see: https://ipywidgets.readthedocs.io/en/7.6.5/embedding.html
return {
# Load RequireJS, used by the IPywidgets for dependency management
"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js": {
"integrity": "sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=",
"crossorigin": "anonymous",
},
# Load IPywidgets bundle for embedding.
"https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@1.0.6/dist/embed-amd.js": {
"data-jupyter-widgets-cdn": "https://cdn.jsdelivr.net/npm/",
"crossorigin": "anonymous",
},
}
def has_items(*validators) -> ValidatorType:
"""
A validator that performs validation per item of a sequence.
:param validators: Validator to apply per item
"""
def _validator(inst, field: dc.Field, value, suffix=""):
if not isinstance(value, Sequence):
raise TypeError(f"{suffix}{field.name} must be a sequence: {value}")
if len(value) != len(validators):
raise TypeError(
f"{suffix}{field.name!r} must be a sequence of length "
f"{len(validators)}: {value}"
)
for idx, (validator, member) in enumerate(zip(validators, value)):
validator(inst, field, member, suffix=f"{suffix}[{idx}]")
return _validator
class Section(Enum):
"""Config section tags."""
global_lvl = "global"
"""Global level configuration."""
file_lvl = "notebook"
"""File level configuration."""
cell_lvl = "cell"
"""Cell level configuration."""
config = "config"
"""Meta configuration."""
read = "read"
"""Configuration for reading files."""
execute = "execute"
"""Configuration for executing notebooks."""
render = "render"
"""Configuration for rendering notebook elements."""
@dc.dataclass()
class NbParserConfig:
"""Global configuration options for the MyST-NB parser.
Note: in the docutils/sphinx configuration,
these option names are prepended with ``nb_``
"""
def __post_init__(self):
self.custom_formats = custom_formats_converter(self.custom_formats)
validate_fields(self)
# file read options
custom_formats: Dict[str, Tuple[str, dict, bool]] = dc.field(
default_factory=dict,
metadata={
"help": "Custom formats for reading notebook; suffix -> reader",
"docutils_exclude": True,
"sections": (Section.global_lvl, Section.read),
},
)
# docutils does not support the custom formats mechanism
read_as_md: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Read as the MyST Markdown format",
"sphinx_exclude": True,
},
repr=False,
)
# configuration override keys (applied after file read)
# TODO previously we had `nb_render_key` (default: "render"),
# for cell.metadata.render.image and cell.metadata.render.figure`,
# and also `timeout`/`allow_errors` in notebook.metadata.execution
# do we still support these or deprecate?
# (plus also cell.metadata.tags:
# nbclient: `skip-execution` and `raises-exception`,
# myst_nb: `remove_cell`, `remove-cell`, `remove_input`, `remove-input`,
# `remove_output`, `remove-output`, `remove-stderr`
# )
# see also:
# https://nbformat.readthedocs.io/en/latest/format_description.html#cell-metadata
metadata_key: str = dc.field(
default="mystnb",
metadata={
"validator": instance_of(str),
"help": "Notebook level metadata key for config overrides",
"sections": (Section.global_lvl, Section.config),
},
)
cell_metadata_key: str = dc.field(
default="mystnb",
metadata={
"validator": instance_of(str),
"help": "Cell level metadata key for config overrides",
"legacy_name": "nb_render_key",
"sections": (Section.global_lvl, Section.file_lvl, Section.config),
},
)
# notebook execution options
kernel_rgx_aliases: Dict[str, str] = dc.field(
default_factory=dict,
metadata={
"validator": deep_mapping(instance_of(str), instance_of(str)),
"help": "Mapping of kernel name regex to replacement kernel name"
"(applied before execution)",
"docutils_exclude": True,
"sections": (Section.global_lvl, Section.execute),
},
)
execution_mode: Literal["off", "force", "auto", "cache", "inline"] = dc.field(
default="auto",
metadata={
"validator": in_(
[
"off",
"auto",
"force",
"cache",
"inline",
]
),
"help": "Execution mode for notebooks",
"legacy_name": "jupyter_execute_notebooks",
"sections": (Section.global_lvl, Section.file_lvl, Section.execute),
},
)
execution_cache_path: str = dc.field(
default="", # No default, so that sphinx can set it inside outdir, if empty
metadata={
"validator": instance_of(str),
"help": "Path to folder for caching notebooks (default: <outdir>)",
"legacy_name": "jupyter_cache",
"sections": (Section.global_lvl, Section.file_lvl, Section.execute),
},
)
execution_excludepatterns: Sequence[str] = dc.field(
default=(),
metadata={
"validator": deep_iterable(instance_of(str)),
"help": "Exclude (POSIX) glob patterns for notebooks",
"legacy_name": "execution_excludepatterns",
"docutils_exclude": True,
"sections": (Section.global_lvl, Section.execute),
},
)
execution_timeout: int = dc.field(
default=30,
metadata={
"validator": instance_of(int),
"help": "Execution timeout (seconds)",
"legacy_name": "execution_timeout",
"sections": (Section.global_lvl, Section.file_lvl, Section.execute),
},
)
execution_in_temp: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Use temporary folder for the execution current working directory",
"legacy_name": "execution_in_temp",
"sections": (Section.global_lvl, Section.file_lvl, Section.execute),
},
)
execution_allow_errors: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Allow errors during execution",
"legacy_name": "execution_allow_errors",
"sections": (Section.global_lvl, Section.file_lvl, Section.execute),
},
)
execution_raise_on_error: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Raise an exception on failed execution, "
"rather than emitting a warning",
"sections": (Section.global_lvl, Section.file_lvl, Section.execute),
},
)
execution_show_tb: bool = dc.field( # TODO implement
default=False,
metadata={
"validator": instance_of(bool),
"help": "Print traceback to stderr on execution error",
"legacy_name": "execution_show_tb",
"sections": (Section.global_lvl, Section.file_lvl, Section.execute),
},
)
# pre-processing options
merge_streams: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Merge stdout/stderr execution output streams",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
# render options
render_plugin: str = dc.field(
default="default",
metadata={
"validator": instance_of(str),
"help": "The entry point for the execution output render class "
"(in group `myst_nb.output_renderer`)",
"sections": (Section.global_lvl, Section.file_lvl, Section.render),
},
)
remove_code_source: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Remove code cell source",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
remove_code_outputs: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Remove code cell outputs",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
code_prompt_show: str = dc.field(
default="Show code cell {type}",
metadata={
"validator": instance_of(str),
"help": "Prompt to expand hidden code cell {content|source|outputs}",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
code_prompt_hide: str = dc.field(
default="Hide code cell {type}",
metadata={
"validator": instance_of(str),
"help": "Prompt to collapse hidden code cell {content|source|outputs}",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
number_source_lines: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Number code cell source lines",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
# we cannot directly obtain a sphinx builder name from docutils,
# so must set it manually
builder_name: str = dc.field(
default="html",
metadata={
"validator": instance_of(str),
"help": "Builder name, to select render priority for mime types",
"sphinx_exclude": True,
},
repr=False,
)
mime_priority_overrides: Sequence[Tuple[str, str, Optional[int]]] = dc.field(
default=(),
metadata={
"validator": deep_iterable(
has_items(
instance_of(str), instance_of(str), optional(instance_of(int))
),
),
"help": "Overrides for the base render priority of mime types: "
"list of (builder name, mime type, priority)",
# TODO how to allow this in docutils?
"docutils_exclude": True,
"sections": (Section.global_lvl, Section.file_lvl, Section.render),
},
repr=False,
)
output_stderr: Literal[
"show", "remove", "remove-warn", "warn", "error", "severe"
] = dc.field(
default="show",
metadata={
"validator": in_(
[
"show",
"remove",
"remove-warn",
"warn",
"error",
"severe",
]
),
"help": "Behaviour for stderr output",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
render_text_lexer: str = dc.field(
default="myst-ansi",
# TODO allow None -> "none"?
# TODO check it can be loaded?
metadata={
"validator": optional(instance_of(str)),
"help": "Pygments lexer applied to stdout/stderr and text/plain outputs",
"cell_key": "text_lexer",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
render_error_lexer: str = dc.field(
default="ipythontb",
# TODO allow None -> "none"?
# TODO check it can be loaded?
metadata={
"validator": optional(instance_of(str)),
"help": "Pygments lexer applied to error/traceback outputs",
"cell_key": "error_lexer",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
render_image_options: Dict[str, str] = dc.field(
default_factory=dict,
# see https://docutils.sourceforge.io/docs/ref/rst/directives.html#image
metadata={
"validator": deep_mapping(instance_of(str), instance_of((str, int))),
"help": "Options for image outputs (class|alt|height|width|scale|align)",
"docutils_exclude": True,
# TODO backward-compatible change to "image_options"?
"cell_key": "image",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
render_figure_options: Dict[str, str] = dc.field(
default_factory=dict,
# see https://docutils.sourceforge.io/docs/ref/rst/directives.html#figure
metadata={
"validator": deep_mapping(instance_of(str), instance_of((str, int))),
"help": "Options for figure outputs (classes|name|caption|caption_before)",
"docutils_exclude": True,
"cell_key": "figure",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
render_markdown_format: Literal["commonmark", "gfm", "myst"] = dc.field(
default="commonmark",
metadata={
"validator": in_(["commonmark", "gfm", "myst"]),
"help": "The format to use for text/markdown rendering",
"cell_key": "markdown_format",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)
# TODO jupyter_sphinx_require_url and jupyter_sphinx_embed_url (undocumented),
# are no longer used by this package, replaced by ipywidgets_js
# do we add any deprecation warnings?
ipywidgets_js: Dict[str, Dict[str, str]] = dc.field(
default_factory=ipywidgets_js_factory,
metadata={
"validator": deep_mapping(
instance_of(str), deep_mapping(instance_of(str), instance_of(str))
),
"help": "Javascript to be loaded on pages containing ipywidgets",
"docutils_exclude": True,
"sections": (Section.global_lvl, Section.render),
},
repr=False,
)
# write options for docutils
output_folder: str = dc.field(
default="build",
metadata={
"validator": instance_of(str),
"help": "Folder for external outputs (like images), skipped if empty",
"sphinx_exclude": True, # in sphinx we always output to the build folder
},
)
append_css: bool = dc.field(
default=True,
metadata={
"validator": instance_of(bool),
"help": "Add default MyST-NB CSS to HTML outputs",
"sphinx_exclude": True,
},
)
metadata_to_fm: bool = dc.field(
default=False,
metadata={
"validator": instance_of(bool),
"help": "Convert unhandled metadata to frontmatter",
"sphinx_exclude": True,
},
)
@classmethod
def get_fields(cls) -> Tuple[dc.Field, ...]:
return dc.fields(cls)
def as_dict(self, dict_factory=dict) -> dict:
return dc.asdict(self, dict_factory=dict_factory)
def as_triple(self) -> Iterable[Tuple[str, Any, dc.Field]]:
"""Yield triples of (name, value, field)."""
fields = {f.name: f for f in dc.fields(self.__class__)}
for name, value in dc.asdict(self).items():
yield name, value, fields[name]
def copy(self, **changes) -> "NbParserConfig":
"""Return a copy of the configuration with optional changes applied."""
return dc.replace(self, **changes)
def __getitem__(self, field: str) -> Any:
"""Get a field value by name."""
if field in ("get_fields", "as_dict", "as_triple", "copy"):
raise KeyError(field)
try:
return getattr(self, field)
except AttributeError:
raise KeyError(field)
def get_cell_level_config(
self,
field_name: str,
cell_metadata: Dict[str, Any],
warning_callback: Callable[[str, str], Any],
) -> Any:
"""Get a configuration value at the cell level.
Takes the highest priority configuration from:
`cell > document > global > default`
:param field: the field name to get the value for
:param cell_metadata: the metadata for the cell
:param warning_callback: a callback to use to warn about issues (msg, subtype)
:raises KeyError: if the field is not found
"""
field: dc.Field = self.__dataclass_fields__[field_name]
cell_key = field.metadata.get("cell_key", field.name)
if (
self.cell_metadata_key not in cell_metadata
and "render" in cell_metadata
and isinstance(cell_metadata["render"], dict)
and cell_key in cell_metadata["render"]
):
warning_callback(
f"Deprecated `cell_metadata_key` 'render' "
f"found, replace with {self.cell_metadata_key!r}",
"cell_metadata_key",
)
cell_meta = cell_metadata["render"]
else:
cell_meta = cell_metadata.get(self.cell_metadata_key, None)
if cell_meta:
try:
if cell_key in cell_meta:
value = cell_meta[cell_key]
if "validator" in field.metadata:
if isinstance(field.metadata["validator"], list):
for validator in field.metadata["validator"]:
validator(self, field, value)
else:
field.metadata["validator"](self, field, value)
return value
except Exception as exc:
warning_callback(f"Cell metadata invalid: {exc}", "cell_config")
# default/global/file level should have already been merged
return getattr(self, field.name)