#!/bin/sh
set -e
if [ "$1" = --remove ]; then
exec find . -name "*-NOTES.md" -delete
fi
if ! command -v jq >/dev/null; then
exec guix shell jq -- "$0" "$@"
fi
if [ $# -lt 1 ]; then
exec find . -name "*.ipynb" -and \
'!' -wholename "*/.ipynb_checkpoints/*" -and \
'!' -name "*-NOTELESS.ipynb" \
-exec "$0" '{}' \;
fi
for FILE in "$@"; do
DST="$(printf %s "$FILE" |
sed 's/\(-NOTES[.]md\|\(-NOTELESS\)\?[.]ipynb\)$/-NOTES.md/')"
NOTEBOOK="$(printf %s "$FILE" |
sed 's/\(-NOTES[.]md\|\(-NOTELESS\)\?[.]ipynb\)$/.ipynb/')"
jq --join-output '
.cells[] |
select(.cell_type == "markdown") |
if (.source[0]? + "") | test("^_notes_") then
"\n", .source[1:][], "\n\n"
else
.source[] |
select(test("^#")) |
if test("\n$") then . else . + "\n" end
end
' < "$NOTEBOOK" > "$DST"
done