1- using IJulia
21using JSON
3- using Pkg
2+ using Literate
3+
44ENV [" GKSwstype" ] = " 100"
55
6- function main (;
7- basedir= get (ENV , " DOCDIR" , " docs" ),
8- cachedir= get (ENV , " NBCACHE" , " .cache" ),
9- rmsvg= true )
10- nb = get (ENV , " NB" , " test.ipynb" )
11- IJulia. installkernel (" Julia" , " --project=@." )
12- # nbconvert command options
13- kernelname = " --ExecutePreprocessor.kernel_name=julia-1.$(VERSION . minor) "
14- execute = ifelse (get (ENV , " ALLOWERRORS" , " false" ) == " true" , " --execute --allow-errors" , " --execute" )
15- timeout = " --ExecutePreprocessor.timeout=" * get (ENV , " TIMEOUT" , " -1" )
16- nbout = joinpath (abspath (pwd ()), cachedir, nb)
17- mkpath (dirname (nbout))
18- cmd = ` jupyter nbconvert --to notebook $(execute) $(timeout) $(kernelname) --output $(nbout) $(nb) `
19- run (cmd)
20- rmsvg && strip_svg (nbout)
6+ function main (; rmsvg= true )
7+ file = get (ENV , " NB" , " test.ipynb" )
8+ cachedir = get (ENV , " NBCACHE" , " .cache" )
9+ nb = if endswith (file, " .jl" )
10+ run_literate (file; cachedir)
11+ elseif endswith (file, " .ipynb" )
12+ lit = to_literate (file)
13+ run_literate (lit; cachedir)
14+ else
15+ error (" $(file) is not a valid notebook file!" )
16+ end
17+ rmsvg && strip_svg (nb)
2118 return nothing
2219end
2320
@@ -42,4 +39,35 @@ function strip_svg(ipynb)
4239 return ipynb
4340end
4441
42+ # Convert a Jupyter notebook into a Literate notebook. Adapted from https://github.com/JuliaInterop/NBInclude.jl.
43+ function to_literate (nbpath; shell_or_help = r" ^\s *[;?]" )
44+ nb = open (JSON. parse, nbpath, " r" )
45+ jlpath = splitext (nbpath)[1 ] * " .jl"
46+ open (jlpath, " w" ) do io
47+ separator = " "
48+ for cell in nb[" cells" ]
49+ if cell[" cell_type" ] == " code"
50+ s = join (cell[" source" ])
51+ isempty (strip (s)) && continue # Jupyter doesn't number empty cells
52+ occursin (shell_or_help, s) && continue # Skip cells with shell and help commands
53+ print (io, separator, " #---\n " , s) # Literate code block mark
54+ separator = " \n\n "
55+ elseif cell[" cell_type" ] == " markdown"
56+ txt = join (cell[" source" ])
57+ print (io, separator, " #===\n " , txt, " \n ===#" )
58+ separator = " \n\n "
59+ end
60+ end
61+ end
62+ return jlpath
63+ end
64+
65+ function run_literate (file; cachedir = " .cache" )
66+ outpath = joinpath (abspath (pwd ()), cachedir, dirname (file))
67+ mkpath (outpath)
68+ ipynb = Literate. notebook (file, dirname (file); mdstrings= true , execute= true )
69+ cp (ipynb, joinpath (outpath, basename (ipynb)); force= true )
70+ return ipynb
71+ end
72+
4573main ()
0 commit comments