Skip to content

Commit

Permalink
nbexport should check for valid ipynb file before writing output (#31)
Browse files Browse the repository at this point in the history
* nbexport should check for valid ipynb file before writing output

* Update NBInclude.jl
  • Loading branch information
stevengj authored Jun 1, 2024
1 parent e086c8f commit 785ab4e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/NBInclude.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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

Expand Down
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 785ab4e

Please sign in to comment.