Skip to content

Commit 29c445d

Browse files
committed
treeprinter: add DotDotDot
Add a feature to add a vertical ellipsis indicating that a node has more hidden children.
1 parent 00f1d21 commit 29c445d

File tree

2 files changed

+65
-5
lines changed

2 files changed

+65
-5
lines changed

internal/treeprinter/tree_printer.go

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,12 @@ import (
1111
)
1212

1313
var (
14-
edgeLinkChr = rune('│')
15-
edgeMidChr = rune('├')
16-
edgeLastChr = rune('└')
17-
horLineChr = rune('─')
18-
bulletChr = rune('•')
14+
edgeLinkChr = rune('│')
15+
edgeMidChr = rune('├')
16+
edgeLastChr = rune('└')
17+
horLineChr = rune('─')
18+
bulletChr = rune('•')
19+
dotDotDotChr = rune('⋮')
1920
)
2021

2122
// Node is a handle associated with a specific depth in a tree. See below for
@@ -250,6 +251,33 @@ func (n Node) Child(text string) Node {
250251
return n.childLine(text)
251252
}
252253

254+
// DotDotDot adds an indication that this node has children that are not shown.
255+
func (n Node) DotDotDot() {
256+
t := n.tree
257+
t.rows = append(t.rows, nil)
258+
rowIdx := len(t.rows) - 1
259+
edgePos := (n.level - 1) * len(t.edgeLast)
260+
if len(t.stack) <= n.level {
261+
// No siblings; Connect to parent.
262+
if len(t.stack) != n.level {
263+
panic("misuse of node")
264+
}
265+
parentRow := t.stack[n.level-1].firstChildConnectRow
266+
for i := parentRow + 1; i < rowIdx; i++ {
267+
t.set(i, edgePos, t.edgeLink)
268+
}
269+
t.set(rowIdx, edgePos, []rune{' ', dotDotDotChr})
270+
} else {
271+
// Case 3: non-first child. Connect to sibling.
272+
siblingRow := t.stack[n.level].nextSiblingConnectRow
273+
t.set(siblingRow, edgePos, t.edgeMid)
274+
for i := siblingRow + 1; i < rowIdx; i++ {
275+
t.set(i, edgePos, t.edgeLink)
276+
}
277+
t.set(rowIdx, edgePos, []rune{' ', dotDotDotChr})
278+
}
279+
}
280+
253281
// AddLine adds a new line to a node without an edge.
254282
func (n Node) AddLine(text string) {
255283
t := n.tree

internal/treeprinter/tree_printer_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,35 @@ tree of trees
227227
t.Errorf("incorrect result:\n%s", res)
228228
}
229229
}
230+
231+
func TestTreePrinterDotDotDot(t *testing.T) {
232+
tp := New()
233+
r1 := tp.Child("root")
234+
r11 := r1.Child("1.1")
235+
r11.DotDotDot()
236+
r12 := r1.Child("1.2")
237+
r12.Child("1.2.1")
238+
r122 := r12.Child("1.2.2")
239+
r122.Child("1.2.2.1")
240+
r122.Child("1.2.2.2")
241+
r122.Child("1.2.2.3")
242+
r12.DotDotDot()
243+
res := tp.String()
244+
245+
exp := `
246+
root
247+
├── 1.1
248+
│ ⋮
249+
└── 1.2
250+
├── 1.2.1
251+
├── 1.2.2
252+
│ ├── 1.2.2.1
253+
│ ├── 1.2.2.2
254+
│ └── 1.2.2.3
255+
256+
`
257+
exp = strings.TrimLeft(exp, "\n")
258+
if res != exp {
259+
t.Errorf("incorrect result:\n%s", res)
260+
}
261+
}

0 commit comments

Comments
 (0)