-
Notifications
You must be signed in to change notification settings - Fork 1
/
treeprinter.go
111 lines (94 loc) · 2.56 KB
/
treeprinter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright 2020-2021 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sql
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"strings"
)
// TreePrinter is a printer for tree nodes.
type TreePrinter struct {
buf bytes.Buffer
nodeWritten bool
written bool
}
// NewTreePrinter creates a new tree printer.
func NewTreePrinter() *TreePrinter {
return new(TreePrinter)
}
// WriteNode writes the main node.
func (p *TreePrinter) WriteNode(format string, args ...interface{}) error {
if p.nodeWritten {
return ErrNodeAlreadyWritten
}
_, err := fmt.Fprintf(&p.buf, format, args...)
if err != nil {
return err
}
p.nodeWritten = true
p.buf.WriteRune('\n')
return nil
}
var (
// ErrNodeNotWritten is returned when the children are printed before the node.
ErrNodeNotWritten = errors.New("treeprinter: a child was written before the node")
// ErrNodeAlreadyWritten is returned when the node has already been written.
ErrNodeAlreadyWritten = errors.New("treeprinter: node already written")
// ErrChildrenAlreadyWritten is returned when the children have already been written.
ErrChildrenAlreadyWritten = errors.New("treeprinter: children already written")
)
// WriteChildren writes a children of the tree.
func (p *TreePrinter) WriteChildren(children ...string) error {
if !p.nodeWritten {
return ErrNodeNotWritten
}
if p.written {
return ErrChildrenAlreadyWritten
}
p.written = true
for i, child := range children {
last := i+1 == len(children)
r := bufio.NewReader(strings.NewReader(child))
var first = true
for {
line, _, err := r.ReadLine()
if err == io.EOF {
break
}
if err != nil {
return err
}
if first && last {
p.buf.WriteString(" └─ ")
} else if first {
p.buf.WriteString(" ├─ ")
} else if !last {
p.buf.WriteString(" │ ")
} else {
p.buf.WriteString(" ")
}
p.buf.Write(line)
p.buf.WriteRune('\n')
first = false
}
}
return nil
}
// String returns the output of the printed tree.
func (p *TreePrinter) String() string {
return p.buf.String()
}