67 lines
2.4 KiB
Python
67 lines
2.4 KiB
Python
# This script converts the example md-files as jupyter notebook,
|
|
# execute the notebook and convert the notebook back to a md-file
|
|
# with outputs included.
|
|
|
|
import subprocess
|
|
from glob import glob
|
|
import os
|
|
from io import TextIOWrapper
|
|
|
|
|
|
def run_cmd(command: list[str]):
|
|
result = subprocess.run(command, capture_output=True, text=True)
|
|
|
|
print('> ' + ' '.join(command))
|
|
print(result.stdout)
|
|
|
|
assert (not result.stderr or
|
|
any('RuntimeWarning: ' in line for line in result.stderr.splitlines()) or
|
|
any('[NbConvertApp]' in line or 'Warning' in line for line in result.stderr.splitlines())), 'ERROR: ' + result.stderr
|
|
|
|
|
|
def run_rendering(input_path: str, output_directory: str):
|
|
file_name = '.'.join(os.path.basename(input_path).split('.')[:-1])
|
|
assert file_name
|
|
|
|
print(f'- Convert {input_path} ...')
|
|
run_cmd(['notedown', input_path, '--to', 'notebook', '--output', f'{output_directory}/{file_name}.ipynb', '--run'])
|
|
run_cmd(['jupyter', 'nbconvert', '--to', 'markdown', f'{output_directory}/{file_name}.ipynb', '--output', f'{file_name}.md'])
|
|
run_cmd(['python', 'tests/md_to_code.py', 'script', f'{input_path}', f'{output_directory}/{file_name}.py'])
|
|
|
|
|
|
def write_dochtree(f: TextIOWrapper, title: str, items: list[str]):
|
|
f.write('```{toctree}\n')
|
|
f.write(':maxdepth: 1\n')
|
|
#f.write(':hidden:\n')
|
|
#f.write(f':caption: {title}:\n')
|
|
for text in items:
|
|
if not text.startswith('_'):
|
|
f.write(f"{text}\n")
|
|
f.write('```\n\n')
|
|
|
|
|
|
def render_examples(filter: str, example_file: str):
|
|
files = glob(filter)
|
|
names = ['.'.join(os.path.basename(path).split('.')[:-1]) for path in files]
|
|
|
|
with open(example_file, 'w') as f:
|
|
f.write('# Gaspype examples\n\n')
|
|
write_dochtree(f, '', [n for n in names if n.lower() != 'readme'])
|
|
|
|
f.write('## Download Jupyter Notebooks\n\n')
|
|
for path, name in zip(files, names):
|
|
if name.lower() != 'readme':
|
|
run_rendering(path, 'docs/source/api')
|
|
notebook = name + '.ipynb'
|
|
f.write(f'- [{notebook}]({notebook})\n\n')
|
|
|
|
f.write('## Download plain python files\n\n')
|
|
for path, name in zip(files, names):
|
|
if name.lower() != 'readme':
|
|
script_name = name + '.py'
|
|
f.write(f'- [{script_name}]({script_name})\n\n')
|
|
|
|
|
|
if __name__ == "__main__":
|
|
render_examples('examples/*.md', 'docs/source/api/examples.md')
|