Skip to content

Commit 7285f40

Browse files
authored
Merge pull request JuliaCollections#111 from YingboMa/myb/print
Fix the `printnode` override feature & add test for it
2 parents 41b2c5c + fa559b0 commit 7285f40

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

src/printing.jl

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,9 @@ function print_tree(printnode::Function, io::IO, node;
194194
prefix::AbstractString="",
195195
)
196196
# Get node representation as string
197-
str = repr_node(node, context=io)
197+
buf = IOBuffer()
198+
printnode(IOContext(buf, io), node)
199+
str = String(take!(buf))
198200

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

250252
# Print key
251253
if this_printkeys
252-
buf = IOBuffer()
253254
print_child_key(IOContext(buf, io), child_key)
254255
key_str = String(take!(buf))
255256

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

272273
"""
273274
repr_tree(tree; context=nothing, kw...)
275+
repr_tree(f, tree; context=nothing, kw...)
274276
275277
Get the string result of calling [`print_tree`](@ref) with the supplied arguments.
276278
277279
The `context` argument works as it does in `Base.repr`.
278280
"""
279-
function repr_tree(tree; context=nothing, kw...)
281+
repr_tree(tree; context=nothing, kw...) = repr_tree(printnode, tree; context=nothing, kw...)
282+
function repr_tree(f, tree; context=nothing, kw...)
280283
buf = IOBuffer()
281284
io = context === nothing ? buf : IOContext(buf, context)
282-
print_tree(io, tree; kw...)
285+
print_tree(f, io, tree; kw...)
283286
return String(take!(buf))
284287
end

test/printing.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,4 +188,25 @@ end
188188
│ └─ 5
189189
└─ "baz"
190190
""")
191+
192+
# Test printnode override
193+
str = repr_tree(tree) do io, s
194+
if s isa BoxNode
195+
print(io, s.s)
196+
else
197+
AbstractTrees.printnode(io, s)
198+
end
199+
end
200+
201+
@test endswith(str, """
202+
├─ "foo"
203+
├─ bar
204+
│ ├─ 1
205+
│ ├─ 2:4
206+
│ │ ├─ 2
207+
│ │ ├─ 3
208+
│ │ └─ 4
209+
│ └─ 5
210+
└─ "baz"
211+
""")
191212
end

0 commit comments

Comments
 (0)