Skip to content

Commit 8730296

Browse files
committed
fastai fixes
1 parent 2c65186 commit 8730296

15 files changed

+396
-242
lines changed

nbdev/_modidx.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
'nbs_path': 'nbs',
4949
'recursive': 'False',
5050
'repo': 'nbdev',
51-
'requirements': 'fastcore>=1.5.5 execnb',
51+
'requirements': 'fastcore>=1.5.5 execnb astunparse',
5252
'status': '2',
5353
'title': 'nbdev',
5454
'tst_flags': 'notest',
@@ -63,6 +63,7 @@
6363
'nbdev.cli.FilterDefaults.base_postprocs': 'https://nbdev.fast.ai/cli#FilterDefaults.base_postprocs',
6464
'nbdev.cli.FilterDefaults.base_preprocs': 'https://nbdev.fast.ai/cli#FilterDefaults.base_preprocs',
6565
'nbdev.cli.FilterDefaults.base_procs': 'https://nbdev.fast.ai/cli#FilterDefaults.base_procs',
66+
'nbdev.cli.FilterDefaults.nb_proc': 'https://nbdev.fast.ai/cli#FilterDefaults.nb_proc',
6667
'nbdev.cli.FilterDefaults.postprocs': 'https://nbdev.fast.ai/cli#FilterDefaults.postprocs',
6768
'nbdev.cli.FilterDefaults.preprocs': 'https://nbdev.fast.ai/cli#FilterDefaults.preprocs',
6869
'nbdev.cli.FilterDefaults.procs': 'https://nbdev.fast.ai/cli#FilterDefaults.procs',

nbdev/cli.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,11 @@ def nbdev_sidebar(
5555
skip_file_re:str='^[_.]', # Skip files matching regex
5656
skip_folder_re:str='(?:^[_.]|^www$)', # Skip folders matching regex
5757
printit:bool=False, # Print YAML for debugging
58+
force:bool=False, # Create sidebar even if settings.ini custom_sidebar=False
5859
returnit:bool=False # Return list of files found
5960
):
6061
"Create sidebar.yml"
62+
if not force and str2bool(config_key('custom_sidebar', path=False)): return
6163
path = config_key("nbs_path") if not path else Path(path)
6264
files = nbglob(path, func=_f, symlinks=symlinks, file_re=file_re, folder_re=folder_re, file_glob=file_glob,
6365
skip_file_glob=skip_file_glob, skip_file_re=skip_file_re, skip_folder_re=skip_folder_re).sorted(key=_sort)
@@ -101,27 +103,34 @@ def preprocs(self):
101103
def postprocs(self):
102104
"Postprocessors for export"
103105
return self.base_postprocs() + self.xtra_postprocs()
106+
107+
def nb_proc(self, nb):
108+
"Get an `NBProcessor` with these processors"
109+
return NBProcessor(nb=nb, procs=self.procs(), preprocs=self.preprocs(), postprocs=self.postprocs())
104110

105111
# %% ../nbs/10_cli.ipynb 11
106112
@call_parse
107113
def nbdev_filter(
108-
nb_txt:str=None # Notebook text (uses stdin if not provided)
114+
nb_txt:str=None, # Notebook text (uses stdin if not provided)
115+
fname:str=None, # Notebook to read (uses `nb_txt` if not provided)
109116
):
110117
"A notebook filter for Quarto"
111118
os.environ["IN_TEST"] = "1"
112119
filt = get_config().get('exporter', FilterDefaults)()
113120
printit = False
114-
if not nb_txt: nb_txt,printit = sys.stdin.read(),True
121+
if fname: nb_txt = Path(fname).read_text()
122+
elif not nb_txt: nb_txt,printit = sys.stdin.read(),True
115123
nb = dict2nb(loads(nb_txt))
116-
with open(os.devnull, 'w') as dn:
117-
with redirect_stdout(dn):
118-
NBProcessor(nb=nb, procs=filt.procs(), preprocs=filt.preprocs(), postprocs=filt.postprocs()).process()
124+
if printit:
125+
with open(os.devnull, 'w') as dn:
126+
with redirect_stdout(dn): filt.nb_proc(nb).process()
127+
else: filt.nb_proc(nb).process()
119128
res = nb2str(nb)
120129
del os.environ["IN_TEST"]
121130
if printit: print(res, flush=True)
122131
else: return res
123132

124-
# %% ../nbs/10_cli.ipynb 13
133+
# %% ../nbs/10_cli.ipynb 14
125134
_re_version = re.compile('^__version__\s*=.*$', re.MULTILINE)
126135

127136
def update_version():
@@ -153,11 +162,11 @@ def nbdev_bump_version(
153162
update_version()
154163
print(f'New version: {cfg.version}')
155164

156-
# %% ../nbs/10_cli.ipynb 15
165+
# %% ../nbs/10_cli.ipynb 16
157166
def extract_tgz(url, dest='.'):
158167
with urlopen(url) as u: tarfile.open(mode='r:gz', fileobj=u).extractall(dest)
159168

160-
# %% ../nbs/10_cli.ipynb 16
169+
# %% ../nbs/10_cli.ipynb 17
161170
def _get_info(owner, repo, default_branch='main', default_kw='nbdev'):
162171
try: from ghapi.all import GhApi
163172
except:
@@ -180,7 +189,7 @@ def _get_info(owner, repo, default_branch='main', default_kw='nbdev'):
180189

181190
return r.default_branch, default_kw if not r.topics else ' '.join(r.topics), r.description
182191

183-
# %% ../nbs/10_cli.ipynb 18
192+
# %% ../nbs/10_cli.ipynb 19
184193
def prompt_user(**kwargs):
185194
config_vals = kwargs
186195
print('================ nbdev Configuration ================\n')
@@ -193,7 +202,7 @@ def prompt_user(**kwargs):
193202
print(f"\n`settings.ini` updated with configuration values.")
194203
return config_vals
195204

196-
# %% ../nbs/10_cli.ipynb 19
205+
# %% ../nbs/10_cli.ipynb 20
197206
def _fetch_from_git(raise_err=False):
198207
"Get information for settings.ini from the user."
199208
try:
@@ -208,7 +217,7 @@ def _fetch_from_git(raise_err=False):
208217
return dict(lib_name=repo.replace('-', '_'), user=owner, branch=branch, author=author,
209218
author_email=email, keywords=keywords, description=descrip, repo=repo)
210219

211-
# %% ../nbs/10_cli.ipynb 21
220+
# %% ../nbs/10_cli.ipynb 22
212221
_quarto_yml="""ipynb-filters: [nbdev_filter]
213222
214223
project:
@@ -258,7 +267,7 @@ def refresh_quarto_yml():
258267
yml=_quarto_yml.format(**vals)
259268
p.write_text(yml)
260269

261-
# %% ../nbs/10_cli.ipynb 22
270+
# %% ../nbs/10_cli.ipynb 23
262271
@call_parse
263272
def nbdev_new():
264273
"Create a new project from the current git repo"
@@ -285,7 +294,7 @@ def nbdev_new():
285294
settings_path.write_text(settings)
286295
refresh_quarto_yml()
287296

288-
# %% ../nbs/10_cli.ipynb 24
297+
# %% ../nbs/10_cli.ipynb 25
289298
@call_parse
290299
def nbdev_quarto(
291300
path:str=None, # Path to notebooks

nbdev/doclinks.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import ast,contextlib
1919
import pkg_resources,importlib
20+
from astunparse import unparse
2021

2122
from pprint import pformat
2223
from urllib.parse import urljoin
@@ -52,9 +53,9 @@ def write_nbdev_idx(self:DocLinks):
5253
# %% ../nbs/04b_doclinks.ipynb 15
5354
def _binop_leafs(bo, o):
5455
if isinstance(bo.left, ast.BinOp): left = _binop_leafs(bo.left, o)
55-
else: left = [f'{_id_or_attr(bo.left)}.{o.name}']
56+
else: left = [f'{unparse(bo.left).strip()}.{o.name}']
5657
if isinstance(bo.right, ast.BinOp): right = _binop_leafs(bo.right, o)
57-
else: right = [f'{_id_or_attr(bo.right)}.{o.name}']
58+
else: right = [f'{unparse(bo.right).strip()}.{o.name}']
5859
return concat(left + right)
5960

6061
# %% ../nbs/04b_doclinks.ipynb 16
@@ -79,10 +80,9 @@ def get_patch_name(o):
7980
if nm=='patch':
8081
a = o.args.args[0].annotation
8182
if isinstance(a, ast.BinOp): return _binop_leafs(a, o)
82-
else: pre = _id_or_attr(a)
83-
elif nm=='patch_to': pre = o.decorator_list[0].args[0].id
83+
elif nm=='patch_to': a = o.decorator_list[0].args[0]
8484
else: return
85-
return f'{pre}.{o.name}'
85+
return f'{unparse(a).strip()}.{o.name}'
8686

8787
# %% ../nbs/04b_doclinks.ipynb 19
8888
def _exp_meths(tree):

nbdev/migrate.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ def _repl_directives(code_str):
8282
def _fmt(x): return f"#|{x.group(2).replace('-', '_')}"
8383
return _re_v1().sub(_fmt, code_str)
8484

85-
8685
# %% ../nbs/15_migrate.ipynb 28
8786
def _repl_v1dir(nb):
8887
"Replace nbdev v1 with v2 directives."

nbdev/processors.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,7 @@ def __call__(self, cell):
142142
flags = getattr(cell.nb, '_nbflags', [])
143143
if 'skip_showdoc' in flags: return
144144
if _do_eval(cell): self.k.cell(cell)
145-
if self.k.exc:
146-
sys.stderr.write(f'Error in cell {cell.idx_}:\n{cell.source}')
147-
raise self.k.exc[1] from None
145+
if self.k.exc: raise Exception(f'Error: cell {cell.idx_}:\n{cell.source}') from self.k.exc[1]
148146

149147
# %% ../nbs/09_processors.ipynb 37
150148
def populate_language(nb):
@@ -166,7 +164,9 @@ def _def_names(cell, shown):
166164

167165
def _get_nm(tree):
168166
i = tree.value.args[0]
169-
return f'{i.value.id}.{i.attr}' if isinstance(i, ast.Attribute) else i.id
167+
if hasattr(i, 'id'): val = i.id
168+
else: val = try_attrs(i.value, 'id', 'func', 'attr')
169+
return f'{val}.{i.attr}' if isinstance(i, ast.Attribute) else i.id
170170

171171
# %% ../nbs/09_processors.ipynb 45
172172
def add_show_docs(nb):

nbdev/test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def test_nb(fn, skip_flags=None, force_flags=None, do_print=False, showerr=True)
2929

3030
def _no_eval(cell):
3131
if cell.cell_type != 'code': return True
32-
if 'nbdev_export' in cell.source: return True
32+
if 'nbdev_export'+'(' in cell.source: return True
3333
direc = getattr(cell, 'directives_', {}) or {}
3434
if direc.get('eval:', [''])[0].lower() == 'false': return True
3535
return flags & direc.keys()

nbs/01_read.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@
313313
"outputs": [],
314314
"source": [
315315
"#|hide\n",
316-
"#|eval: false\n",
316+
"#| eval: false\n",
317317
"path = Path('../nbdev')\n",
318318
"(path/'read.py').unlink(missing_ok=True)\n",
319319
"\n",

0 commit comments

Comments
 (0)