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 the printnode override feature & add test for it #111

Merged
merged 1 commit into from
Aug 1, 2022
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
11 changes: 7 additions & 4 deletions src/printing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@ function print_tree(printnode::Function, io::IO, node;
prefix::AbstractString="",
)
# Get node representation as string
str = repr_node(node, context=io)
buf = IOBuffer()
printnode(IOContext(buf, io), node)
str = String(take!(buf))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this part? This is essentially replacing the function call with its implementation.


# Copy buffer to output, prepending prefix to each line
for (i, line) in enumerate(split(str, '\n'))
Expand Down Expand Up @@ -249,7 +251,6 @@ function print_tree(printnode::Function, io::IO, node;

# Print key
if this_printkeys
buf = IOBuffer()
print_child_key(IOContext(buf, io), child_key)
key_str = String(take!(buf))

Expand All @@ -271,14 +272,16 @@ print_tree(node; kw...) = print_tree(stdout, node; kw...)

"""
repr_tree(tree; context=nothing, kw...)
repr_tree(f, tree; context=nothing, kw...)

Get the string result of calling [`print_tree`](@ref) with the supplied arguments.

The `context` argument works as it does in `Base.repr`.
"""
function repr_tree(tree; context=nothing, kw...)
repr_tree(tree; context=nothing, kw...) = repr_tree(printnode, tree; context=nothing, kw...)
function repr_tree(f, tree; context=nothing, kw...)
buf = IOBuffer()
io = context === nothing ? buf : IOContext(buf, context)
print_tree(io, tree; kw...)
print_tree(f, io, tree; kw...)
return String(take!(buf))
end
21 changes: 21 additions & 0 deletions test/printing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,25 @@ end
│ └─ 5
└─ "baz"
""")

# Test printnode override
str = repr_tree(tree) do io, s
if s isa BoxNode
print(io, s.s)
else
AbstractTrees.printnode(io, s)
end
end

@test endswith(str, """
├─ "foo"
├─ bar
│ ├─ 1
│ ├─ 2:4
│ │ ├─ 2
│ │ ├─ 3
│ │ └─ 4
│ └─ 5
└─ "baz"
""")
end