-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
printer.go
143 lines (124 loc) · 2.51 KB
/
printer.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package coverage
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"strconv"
"strings"
"github.com/fatih/color"
"github.com/goark/gnkf/enc"
"github.com/goark/gnkf/guess"
)
const maxSrcSize = 1073741824 //1GB
type Printer struct {
fc *FileCoverage
}
func NewPrinter(fc *FileCoverage) *Printer {
return &Printer{
fc: fc,
}
}
func (p *Printer) Print(src io.Reader, dest io.Writer) error {
dup := new(bytes.Buffer)
size, err := io.CopyN(dup, src, maxSrcSize)
if !errors.Is(err, io.EOF) {
return err
}
if size >= maxSrcSize {
return fmt.Errorf("too large file size to copy: %d >= %d", size, maxSrcSize)
}
b := dup.Bytes()
c := bytes.Count(b, []byte{'\n'})
w := len(strconv.Itoa(c))
w2 := len(strconv.Itoa(p.fc.Blocks.MaxCount()))
e, err := guess.EncodingBytes(b)
if err != nil {
return err
}
dup2 := new(bytes.Buffer)
if err := enc.Convert("UTF-8", dup2, e[0], dup); err != nil {
return err
}
lcs := p.fc.Blocks.ToLineCoverages()
scanner := bufio.NewScanner(dup2)
n := 1
cl := color.New(color.FgYellow)
cl.EnableColor()
for scanner.Scan() {
lc, _ := lcs.FindByLine(n) //nostyle:handlerrors
c, out := paintLine(n, w2, scanner.Text(), lc)
if _, err := fmt.Fprintf(dest, "%s %s %s\n", cl.Sprint(fmt.Sprintf(fmt.Sprintf("%%%dd", w), n)), c, out); err != nil {
return err
}
n += 1
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}
const (
posGreen = "g"
posRed = "r"
)
func lineCovered(lcnt int, lc *LineCoverage) (int, []string) {
l := make([]string, lcnt)
if lc == nil {
return 0, l
}
for i := 0; i < lcnt; i++ {
c, err := lc.PosCoverages.FindCountByPos(i + 1)
if err != nil {
continue
}
if c > 0 {
l[i] = posGreen
} else {
l[i] = posRed
}
}
return lc.Count, l
}
func paintLine(n, w int, in string, lc *LineCoverage) (string, string) {
g := color.New(color.FgGreen)
g.EnableColor()
r := color.New(color.FgRed)
r.EnableColor()
lcnt := len(in)
c, l := lineCovered(lcnt, lc)
out := ""
pos := 0
current := ""
for i, cl := range l {
if current == cl {
continue
}
switch current {
case "":
out += in[pos:i]
case posGreen:
out += g.Sprint(in[pos:i])
case posRed:
out += r.Sprint(in[pos:i])
}
current = cl
pos = i
}
switch current {
case "":
out += in[pos:lcnt]
case posGreen:
out += g.Sprint(in[pos:lcnt])
case posRed:
out += r.Sprint(in[pos:lcnt])
}
s := strings.Repeat(" ", w)
if c > 0 {
g := color.New(color.FgHiGreen)
g.EnableColor()
s = g.Sprintf(fmt.Sprintf("%%%dd", w), c)
}
return s, out
}