Convert .ngscript
to .jl
¶
This example implements a simple utility to convert .ngscript
to files with the extension .jl
, intended for direct execution in the Julia terminal.
The main task of the script is to extract the contents of notebook cells (including both markdown text and executable code) and save them in a readable format.
The script itself reads the notebook content represented in JSON format, processing two main categories of cells: markdown cells and code cells. The markdown cells are saved as comments, while code cells are written literally, providing the ability to run later. It is also possible to skip markdown cells if necessary.
using JSON
Let's look at the function itself. It takes the path to the input file and an optional argument skip_markdown
, which determines whether to skip markdown cells during conversion.
Now let's turn to the algorithm and consider it line by line.
- Declare a function.
- Convert the relative path to an absolute path.
- Form the output file name by replacing the source file extension with
.jl
. - Read the contents of the JSON format file and parse it into a Julia structure.
- Open the output file for writing.
- Cycle through all the cells.
- If a cell is found to be of type markdown.
- Skip processing if the markdown cell skip flag is set.
- Skip markdown cells containing inserted images (
![]
). - Write the contents of the markdown cell as a Julia comment (
#=...=#
). - if the cell is a code and contains a non-zero number of rows.
- Write the lines of code directly to the file, preserving their order.
- End.
function script2jl(input_path::String; skip_markdown=false)
input_file = abspath(input_path)
output_file = replace(input_file, r"\.\w+$" => ".jl")
notebook = JSON.parsefile(input_file)
open(output_file, "w") do f
for cell in notebook["cells"]
if cell["cell_type"] == "markdown"
skip_markdown && continue
any(startswith(l, "![") for l in cell["source"]) && continue
println(f, "#= ", join(cell["source"]), " =#\n")
elseif cell["cell_type"] == "code" && !isempty(cell["source"])
println(f, join(cell["source"]), "\n")
end
end
end
println("Конвертация ngscript в jl завершена.")
end
Examples of use¶
Convert script2jl.ngscript file with absolute path without skipping the markdown cell.
@time script2jl("$(@__DIR__)/script2jl.ngscript")
Convert script2jl.ngscript file with missing markdown cell.
@time script2jl("script2jl.ngscript", skip_markdown=true)
Conclusion¶
As a result of executing this example, we got the code in the format .jl
which can be attached to any project via the command include("$(@__DIR__)/script2jl.jl")
.
This tool is useful for developers who use .ngscript
for experimentation and prototyping. It allows you to easily transfer working code into full-fledged Julia programs.
Thanks to its simplicity and flexibility, the script improves software development efficiency and simplifies migration between programming environments.