-
Notifications
You must be signed in to change notification settings - Fork 187
/
structure_report.go
90 lines (75 loc) · 1.83 KB
/
structure_report.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
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package reporting
import (
"fmt"
"io"
)
const (
blockIndent = "│ "
itemPrefix = "├── "
lastItemPrefix = "└── "
lastBlockIndent = " "
)
// StructureReport represents a hierarchical dump of structural information
type StructureReport struct {
line string
nested []*StructureReport
}
// NewStructureReport creates a new StructureReport
func NewStructureReport(line string) *StructureReport {
return &StructureReport{line: line}
}
// Addf formats a new line in the report, returning a nested report for any additional information
func (sr *StructureReport) Addf(format string, a ...any) *StructureReport {
result := &StructureReport{line: fmt.Sprintf(format, a...)}
sr.nested = append(sr.nested, result)
return result
}
func (sr *StructureReport) SaveTo(writer io.Writer) error {
var indents []string
return sr.writeBlock(writer, indents, "", "")
}
// writeTo writes a block of lines from this StructureReport to a writer
func (sr *StructureReport) writeBlock(
writer io.Writer,
indents []string,
prefixForItem string,
prefixForSubItems string,
) error {
// Write existing prefix
for _, i := range indents {
_, err := io.WriteString(writer, i)
if err != nil {
return err
}
}
_, err := io.WriteString(writer, prefixForItem)
if err != nil {
return err
}
_, err = io.WriteString(writer, sr.line)
if err != nil {
return err
}
_, err = io.WriteString(writer, "\n")
if err != nil {
return err
}
nested := append(indents, prefixForSubItems)
for index, line := range sr.nested {
ind := itemPrefix
sub := blockIndent
if index == len(sr.nested)-1 {
ind = lastItemPrefix
sub = lastBlockIndent
}
err = line.writeBlock(writer, nested, ind, sub)
if err != nil {
return err
}
}
return nil
}