-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
78 lines (63 loc) · 1.71 KB
/
Copy pathparser.go
File metadata and controls
78 lines (63 loc) · 1.71 KB
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
package golumn
import (
"math"
"regexp"
)
type Options struct {
ColumnWidth int
MaxColumnWidth int
ColumnSpacer string
NewLine string
Delim string
Truncate bool
}
type Parser struct {
lines []*Line
padSizes map[int]int // Maps the column index to a pad-size
options *Options
}
func NewParser(input string, options *Options) *Parser {
lines := makeLines(input, options)
padSizes := makePadSizes(lines, options)
return &Parser{
lines: lines,
padSizes: padSizes,
options: options,
}
}
func (p *Parser) Parse(output *string) {
for i, line := range p.lines {
*output += line.Join(p.padSizes, p.options.ColumnSpacer, p.options.Truncate)
if i < len(p.lines)-1 {
*output += p.options.NewLine
}
}
}
func makeLines(input string, options *Options) []*Line {
lines := regexp.MustCompile(options.NewLine).Split(input, -1)
slice := make([]*Line, len(lines))
for i, line := range lines {
slice[i] = NewLine(line, options.Delim)
}
return slice
}
func makePadSizes(lines []*Line, options *Options) map[int]int {
padSizes := make(map[int]int)
for _, line := range lines {
for columnIndex, chunk := range line.chunks {
if options.ColumnWidth > 0 {
padSizes[columnIndex] = options.ColumnWidth
continue
}
// Determine if we need to increase the pad size
// due to this chunk being larger than the next largest
padSizes[columnIndex] = int(math.Max(float64(padSizes[columnIndex]), float64(len(chunk))))
// Ensure pad size is no greater than a max width
// if it was specified
if options.MaxColumnWidth > 0 {
padSizes[columnIndex] = int(math.Min(float64(padSizes[columnIndex]), float64(options.MaxColumnWidth)))
}
}
}
return padSizes
}