|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +notebook_files=() |
| 4 | + |
| 5 | +convert_file() { |
| 6 | + local file="$1" |
| 7 | + # Convert to ipynb format, to be consumed by pytest nbval plugin. |
| 8 | + jupytext --to ipynb $file |
| 9 | + if [ $? -ne 0 ]; then |
| 10 | + error_occurred=1 |
| 11 | + echo "Errors when converting $file" |
| 12 | + # Exit early |
| 13 | + exit 1 |
| 14 | + fi |
| 15 | + notebook_file="${file%.md}.ipynb" |
| 16 | + # Stash file in array to be cleaned up at the end. |
| 17 | + notebook_files+=("${notebook_file}") |
| 18 | + local status=$? |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +# If no arguments were provided, exit with error and show usage. |
| 23 | +if [ $# -eq 0 ]; then |
| 24 | + echo "Usage: $0 [filepaths...] | --all" >&2 |
| 25 | + exit 1 |
| 26 | +fi |
| 27 | + |
| 28 | +# Variable to track if any errors occur |
| 29 | +error_occurred=0 |
| 30 | + |
| 31 | +# If --all is passed, locate eligible files and execute them all. |
| 32 | +if [ "$1" == "--all" ]; then |
| 33 | + files=$(find "tutorials" -name "*.md" | grep -v .ipynb_checkpoints) |
| 34 | + for file in $files; do |
| 35 | + if [ -f "$file" ]; then |
| 36 | + # Extract the kernel information from the Jupytext Markdown file |
| 37 | + kernel_info=$(grep -A 10 '^---$' "$file" | grep -E 'kernelspec') |
| 38 | + # Skip if no kernel information was found |
| 39 | + if [ -z "$kernel_info" ]; then |
| 40 | + continue |
| 41 | + fi |
| 42 | + convert_file "$file" |
| 43 | + if [ $? -ne 0 ]; then |
| 44 | + error_occurred=1 |
| 45 | + fi |
| 46 | + else |
| 47 | + echo "File not found: $file" >&2 |
| 48 | + fi |
| 49 | + done |
| 50 | +else |
| 51 | + # If filepaths are passed, execute them. |
| 52 | + for file in "$@"; do |
| 53 | + if [ -f "$file" ]; then |
| 54 | + convert_file "$file" |
| 55 | + if [ $? -ne 0 ]; then |
| 56 | + error_occurred=1 |
| 57 | + fi |
| 58 | + else |
| 59 | + echo "File not found: $file" >&2 |
| 60 | + # Exit early |
| 61 | + exit 1 |
| 62 | + fi |
| 63 | + done |
| 64 | +fi |
| 65 | + |
| 66 | +pytest --nbval |
| 67 | + |
| 68 | +# Clean up ipynb files that were converted. Any stray ipynb files that were |
| 69 | +# _not_ the result of conversion from Markdown will be left alone. |
| 70 | +for file in "${notebook_files[@]}"; do |
| 71 | + rm -v "$file" |
| 72 | +done |
| 73 | + |
| 74 | +if [ $error_occurred -ne 0 ]; then |
| 75 | + echo "Some files executed with unexpected errors." >&2 |
| 76 | + exit 1 |
| 77 | +else |
| 78 | + echo "All files executed successfully." >&2 |
| 79 | + exit 0 |
| 80 | +fi |
| 81 | + |
| 82 | + |
0 commit comments