Skip to content

Commit

Permalink
Merge pull request #31 from PumasAI/mh/yaml
Browse files Browse the repository at this point in the history
Fix #30, correct YAML handling in cells
  • Loading branch information
MichaelHatherly authored Feb 8, 2024
2 parents 5d26bbc + b9b546b commit c2e4325
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 41 deletions.
62 changes: 22 additions & 40 deletions src/server.jl
Original file line number Diff line number Diff line change
Expand Up @@ -607,53 +607,35 @@ function process_cell_source(source::AbstractString)
end

function extract_cell_options(source::AbstractString; file::AbstractString, line::Integer)
function error_message(io::IO, msg::AbstractString)
print(io, " ")
printstyled(IOContext(io, :color => true), "$msg"; color = :red, bold = true)
end

prefix = "#| "
options = Dict{String,Any}()

msg = IOBuffer()
errors = false

yaml = IOBuffer()
none = true
for line in eachline(IOBuffer(source))
print(msg, line)
if startswith(line, prefix)
_, rest = split(line, prefix; limit = 2)
rest = lstrip(rest)
if isempty(rest)
error_message(msg, "blank line")
errors = true
else
try
option = YAML.load(rest)
if isa(option, Dict)
merge!(options, option)
else
error_message(msg, "invalid syntax")
errors = true
end
catch error
error_message(msg, string(error))
errors = true
end
end
println(yaml, rest)
none = false
end
println(msg)
end
if errors
error("""
Error parsing cell attributes:
$(file):$(line)
```{julia}
$(rstrip(String(take!(msg))))
```
""")
if none
return Dict{String,Any}()
else
seekstart(yaml)
options = try
YAML.load(yaml)
catch
msg = """
Error parsing cell attributes at $(file):$(line):
```{julia}
$source
```
"""
error(msg)
end
isa(options, Dict) || error("Cell attributes must be a dictionary.")
return options
end
return options
end

"""
Expand Down
15 changes: 14 additions & 1 deletion test/testsets/cell_options.jl
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ end
line = 1,
) == Dict("valid" => true)

text = """
```{julia}
#| multiline:
#| - 1
#| - 2
```
"""
@test QuartoNotebookRunner.extract_cell_options(
text;
file = "file.qmd",
line = 1,
) == Dict("multiline" => [1, 2])

text = """
```{julia}
#| valid: true
Expand Down Expand Up @@ -68,7 +81,7 @@ end
server = QuartoNotebookRunner.Server()

buffer = IOBuffer()
@test_throws_message "Error parsing cell attributes" QuartoNotebookRunner.run!(
@test_throws_message "Cell attributes must be a dictionary." QuartoNotebookRunner.run!(
server,
notebook;
output = buffer,
Expand Down

0 comments on commit c2e4325

Please sign in to comment.