Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #30, correct YAML handling in cells #31

Merged
merged 1 commit into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading