From 785ab4eb22155d89e2b00933697393189c20ddcc Mon Sep 17 00:00:00 2001 From: "Steven G. Johnson" Date: Fri, 31 May 2024 21:54:27 -0400 Subject: [PATCH] nbexport should check for valid ipynb file before writing output (#31) * nbexport should check for valid ipynb file before writing output * Update NBInclude.jl --- src/NBInclude.jl | 16 ++++++++++++---- test/runtests.jl | 3 +++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/NBInclude.jl b/src/NBInclude.jl index c3c9a34..c14216f 100644 --- a/src/NBInclude.jl +++ b/src/NBInclude.jl @@ -168,8 +168,8 @@ macro nbinclude(args...) return Expr(:call, :nbinclude, Expr(:parameters, kws...), args...) end -function nbexport(io::IO, nbpath::AbstractString; regex::Regex = r"", markdown::Bool=true) - nb = open(JSON.parse, nbpath, "r") +# low-level nbexport function that takes in the `nb` Dict +function _nbexport(io::IO, nb::AbstractDict, regex::Regex, markdown::Bool=true) separator = "" for cell in nb["cells"] if cell["cell_type"] == "code" @@ -188,8 +188,16 @@ function nbexport(io::IO, nbpath::AbstractString; regex::Regex = r"", markdown:: return io end -function nbexport(jlpath::AbstractString, nbpath::AbstractString; kws...) - open(io -> nbexport(io, nbpath; kws...), jlpath, "w") +function nbexport(io::IO, nbpath::AbstractString; regex::Regex = r"", markdown::Bool=true) + nb = open(JSON.parse, nbpath, "r") + return _nbexport(io, nb, regex, markdown) +end + +function nbexport(jlpath::AbstractString, nbpath::AbstractString; regex::Regex = r"", markdown::Bool=true) + # parse the notebook file before overwriting the jlpath, + # to avoid overwriting files on errors (issue #30) + nb = open(JSON.parse, nbpath, "r") + open(io -> _nbexport(io, nb, regex, markdown), jlpath, "w") return nothing end diff --git a/test/runtests.jl b/test/runtests.jl index f398580..8d35235 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -33,6 +33,9 @@ let desired_output = "# This is an example notebook:\n\nfunction f(x)\n ret test_ipynb = joinpath(@__DIR__, "test.ipynb"), outfilename = tempname() @test sprint(nbexport, test_ipynb) == desired_output try + # wrong arg order should not overwrite ipynb (#30): + @test_throws Exception nbexport(test_ipynb, outfilename) + nbexport(outfilename, test_ipynb) @test read(outfilename, String) == desired_output finally