nbdev 3.2.1__tar.gz → 3.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {nbdev-3.2.1/nbdev.egg-info → nbdev-3.3.0}/PKG-INFO +6 -6
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/__init__.py +1 -1
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/_modidx.py +26 -9
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/clean.py +109 -19
- nbdev-3.3.0/nbdev/diff.py +198 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/migrate.py +1 -0
- nbdev-3.3.0/nbdev/process.py +88 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/processors.py +3 -3
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/release.py +33 -7
- nbdev-3.3.0/nbdev/skill.py +181 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/sync.py +1 -2
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/test.py +1 -1
- {nbdev-3.2.1 → nbdev-3.3.0/nbdev.egg-info}/PKG-INFO +6 -6
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev.egg-info/SOURCES.txt +1 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev.egg-info/entry_points.txt +5 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev.egg-info/requires.txt +4 -4
- {nbdev-3.2.1 → nbdev-3.3.0}/pyproject.toml +8 -3
- nbdev-3.2.1/nbdev/diff.py +0 -94
- nbdev-3.2.1/nbdev/process.py +0 -138
- {nbdev-3.2.1 → nbdev-3.3.0}/CONTRIBUTING.md +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/LICENSE +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/MANIFEST.in +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/README.md +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/cli.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/config.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/doclinks.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/export.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/extract_attachments.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/frontmatter.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/imports.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/maker.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/merge.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/qmd.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/quarto.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/scrubmagics.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/serve.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/serve_drv.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev/showdoc.py +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev.egg-info/dependency_links.txt +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/nbdev.egg-info/top_level.txt +0 -0
- {nbdev-3.2.1 → nbdev-3.3.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: nbdev
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.3.0
|
|
4
4
|
Summary: Create delightful software with Jupyter Notebooks
|
|
5
5
|
Author-email: "Jeremy Howard and the fast.ai community" <j@fast.ai>
|
|
6
6
|
License: Apache-2.0
|
|
@@ -13,18 +13,18 @@ Classifier: Natural Language :: English
|
|
|
13
13
|
Classifier: Programming Language :: Python :: 3
|
|
14
14
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
15
|
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
-
Requires-Python: >=3.
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
License-File: LICENSE
|
|
19
|
-
Requires-Dist: fastcore>=1.
|
|
20
|
-
Requires-Dist: execnb>=0.2.
|
|
19
|
+
Requires-Dist: fastcore>=2.1.3
|
|
20
|
+
Requires-Dist: execnb>=0.2.8
|
|
21
21
|
Requires-Dist: astunparse
|
|
22
|
-
Requires-Dist: ghapi>=2.0.
|
|
22
|
+
Requires-Dist: ghapi>=2.0.2
|
|
23
23
|
Requires-Dist: watchdog
|
|
24
24
|
Requires-Dist: asttokens
|
|
25
25
|
Requires-Dist: setuptools
|
|
26
26
|
Requires-Dist: build
|
|
27
|
-
Requires-Dist: fastgit
|
|
27
|
+
Requires-Dist: fastgit>=0.0.7
|
|
28
28
|
Requires-Dist: pyyaml
|
|
29
29
|
Requires-Dist: tomli; python_version < "3.11"
|
|
30
30
|
Provides-Extra: dev
|
|
@@ -5,14 +5,23 @@ d = { 'settings': { 'branch': 'main',
|
|
|
5
5
|
'doc_host': 'https://nbdev.fast.ai',
|
|
6
6
|
'git_url': 'https://github.com/AnswerDotAI/nbdev',
|
|
7
7
|
'lib_path': 'nbdev'},
|
|
8
|
-
'syms': { 'nbdev.clean': { 'nbdev.clean.
|
|
8
|
+
'syms': { 'nbdev.clean': { 'nbdev.clean._add_attrs': ('api/clean.html#_add_attrs', 'nbdev/clean.py'),
|
|
9
|
+
'nbdev.clean._add_jupyter_hooks': ('api/clean.html#_add_jupyter_hooks', 'nbdev/clean.py'),
|
|
10
|
+
'nbdev.clean._canon_dirs': ('api/clean.html#_canon_dirs', 'nbdev/clean.py'),
|
|
11
|
+
'nbdev.clean._cfg_drivers': ('api/clean.html#_cfg_drivers', 'nbdev/clean.py'),
|
|
9
12
|
'nbdev.clean._clean_cell': ('api/clean.html#_clean_cell', 'nbdev/clean.py'),
|
|
10
13
|
'nbdev.clean._clean_cell_output': ('api/clean.html#_clean_cell_output', 'nbdev/clean.py'),
|
|
11
14
|
'nbdev.clean._clean_cell_output_id': ('api/clean.html#_clean_cell_output_id', 'nbdev/clean.py'),
|
|
15
|
+
'nbdev.clean._cmt_dirs': ('api/clean.html#_cmt_dirs', 'nbdev/clean.py'),
|
|
16
|
+
'nbdev.clean._dir_moves': ('api/clean.html#_dir_moves', 'nbdev/clean.py'),
|
|
12
17
|
'nbdev.clean._git_root': ('api/clean.html#_git_root', 'nbdev/clean.py'),
|
|
18
|
+
'nbdev.clean._hoist_nb_meta': ('api/clean.html#_hoist_nb_meta', 'nbdev/clean.py'),
|
|
13
19
|
'nbdev.clean._nbdev_clean': ('api/clean.html#_nbdev_clean', 'nbdev/clean.py'),
|
|
14
20
|
'nbdev.clean._reconfigure': ('api/clean.html#_reconfigure', 'nbdev/clean.py'),
|
|
21
|
+
'nbdev.clean._rm_dir_lines': ('api/clean.html#_rm_dir_lines', 'nbdev/clean.py'),
|
|
15
22
|
'nbdev.clean._skip_or_sub': ('api/clean.html#_skip_or_sub', 'nbdev/clean.py'),
|
|
23
|
+
'nbdev.clean._to_comments': ('api/clean.html#_to_comments', 'nbdev/clean.py'),
|
|
24
|
+
'nbdev.clean._to_meta': ('api/clean.html#_to_meta', 'nbdev/clean.py'),
|
|
16
25
|
'nbdev.clean.clean_jupyter': ('api/clean.html#clean_jupyter', 'nbdev/clean.py'),
|
|
17
26
|
'nbdev.clean.clean_nb': ('api/clean.html#clean_nb', 'nbdev/clean.py'),
|
|
18
27
|
'nbdev.clean.nbdev_clean': ('api/clean.html#nbdev_clean', 'nbdev/clean.py'),
|
|
@@ -61,11 +70,20 @@ d = { 'settings': { 'branch': 'main',
|
|
|
61
70
|
'nbdev.config.update_version': ('api/config.html#update_version', 'nbdev/config.py'),
|
|
62
71
|
'nbdev.config.write_cells': ('api/config.html#write_cells', 'nbdev/config.py')},
|
|
63
72
|
'nbdev.diff': { 'nbdev.diff._cell_changes': ('api/diff.html#_cell_changes', 'nbdev/diff.py'),
|
|
73
|
+
'nbdev.diff._diff_order': ('api/diff.html#_diff_order', 'nbdev/diff.py'),
|
|
74
|
+
'nbdev.diff._dline': ('api/diff.html#_dline', 'nbdev/diff.py'),
|
|
75
|
+
'nbdev.diff._file_srcs': ('api/diff.html#_file_srcs', 'nbdev/diff.py'),
|
|
64
76
|
'nbdev.diff._nb_srcdict': ('api/diff.html#_nb_srcdict', 'nbdev/diff.py'),
|
|
77
|
+
'nbdev.diff._src': ('api/diff.html#_src', 'nbdev/diff.py'),
|
|
78
|
+
'nbdev.diff._srcdict': ('api/diff.html#_srcdict', 'nbdev/diff.py'),
|
|
65
79
|
'nbdev.diff.cell_diffs': ('api/diff.html#cell_diffs', 'nbdev/diff.py'),
|
|
66
80
|
'nbdev.diff.changed_cells': ('api/diff.html#changed_cells', 'nbdev/diff.py'),
|
|
81
|
+
'nbdev.diff.nb_diff': ('api/diff.html#nb_diff', 'nbdev/diff.py'),
|
|
82
|
+
'nbdev.diff.nbdev_diff': ('api/diff.html#nbdev_diff', 'nbdev/diff.py'),
|
|
83
|
+
'nbdev.diff.nbdev_diff_driver': ('api/diff.html#nbdev_diff_driver', 'nbdev/diff.py'),
|
|
67
84
|
'nbdev.diff.nbs_pair': ('api/diff.html#nbs_pair', 'nbdev/diff.py'),
|
|
68
85
|
'nbdev.diff.read_nb_from_git': ('api/diff.html#read_nb_from_git', 'nbdev/diff.py'),
|
|
86
|
+
'nbdev.diff.render_diff': ('api/diff.html#render_diff', 'nbdev/diff.py'),
|
|
69
87
|
'nbdev.diff.source_diff': ('api/diff.html#source_diff', 'nbdev/diff.py')},
|
|
70
88
|
'nbdev.doclinks': { 'nbdev.doclinks.NbdevLookup': ('api/doclinks.html#nbdevlookup', 'nbdev/doclinks.py'),
|
|
71
89
|
'nbdev.doclinks.NbdevLookup.__getitem__': ( 'api/doclinks.html#nbdevlookup.__getitem__',
|
|
@@ -193,17 +211,9 @@ d = { 'settings': { 'branch': 'main',
|
|
|
193
211
|
'nbdev.process.Processor.__call__': ('api/process.html#processor.__call__', 'nbdev/process.py'),
|
|
194
212
|
'nbdev.process.Processor.__init__': ('api/process.html#processor.__init__', 'nbdev/process.py'),
|
|
195
213
|
'nbdev.process.Processor.cell': ('api/process.html#processor.cell', 'nbdev/process.py'),
|
|
196
|
-
'nbdev.process._dir_pre': ('api/process.html#_dir_pre', 'nbdev/process.py'),
|
|
197
|
-
'nbdev.process._directive': ('api/process.html#_directive', 'nbdev/process.py'),
|
|
198
214
|
'nbdev.process._is_direc': ('api/process.html#_is_direc', 'nbdev/process.py'),
|
|
199
215
|
'nbdev.process._mk_procs': ('api/process.html#_mk_procs', 'nbdev/process.py'),
|
|
200
|
-
'nbdev.process._norm_quarto': ('api/process.html#_norm_quarto', 'nbdev/process.py'),
|
|
201
|
-
'nbdev.process._partition_cell': ('api/process.html#_partition_cell', 'nbdev/process.py'),
|
|
202
|
-
'nbdev.process._quarto_re': ('api/process.html#_quarto_re', 'nbdev/process.py'),
|
|
203
|
-
'nbdev.process.extract_directives': ('api/process.html#extract_directives', 'nbdev/process.py'),
|
|
204
|
-
'nbdev.process.first_code_ln': ('api/process.html#first_code_ln', 'nbdev/process.py'),
|
|
205
216
|
'nbdev.process.instantiate': ('api/process.html#instantiate', 'nbdev/process.py'),
|
|
206
|
-
'nbdev.process.nb_lang': ('api/process.html#nb_lang', 'nbdev/process.py'),
|
|
207
217
|
'nbdev.process.opt_set': ('api/process.html#opt_set', 'nbdev/process.py')},
|
|
208
218
|
'nbdev.processors': { 'nbdev.processors.FilterDefaults': ('api/processors.html#filterdefaults', 'nbdev/processors.py'),
|
|
209
219
|
'nbdev.processors.FilterDefaults.__call__': ( 'api/processors.html#filterdefaults.__call__',
|
|
@@ -313,11 +323,17 @@ d = { 'settings': { 'branch': 'main',
|
|
|
313
323
|
'nbdev.release.Release.changelog': ('api/release.html#release.changelog', 'nbdev/release.py'),
|
|
314
324
|
'nbdev.release.Release.latest_notes': ('api/release.html#release.latest_notes', 'nbdev/release.py'),
|
|
315
325
|
'nbdev.release.Release.release': ('api/release.html#release.release', 'nbdev/release.py'),
|
|
326
|
+
'nbdev.release._check_changelog_base': ('api/release.html#_check_changelog_base', 'nbdev/release.py'),
|
|
316
327
|
'nbdev.release._find_config': ('api/release.html#_find_config', 'nbdev/release.py'),
|
|
317
328
|
'nbdev.release._get_conda_meta': ('api/release.html#_get_conda_meta', 'nbdev/release.py'),
|
|
329
|
+
'nbdev.release._is_ancestor': ('api/release.html#_is_ancestor', 'nbdev/release.py'),
|
|
318
330
|
'nbdev.release._issue_txt': ('api/release.html#_issue_txt', 'nbdev/release.py'),
|
|
319
331
|
'nbdev.release._issues_txt': ('api/release.html#_issues_txt', 'nbdev/release.py'),
|
|
320
332
|
'nbdev.release._load_json': ('api/release.html#_load_json', 'nbdev/release.py'),
|
|
333
|
+
'nbdev.release._release_branch': ('api/release.html#_release_branch', 'nbdev/release.py'),
|
|
334
|
+
'nbdev.release._release_head': ('api/release.html#_release_head', 'nbdev/release.py'),
|
|
335
|
+
'nbdev.release._remote_shas': ('api/release.html#_remote_shas', 'nbdev/release.py'),
|
|
336
|
+
'nbdev.release._require_release_branch': ('api/release.html#_require_release_branch', 'nbdev/release.py'),
|
|
321
337
|
'nbdev.release._run': ('api/release.html#_run', 'nbdev/release.py'),
|
|
322
338
|
'nbdev.release._write_yaml': ('api/release.html#_write_yaml', 'nbdev/release.py'),
|
|
323
339
|
'nbdev.release.anaconda_upload': ('api/release.html#anaconda_upload', 'nbdev/release.py'),
|
|
@@ -351,6 +367,7 @@ d = { 'settings': { 'branch': 'main',
|
|
|
351
367
|
'nbdev.showdoc.doc': ('api/showdoc.html#doc', 'nbdev/showdoc.py'),
|
|
352
368
|
'nbdev.showdoc.show_doc': ('api/showdoc.html#show_doc', 'nbdev/showdoc.py'),
|
|
353
369
|
'nbdev.showdoc.showdoc_nm': ('api/showdoc.html#showdoc_nm', 'nbdev/showdoc.py')},
|
|
370
|
+
'nbdev.skill': {},
|
|
354
371
|
'nbdev.sync': { 'nbdev.sync._mod_files': ('api/sync.html#_mod_files', 'nbdev/sync.py'),
|
|
355
372
|
'nbdev.sync._to_absolute': ('api/sync.html#_to_absolute', 'nbdev/sync.py'),
|
|
356
373
|
'nbdev.sync._update_mod': ('api/sync.html#_update_mod', 'nbdev/sync.py'),
|
|
@@ -13,6 +13,7 @@ from astunparse import unparse
|
|
|
13
13
|
from textwrap import indent
|
|
14
14
|
|
|
15
15
|
from fastcore.nbio import *
|
|
16
|
+
from fastcore.nbio import _directive, _dir_line, _meta_directives, _unparse_dir
|
|
16
17
|
from fastcore.script import *
|
|
17
18
|
from fastcore.utils import *
|
|
18
19
|
from fastcore.xtras import *
|
|
@@ -93,11 +94,13 @@ def clean_nb(
|
|
|
93
94
|
allowed_cell_metadata_keys:list=None, # Preserve the list of keys in cell level metadata
|
|
94
95
|
clean_ids=True, # Remove ids from plaintext reprs?
|
|
95
96
|
allowed_out_metadata_keys:list=None, # Preserve the list of keys in output metadata
|
|
97
|
+
repair:bool=True, # Fix structural problems first (see `repair_nb`)?
|
|
96
98
|
):
|
|
97
99
|
"Clean `nb` from superfluous metadata"
|
|
98
|
-
|
|
100
|
+
if repair: repair_nb(nb)
|
|
101
|
+
metadata_keys = {"kernelspec", "jekyll", "jupytext", "doc", "widgets", "nbdev"}
|
|
99
102
|
if allowed_metadata_keys: metadata_keys.update(allowed_metadata_keys)
|
|
100
|
-
cell_metadata_keys = {"hide_input"}
|
|
103
|
+
cell_metadata_keys = {"hide_input", "nbdev"}
|
|
101
104
|
if allowed_cell_metadata_keys: cell_metadata_keys.update(allowed_cell_metadata_keys)
|
|
102
105
|
out_meta_keys = set()
|
|
103
106
|
if allowed_out_metadata_keys: out_meta_keys.update(allowed_out_metadata_keys)
|
|
@@ -126,14 +129,73 @@ def process_write(warn_msg, proc_nb, f_in, f_out=None, disp=False):
|
|
|
126
129
|
warn(f'{warn_msg}')
|
|
127
130
|
warn(e)
|
|
128
131
|
|
|
132
|
+
# %% ../nbs/api/11_clean.ipynb #f6e854ac
|
|
133
|
+
def _cmt_dirs(cell):
|
|
134
|
+
"Comment directives in `cell` as `{name: value}`, plus the partitioned `(dirs,code)` lines"
|
|
135
|
+
dirs,code = cell._partition()
|
|
136
|
+
return dict(t for t in (_directive(s, cell.lang_) for s in dirs) if t),dirs,code
|
|
137
|
+
|
|
138
|
+
def _rm_dir_lines(cell, dirs, code, names):
|
|
139
|
+
"Rewrite `cell` source without the directive lines in `names`"
|
|
140
|
+
cell.set_source(''.join([o for o in dirs if (t:=_directive(o, cell.lang_)) is None or t[0] not in names] + code))
|
|
141
|
+
|
|
142
|
+
def _to_meta(cell, names):
|
|
143
|
+
"Move comment directives in `names` to the cell's `nbdev` metadata key"
|
|
144
|
+
cmts,dirs,code = _cmt_dirs(cell)
|
|
145
|
+
move = {k:v for k,v in cmts.items() if k in names}
|
|
146
|
+
if not move: return
|
|
147
|
+
cell.setdefault('metadata',{}).setdefault('nbdev',{}).update({k:_unparse_dir(v) for k,v in move.items()})
|
|
148
|
+
_rm_dir_lines(cell, dirs, code, move)
|
|
149
|
+
|
|
150
|
+
def _to_comments(cell, names):
|
|
151
|
+
"Move directives in `names` from the cell's `nbdev` metadata key to comments"
|
|
152
|
+
move = {k:v for k,v in _meta_directives(cell).items() if k in names}
|
|
153
|
+
if not move: return
|
|
154
|
+
nbd = cell.metadata['nbdev']
|
|
155
|
+
for k in move: nbd.pop(k, None)
|
|
156
|
+
if not nbd: del cell.metadata['nbdev']
|
|
157
|
+
dirs,code = cell._partition()
|
|
158
|
+
cell.set_source(''.join(dirs + [_dir_line(k, v, cell.lang_) for k,v in move.items()] + code))
|
|
159
|
+
|
|
160
|
+
# %% ../nbs/api/11_clean.ipynb #6e8d013d
|
|
161
|
+
def _canon_dirs(cell):
|
|
162
|
+
"Rewrite `cell`'s comment directives in canonical form (colon-separated, bare for true)"
|
|
163
|
+
dirs,code = cell._partition()
|
|
164
|
+
new = [o if (t:=_directive(o, cell.lang_)) is None else _dir_line(*t, lang=cell.lang_) for o in dirs]
|
|
165
|
+
if new != dirs: cell.set_source(''.join(new + code))
|
|
166
|
+
|
|
167
|
+
def _hoist_nb_meta(nb, names=('default_exp',)):
|
|
168
|
+
"Move notebook-scope directives in `names` to notebook metadata, dropping any cell left empty"
|
|
169
|
+
for c in list(nb.cells):
|
|
170
|
+
cmts,dirs,code = _cmt_dirs(c)
|
|
171
|
+
move = {k:v for k,v in cmts.items() if k in names}
|
|
172
|
+
if not move: continue
|
|
173
|
+
nb.setdefault('metadata',{}).setdefault('nbdev',{}).update({k:_unparse_dir(v) for k,v in move.items()})
|
|
174
|
+
_rm_dir_lines(c, dirs, code, move)
|
|
175
|
+
left = set(c.directives) - {'hide'}
|
|
176
|
+
if not left and not ''.join(c._partition()[1]).strip(): nb.cells.remove(c)
|
|
177
|
+
|
|
178
|
+
def _dir_moves(nb, dirs=False, to_meta=None, to_comments=None, nb_meta=False):
|
|
179
|
+
"Apply directive migrations to loaded notebook dict `nb` in place"
|
|
180
|
+
nbo = dict2nb(nb)
|
|
181
|
+
if to_meta:
|
|
182
|
+
for c in nbo.cells: _to_meta(c, to_meta.split())
|
|
183
|
+
if to_comments:
|
|
184
|
+
for c in nbo.cells: _to_comments(c, to_comments.split())
|
|
185
|
+
if nb_meta: _hoist_nb_meta(nbo)
|
|
186
|
+
if dirs:
|
|
187
|
+
for c in nbo.cells: _canon_dirs(c)
|
|
188
|
+
nb['cells'],nb['metadata'] = nbo.cells,nbo.metadata
|
|
189
|
+
|
|
129
190
|
# %% ../nbs/api/11_clean.ipynb #714357ce
|
|
130
|
-
def _nbdev_clean(nb, path=None, clear_all=None):
|
|
191
|
+
def _nbdev_clean(nb, path=None, clear_all=None, repair=True, dirs=False, to_meta=None, to_comments=None, nb_meta=False):
|
|
131
192
|
cfg = get_config(path=path)
|
|
132
193
|
clear_all = clear_all or cfg.clear_all
|
|
133
194
|
allowed_metadata_keys = cfg.get("allowed_metadata_keys") or []
|
|
134
195
|
allowed_cell_metadata_keys = cfg.get("allowed_cell_metadata_keys") or []
|
|
135
196
|
allowed_out_metadata_keys = cfg.get("allowed_out_metadata_keys") or []
|
|
136
|
-
|
|
197
|
+
if dirs or to_meta or to_comments or nb_meta: _dir_moves(nb, dirs, to_meta, to_comments, nb_meta)
|
|
198
|
+
clean_nb(nb, clear_all, allowed_metadata_keys, allowed_cell_metadata_keys, cfg.clean_ids, allowed_out_metadata_keys, repair=repair)
|
|
137
199
|
if path: nbdev_trust.__wrapped__(path)
|
|
138
200
|
|
|
139
201
|
# %% ../nbs/api/11_clean.ipynb #6af3b9d4
|
|
@@ -142,11 +204,16 @@ def nbdev_clean(
|
|
|
142
204
|
fname:str=None, # A notebook name or glob to clean
|
|
143
205
|
clear_all:bool=False, # Remove all cell metadata and cell outputs?
|
|
144
206
|
disp:bool=False, # Print the cleaned outputs
|
|
145
|
-
stdin:bool=False # Read notebook from input stream
|
|
207
|
+
stdin:bool=False, # Read notebook from input stream
|
|
208
|
+
repair:bool_arg=True, # Fix structural problems, e.g. stray outputs on non-code cells (see `repair_nb`)?
|
|
209
|
+
dirs:bool=False, # Rewrite comment directives in canonical form?
|
|
210
|
+
to_meta:str=None, # Space-separated directive names to move from comments to cell metadata
|
|
211
|
+
to_comments:str=None, # Space-separated directive names to move from cell metadata to comments
|
|
212
|
+
nb_meta:bool=False # Move `default_exp` into notebook metadata?
|
|
146
213
|
):
|
|
147
214
|
"Clean all notebooks in `fname` to avoid merge conflicts"
|
|
148
215
|
# Git hooks will pass the notebooks in stdin
|
|
149
|
-
_clean = partial(_nbdev_clean, clear_all=clear_all)
|
|
216
|
+
_clean = partial(_nbdev_clean, clear_all=clear_all, repair=repair, dirs=dirs, to_meta=to_meta, to_comments=to_comments, nb_meta=nb_meta)
|
|
150
217
|
_write = partial(process_write, warn_msg='Failed to clean notebook', proc_nb=_clean)
|
|
151
218
|
if stdin: return _write(f_in=sys.stdin, f_out=sys.stdout)
|
|
152
219
|
if fname is None: fname = get_config().nbs_path
|
|
@@ -193,8 +260,29 @@ def _git_root():
|
|
|
193
260
|
except OSError: return None
|
|
194
261
|
|
|
195
262
|
# %% ../nbs/api/11_clean.ipynb #e6083614
|
|
263
|
+
def _add_attrs(path, attrs):
|
|
264
|
+
"Append missing attribute lines to git attributes file at `path`"
|
|
265
|
+
txt = path.read_text() if path.exists() else ''
|
|
266
|
+
have = [l.split() for l in txt.splitlines()] # whitespace-insensitive: nbdime writes its lines with tabs
|
|
267
|
+
for attr in attrs:
|
|
268
|
+
if attr.split() not in have:
|
|
269
|
+
if txt and not txt.endswith('\n'): txt+='\n'
|
|
270
|
+
txt += attr+'\n'
|
|
271
|
+
path.write_text(txt)
|
|
272
|
+
|
|
273
|
+
def _cfg_drivers(loc, merge, diff):
|
|
274
|
+
"Define the `jupyternotebook` merge/diff drivers via `git config <loc>`"
|
|
275
|
+
if merge:
|
|
276
|
+
run(f'git config {loc} merge.jupyternotebook.name "resolve conflicts with nbdev_fix"')
|
|
277
|
+
run(f'git config {loc} merge.jupyternotebook.driver "nbdev-merge %O %A %B %P"')
|
|
278
|
+
if diff: run(f'git config {loc} diff.jupyternotebook.command nbdev-diff-driver')
|
|
279
|
+
|
|
196
280
|
@call_parse
|
|
197
|
-
def nbdev_install_hooks(
|
|
281
|
+
def nbdev_install_hooks(
|
|
282
|
+
merge:bool_arg=True, # Install the notebook merge driver?
|
|
283
|
+
diff:bool_arg=True, # Install the notebook diff driver?
|
|
284
|
+
globally:bool_arg=False # Define the drivers in `~/.gitconfig` and the global attributes file, instead of repo files?
|
|
285
|
+
):
|
|
198
286
|
"Install Jupyter and git hooks to automatically clean, trust, and fix merge conflicts in notebooks"
|
|
199
287
|
cfg_path = Path.home()/'.jupyter'
|
|
200
288
|
cfg_path.mkdir(exist_ok=True)
|
|
@@ -204,6 +292,16 @@ def nbdev_install_hooks():
|
|
|
204
292
|
upd = _add_jupyter_hooks(src, fn)
|
|
205
293
|
if upd is not None: fn.write_text(upd)
|
|
206
294
|
|
|
295
|
+
nbdev_attrs = (['*.ipynb merge=jupyternotebook'] if merge else []) + (['*.ipynb diff=jupyternotebook'] if diff else [])
|
|
296
|
+
if globally:
|
|
297
|
+
_cfg_drivers('--global', merge, diff)
|
|
298
|
+
rc,p = run('git config --global --get core.attributesFile', ignore_ex=True)
|
|
299
|
+
if rc: p = os.environ.get('XDG_CONFIG_HOME', '~/.config') + '/git/attributes'
|
|
300
|
+
attrs_path = Path(p).expanduser()
|
|
301
|
+
attrs_path.parent.mkdir(parents=True, exist_ok=True)
|
|
302
|
+
_add_attrs(attrs_path, nbdev_attrs)
|
|
303
|
+
return print("Hooks are installed globally.")
|
|
304
|
+
|
|
207
305
|
repo_path = _git_root()
|
|
208
306
|
if repo_path is None:
|
|
209
307
|
sys.stderr.write('Not in a git repository, git hooks cannot be installed.\n')
|
|
@@ -215,7 +313,8 @@ def nbdev_install_hooks():
|
|
|
215
313
|
os.chmod(fn, os.stat(fn).st_mode | stat.S_IEXEC)
|
|
216
314
|
|
|
217
315
|
cmd = 'git config --local include.path ../.gitconfig'
|
|
218
|
-
|
|
316
|
+
cfg_fn = repo_path/'.gitconfig'
|
|
317
|
+
cfg_fn.write_text(f'''# Generated by nbdev-install-hooks
|
|
219
318
|
#
|
|
220
319
|
# If you need to disable this instrumentation do:
|
|
221
320
|
# git config --local --unset include.path
|
|
@@ -223,19 +322,10 @@ def nbdev_install_hooks():
|
|
|
223
322
|
# To restore:
|
|
224
323
|
# {cmd}
|
|
225
324
|
#
|
|
226
|
-
[merge "nbdev-merge"]
|
|
227
|
-
name = resolve conflicts with nbdev_fix
|
|
228
|
-
driver = nbdev-merge %O %A %B %P
|
|
229
325
|
''')
|
|
326
|
+
_cfg_drivers(f'--file "{cfg_fn}"', merge, diff)
|
|
230
327
|
run(cmd)
|
|
231
328
|
|
|
232
|
-
|
|
233
|
-
nbdev_attr = '*.ipynb merge=nbdev-merge\n'
|
|
234
|
-
try:
|
|
235
|
-
attrs = attrs_path.read_text()
|
|
236
|
-
if nbdev_attr not in attrs:
|
|
237
|
-
if not attrs.endswith('\n'): attrs+='\n'
|
|
238
|
-
attrs_path.write_text(attrs+nbdev_attr)
|
|
239
|
-
except FileNotFoundError: attrs_path.write_text(nbdev_attr)
|
|
329
|
+
_add_attrs(repo_path/'.gitattributes', nbdev_attrs)
|
|
240
330
|
|
|
241
331
|
print("Hooks are installed.")
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Cell-level git diffs for notebooks
|
|
2
|
+
|
|
3
|
+
Docs: https://nbdev.fast.ai/api/diff.html.md"""
|
|
4
|
+
|
|
5
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/api/19_diff.ipynb.
|
|
6
|
+
|
|
7
|
+
# %% auto #0
|
|
8
|
+
__all__ = ['read_nb_from_git', 'nbs_pair', 'changed_cells', 'source_diff', 'cell_diffs', 'render_diff', 'nb_diff',
|
|
9
|
+
'nbdev_diff_driver', 'nbdev_diff']
|
|
10
|
+
|
|
11
|
+
# %% ../nbs/api/19_diff.ipynb #10c8ad0b
|
|
12
|
+
import json
|
|
13
|
+
from fastcore.utils import *
|
|
14
|
+
from fastcore.meta import delegates
|
|
15
|
+
from fastcore.script import *
|
|
16
|
+
from difflib import unified_diff
|
|
17
|
+
from subprocess import CalledProcessError
|
|
18
|
+
from typing import Annotated
|
|
19
|
+
from fastgit import Git
|
|
20
|
+
from fastcore.nbio import *
|
|
21
|
+
from .doclinks import nbglob
|
|
22
|
+
|
|
23
|
+
# %% ../nbs/api/19_diff.ipynb #a8981115
|
|
24
|
+
def read_nb_from_git(
|
|
25
|
+
g:Git, # The git object
|
|
26
|
+
path, # The path to the notebook (absolute or relative to git root)
|
|
27
|
+
ref=None # The git ref to read from (e.g. HEAD); None for working dir
|
|
28
|
+
)->AttrDict: # The notebook; empty if `path` doesn't exist at `ref`
|
|
29
|
+
"Read notebook from git ref (e.g. HEAD) at path, or working dir if ref is None"
|
|
30
|
+
path = Path(path)
|
|
31
|
+
if path.is_absolute(): path = path.relative_to(g.top())
|
|
32
|
+
if ref is None: return read_nb(g.top()/path)
|
|
33
|
+
try: raw = g.show(f'{ref}:{path}', raise_exc=True)
|
|
34
|
+
except CalledProcessError as e:
|
|
35
|
+
if " in '" not in str(e.stderr): raise
|
|
36
|
+
return new_nb([])
|
|
37
|
+
return dict2nb(json.loads(raw))
|
|
38
|
+
|
|
39
|
+
# %% ../nbs/api/19_diff.ipynb #3ac25702
|
|
40
|
+
def _src(c): return c.get('source','')
|
|
41
|
+
|
|
42
|
+
def _srcdict(nb, f=noop):
|
|
43
|
+
"Dict of cell id->`f(cell)`, with positional fallback ids for pre-4.5 notebooks"
|
|
44
|
+
return {c.get('id', f'c{c.idx_}'): f(c) for c in nb.cells}
|
|
45
|
+
|
|
46
|
+
def _nb_srcdict(g:Git, nb_path, ref=None, f=noop): return _srcdict(read_nb_from_git(g, nb_path, ref), f)
|
|
47
|
+
|
|
48
|
+
# %% ../nbs/api/19_diff.ipynb #27ff9a7b
|
|
49
|
+
def nbs_pair(
|
|
50
|
+
nb_path, # Path to the notebook
|
|
51
|
+
ref_a='HEAD', # First git ref (None for working dir)
|
|
52
|
+
ref_b=None, # Second git ref (None for working dir)
|
|
53
|
+
f=noop # Function to call on contents
|
|
54
|
+
): # Tuple of two notebooks
|
|
55
|
+
"NBs at two refs; None means working dir. By default provides HEAD and working dir"
|
|
56
|
+
nb_path = Path(nb_path).resolve()
|
|
57
|
+
g = Git(nb_path.parent)
|
|
58
|
+
return _nb_srcdict(g, nb_path, ref_a, f), _nb_srcdict(g, nb_path, ref_b, f)
|
|
59
|
+
|
|
60
|
+
# %% ../nbs/api/19_diff.ipynb #958aeaf8
|
|
61
|
+
def _cell_changes(
|
|
62
|
+
nb_path, # Path to the notebook
|
|
63
|
+
fn, # function to call to get dict values
|
|
64
|
+
ref_a='HEAD', # First git ref (None for working dir)
|
|
65
|
+
ref_b=None, # Second git ref (None for working dir)
|
|
66
|
+
adds=True, # Include cells in b but not in a
|
|
67
|
+
changes=True, # Include cells with different content
|
|
68
|
+
dels=False, # Include cells in a but not in b
|
|
69
|
+
metadata=False, # Consider cell metadata when comparing
|
|
70
|
+
outputs=False # Consider cell outputs when comparing
|
|
71
|
+
): # Dict of results
|
|
72
|
+
"Apply fn(cell_id, old_content, new_content) to changed cells between two refs"
|
|
73
|
+
def cell_content(c):
|
|
74
|
+
res = c.get('source', '')
|
|
75
|
+
if metadata: res += '\n# metadata: ' + json.dumps(c.get('metadata', {}), sort_keys=True)
|
|
76
|
+
if outputs: res += '\n# outputs: ' + json.dumps(c.get('outputs', []), sort_keys=True)
|
|
77
|
+
return res
|
|
78
|
+
old,new = nbs_pair(nb_path, ref_a, ref_b, f=cell_content)
|
|
79
|
+
res = {}
|
|
80
|
+
if adds: res |= {cid: fn(cid, '', new[cid]) for cid in new if cid not in old}
|
|
81
|
+
if changes: res |= {cid: fn(cid, old[cid], new[cid]) for cid in new if cid in old and new[cid] != old[cid]}
|
|
82
|
+
if dels: res |= {cid: fn(cid, old[cid], '') for cid in old if cid not in new}
|
|
83
|
+
return res
|
|
84
|
+
|
|
85
|
+
# %% ../nbs/api/19_diff.ipynb #6a723bc8
|
|
86
|
+
@delegates(_cell_changes)
|
|
87
|
+
def changed_cells(nb_path, **kwargs):
|
|
88
|
+
"Return set of cell IDs for changed/added/deleted cells between two refs"
|
|
89
|
+
def f(cid,o,n): return cid
|
|
90
|
+
return set(_cell_changes(nb_path, f, **kwargs).keys())
|
|
91
|
+
|
|
92
|
+
# %% ../nbs/api/19_diff.ipynb #079eedb0
|
|
93
|
+
def source_diff(
|
|
94
|
+
old_source, # Original source string
|
|
95
|
+
new_source # New source string
|
|
96
|
+
): # Unified diff string
|
|
97
|
+
"Return unified diff string for source change"
|
|
98
|
+
return '\n'.join(unified_diff(old_source.splitlines(), new_source.splitlines(), lineterm=''))
|
|
99
|
+
|
|
100
|
+
# %% ../nbs/api/19_diff.ipynb #38216afa
|
|
101
|
+
@delegates(_cell_changes)
|
|
102
|
+
def cell_diffs(nb_path, **kwargs):
|
|
103
|
+
"{cell_id:diff} for changed/added/deleted cells between two refs"
|
|
104
|
+
def f(cid,o,n): return source_diff(o,n)
|
|
105
|
+
return _cell_changes(nb_path, f, **kwargs)
|
|
106
|
+
|
|
107
|
+
# %% ../nbs/api/19_diff.ipynb #d670e58e
|
|
108
|
+
_dcolors = {'-':'\x1b[31m', '+':'\x1b[32m', '@':'\x1b[36m', '#':'\x1b[1m', '# ':'\x1b[1;7m'}
|
|
109
|
+
|
|
110
|
+
def _dline(l, maxlen=120, color=False):
|
|
111
|
+
"Truncate `l` to `maxlen` with an ellipsis, optionally colored by its leading diff marker"
|
|
112
|
+
if maxlen and len(l)>maxlen: l = l[:maxlen]+'…'
|
|
113
|
+
c = (_dcolors.get(l[:2]) or _dcolors.get(l[:1])) if color else None
|
|
114
|
+
return f'{c}{l}\x1b[0m' if c else l
|
|
115
|
+
|
|
116
|
+
# %% ../nbs/api/19_diff.ipynb #342fc231
|
|
117
|
+
def _diff_order(old, new):
|
|
118
|
+
"All cell ids in notebook order: `new`'s order, with deleted ids after their predecessor in `old`"
|
|
119
|
+
res,olds = list(new),list(old)
|
|
120
|
+
for i,cid in enumerate(olds):
|
|
121
|
+
if cid in new: continue
|
|
122
|
+
pred = first(o for o in reversed(olds[:i]) if o in res)
|
|
123
|
+
res.insert(res.index(pred)+1 if pred else 0, cid)
|
|
124
|
+
return res
|
|
125
|
+
|
|
126
|
+
# %% ../nbs/api/19_diff.ipynb #eb3fc128
|
|
127
|
+
def render_diff(
|
|
128
|
+
old, # `{id: source}` for the old version of the notebook
|
|
129
|
+
new, # `{id: source}` for the new version
|
|
130
|
+
maxlen:int=120, # Truncate diff lines to this width (falsy: no limit)
|
|
131
|
+
color:bool=False # Add ANSI colors?
|
|
132
|
+
): # One section per changed cell, in notebook order
|
|
133
|
+
"Render cell-level changes between two notebooks as truncated unified diffs"
|
|
134
|
+
res = []
|
|
135
|
+
for cid in _diff_order(old, new):
|
|
136
|
+
o,n = old.get(cid,''), new.get(cid,'')
|
|
137
|
+
if cid in old and cid in new and o==n: continue
|
|
138
|
+
kind = 'modified' if cid in old and cid in new else 'added' if cid in new else 'deleted'
|
|
139
|
+
lines = [f'## {kind} {cid}:'] + source_diff(o,n).splitlines()[2:]
|
|
140
|
+
res.append('\n'.join(_dline(l, maxlen, color) for l in lines))
|
|
141
|
+
return '\n\n'.join(res)
|
|
142
|
+
|
|
143
|
+
# %% ../nbs/api/19_diff.ipynb #7f90d675
|
|
144
|
+
def nb_diff(
|
|
145
|
+
nb_path, # Path to the notebook
|
|
146
|
+
ref_a='HEAD', # First git ref
|
|
147
|
+
ref_b=None, # Second git ref; None for working dir
|
|
148
|
+
maxlen:int=120, # Truncate diff lines to this width (falsy: no limit)
|
|
149
|
+
color:bool=False # Add ANSI colors?
|
|
150
|
+
): # Rendered diff of changed cells
|
|
151
|
+
"Rendered cell diff for `nb_path` between two refs"
|
|
152
|
+
a,b = nbs_pair(nb_path, ref_a, ref_b, f=_src)
|
|
153
|
+
return render_diff(a, b, maxlen=maxlen, color=color)
|
|
154
|
+
|
|
155
|
+
# %% ../nbs/api/19_diff.ipynb #ab9f0b26
|
|
156
|
+
def _file_srcs(path):
|
|
157
|
+
"`{id: source}` from an ipynb file; `{}` when missing or empty (e.g. `/dev/null`)"
|
|
158
|
+
p = Path(path)
|
|
159
|
+
if not p.exists() or not p.stat().st_size: return {}
|
|
160
|
+
return _srcdict(read_nb(p), _src)
|
|
161
|
+
|
|
162
|
+
_pos = Annotated[str, {'opt':False, 'nargs':'?'}] # optional positional CLI arg, as git passes them
|
|
163
|
+
|
|
164
|
+
@call_parse
|
|
165
|
+
def nbdev_diff_driver(
|
|
166
|
+
path:str, # Repo path of the notebook being diffed
|
|
167
|
+
old_file:_pos=None, # Pre-change file (git temp file, or /dev/null)
|
|
168
|
+
old_hex:_pos=None, # Pre-change blob hash
|
|
169
|
+
old_mode:_pos=None, # Pre-change file mode
|
|
170
|
+
new_file:_pos=None, # Post-change file
|
|
171
|
+
new_hex:_pos=None, # Post-change blob hash
|
|
172
|
+
new_mode:_pos=None, # Post-change file mode
|
|
173
|
+
rename_to:_pos=None, # New repo path, when git detected a rename
|
|
174
|
+
similarity:_pos=None, # Similarity score, when git detected a rename
|
|
175
|
+
maxlen:int=120 # Truncate diff lines to this width (0 for no limit)
|
|
176
|
+
):
|
|
177
|
+
"Git external diff driver for notebooks; installed by `nbdev-install-hooks`"
|
|
178
|
+
if not new_file: return print(f'unmerged: {path}')
|
|
179
|
+
color = sys.stdout.isatty() or os.environ.get('GIT_PAGER_IN_USE')=='true'
|
|
180
|
+
res = render_diff(_file_srcs(old_file), _file_srcs(new_file), maxlen=maxlen, color=color)
|
|
181
|
+
if not res: return
|
|
182
|
+
print(_dline(f'# {path}', 0, color))
|
|
183
|
+
print(res, end='\n\n')
|
|
184
|
+
|
|
185
|
+
# %% ../nbs/api/19_diff.ipynb #2604c719
|
|
186
|
+
@call_parse
|
|
187
|
+
def nbdev_diff(
|
|
188
|
+
path:str=None, # Notebook or directory (default: project's notebooks folder)
|
|
189
|
+
ref_a:str='HEAD', # First git ref
|
|
190
|
+
ref_b:str=None, # Second git ref (default: working directory)
|
|
191
|
+
maxlen:int=120, # Truncate diff lines to this width (0 for no limit)
|
|
192
|
+
color:bool_arg=None # Add ANSI colors? (default: only if stdout is a tty)
|
|
193
|
+
):
|
|
194
|
+
"Cell-level diffs for changed notebooks between two git refs"
|
|
195
|
+
if color is None: color = sys.stdout.isatty()
|
|
196
|
+
for p in sorted(nbglob(path)):
|
|
197
|
+
res = nb_diff(p, ref_a, ref_b, maxlen=maxlen, color=color)
|
|
198
|
+
if res: print(_dline(f'# {p}', 0, color), res, sep='\n', end='\n\n')
|
|
@@ -9,6 +9,7 @@ __all__ = ['MigrateProc', 'fp_md_fm', 'migrate_nb', 'migrate_md', 'nbdev_migrate
|
|
|
9
9
|
|
|
10
10
|
# %% ../nbs/api/16_migrate.ipynb #5b687fa0-dc50-48df-8bfc-e98df34e7572
|
|
11
11
|
from .process import *
|
|
12
|
+
from fastcore.nbio import first_code_ln, langs
|
|
12
13
|
from .frontmatter import *
|
|
13
14
|
from .frontmatter import _fm2dict, _re_fm_md, _dict2fm, _insertfm
|
|
14
15
|
from .processors import *
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""A notebook processor
|
|
2
|
+
|
|
3
|
+
Docs: https://nbdev.fast.ai/api/process.html.md"""
|
|
4
|
+
|
|
5
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/api/03_process.ipynb.
|
|
6
|
+
|
|
7
|
+
# %% auto #0
|
|
8
|
+
__all__ = ['opt_set', 'instantiate', 'NBProcessor', 'Processor']
|
|
9
|
+
|
|
10
|
+
# %% ../nbs/api/03_process.ipynb #59172c3d
|
|
11
|
+
from .config import *
|
|
12
|
+
from .maker import *
|
|
13
|
+
from .imports import *
|
|
14
|
+
|
|
15
|
+
from fastcore.nbio import *
|
|
16
|
+
from fastcore.nbio import _meta_directives
|
|
17
|
+
from fastcore.script import *
|
|
18
|
+
from fastcore.imports import *
|
|
19
|
+
|
|
20
|
+
from collections import defaultdict
|
|
21
|
+
|
|
22
|
+
# %% ../nbs/api/03_process.ipynb #e6701805
|
|
23
|
+
def opt_set(var, newval):
|
|
24
|
+
"newval if newval else var"
|
|
25
|
+
return newval if newval else var
|
|
26
|
+
|
|
27
|
+
# %% ../nbs/api/03_process.ipynb #98c9d556
|
|
28
|
+
def instantiate(x, **kwargs):
|
|
29
|
+
"Instantiate `x` if it's a type"
|
|
30
|
+
return x(**kwargs) if isinstance(x,type) else x
|
|
31
|
+
|
|
32
|
+
def _mk_procs(procs, nb): return L(procs).map(instantiate, nb=nb)
|
|
33
|
+
|
|
34
|
+
# %% ../nbs/api/03_process.ipynb #ab147efe
|
|
35
|
+
def _is_direc(f): return getattr(f, '__name__', '-')[-1]=='_'
|
|
36
|
+
|
|
37
|
+
# %% ../nbs/api/03_process.ipynb #7c81f109
|
|
38
|
+
class NBProcessor:
|
|
39
|
+
"Process cells and nbdev comments in a notebook"
|
|
40
|
+
def __init__(self, path=None, procs=None, nb=None, debug=False, rm_directives=True, process=False):
|
|
41
|
+
self.nb = read_nb(path) if nb is None else nb
|
|
42
|
+
self.lang = nb_lang(self.nb)
|
|
43
|
+
for cell in self.nb.cells: cell.directives_ = cell.directives
|
|
44
|
+
nbdirs = {k:v for k,v in _meta_directives(self.nb).items() if not any(k in c.directives_ for c in self.nb.cells)}
|
|
45
|
+
if nbdirs:
|
|
46
|
+
fc = first(c for c in self.nb.cells if c.cell_type=='code')
|
|
47
|
+
if fc is not None: fc.directives_ = nbdirs | fc.directives_
|
|
48
|
+
if rm_directives:
|
|
49
|
+
for cell in self.nb.cells: cell.remove_directives(quarto=rm_directives=='quarto')
|
|
50
|
+
self.procs = _mk_procs(procs, nb=self.nb)
|
|
51
|
+
self.debug,self.rm_directives = debug,rm_directives
|
|
52
|
+
if process: self.process()
|
|
53
|
+
|
|
54
|
+
def _process_cell(self, proc, cell):
|
|
55
|
+
if not hasattr(cell,'source'): return
|
|
56
|
+
if cell.cell_type=='code' and cell.directives_:
|
|
57
|
+
# Option 1: `proc` is directive name with `_` suffix
|
|
58
|
+
f = getattr(proc, '__name__', '-').rstrip('_')
|
|
59
|
+
if f in cell.directives_: self._process_comment(proc, cell, f)
|
|
60
|
+
|
|
61
|
+
# Option 2: `proc` contains a method named `_{directive}_`
|
|
62
|
+
for cmd in cell.directives_:
|
|
63
|
+
f = getattr(proc, f'_{cmd}_', None)
|
|
64
|
+
if f: self._process_comment(f, cell, cmd)
|
|
65
|
+
if callable(proc) and not _is_direc(proc): cell = opt_set(cell, proc(cell))
|
|
66
|
+
|
|
67
|
+
def _process_comment(self, proc, cell, cmd):
|
|
68
|
+
args = cell.directives_[cmd].split()
|
|
69
|
+
if self.debug: print(cmd, args, proc)
|
|
70
|
+
return proc(cell, *args)
|
|
71
|
+
|
|
72
|
+
def _proc(self, proc):
|
|
73
|
+
if hasattr(proc,'begin'): proc.begin()
|
|
74
|
+
for cell in self.nb.cells: self._process_cell(proc, cell)
|
|
75
|
+
if hasattr(proc,'end'): proc.end()
|
|
76
|
+
self.nb.cells = [c for c in self.nb.cells if c and getattr(c,'source',None) is not None]
|
|
77
|
+
for i,cell in enumerate(self.nb.cells): cell.idx_ = i
|
|
78
|
+
|
|
79
|
+
def process(self):
|
|
80
|
+
"Process all cells with all processors"
|
|
81
|
+
for proc in self.procs: self._proc(proc)
|
|
82
|
+
|
|
83
|
+
# %% ../nbs/api/03_process.ipynb #fa1f8668
|
|
84
|
+
class Processor:
|
|
85
|
+
"Base class for processors"
|
|
86
|
+
def __init__(self, nb): self.nb = nb
|
|
87
|
+
def cell(self, cell): pass
|
|
88
|
+
def __call__(self, cell): return self.cell(cell)
|
|
@@ -68,7 +68,7 @@ def cell_lang(cell): return nested_attr(cell, 'metadata.language', 'python')
|
|
|
68
68
|
def _want_doc(c):
|
|
69
69
|
d = c.directives_
|
|
70
70
|
show_d = set(['export', 'exports', 'exec_doc']).intersection(d)
|
|
71
|
-
return c.source and c.cell_type=='code' and show_d and 'hide' not in d and d.get('include
|
|
71
|
+
return c.source and c.cell_type=='code' and show_d and 'hide' not in d and d.get('include') != 'false'
|
|
72
72
|
|
|
73
73
|
class add_show_docs(Processor):
|
|
74
74
|
"Add show_doc cells after exported cells, unless they are already documented"
|
|
@@ -234,7 +234,7 @@ def _do_eval(cell):
|
|
|
234
234
|
if not cell.source or 'nbdev_export'+'()' in cell.source: return
|
|
235
235
|
trees = cell.parsed_()
|
|
236
236
|
if cell.cell_type != 'code' or not trees: return
|
|
237
|
-
if cell.directives_.get('eval
|
|
237
|
+
if cell.directives_.get('eval', '').lower() == 'false': return
|
|
238
238
|
|
|
239
239
|
_show_dirs = {'export','exports','exporti','exec_doc'}
|
|
240
240
|
if cell.directives_.keys() & _show_dirs: return True
|
|
@@ -292,6 +292,6 @@ class FilterDefaults:
|
|
|
292
292
|
|
|
293
293
|
def nb_proc(self, nb):
|
|
294
294
|
"Get an `NBProcessor` with these processors"
|
|
295
|
-
return NBProcessor(nb=nb, procs=self.procs())
|
|
295
|
+
return NBProcessor(nb=nb, procs=self.procs(), rm_directives='quarto')
|
|
296
296
|
|
|
297
297
|
def __call__(self, nb): return self.nb_proc(nb).process()
|