-
Notifications
You must be signed in to change notification settings - Fork 0
/
annotations.go
101 lines (85 loc) · 1.9 KB
/
annotations.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
package main
import (
"fmt"
"strconv"
"strings"
)
const (
tabLen = 4
maxLen = 100
)
func annotateLongLines(contents []byte) ([]byte, int) {
annotatedLines := []string{}
lines := strings.Split(string(contents), "\n")
linesToShorten := 0
prevLen := -1
for _, line := range lines {
length := lineLen(line)
if prevLen > -1 {
if length <= maxLen {
// Shortening successful, remove previous annotation
annotatedLines = annotatedLines[:len(annotatedLines)-1]
} else if length < prevLen {
// Replace annotation with new length
annotatedLines[len(annotatedLines)-1] = fmt.Sprintf(
"// prettylines:shorten:%d",
length,
)
linesToShorten += 1
}
} else if !isComment(line) && length > maxLen {
annotatedLines = append(
annotatedLines,
fmt.Sprintf(
"// prettylines:shorten:%d",
length,
),
)
linesToShorten += 1
}
annotatedLines = append(annotatedLines, line)
prevLen = parseAnnotation(line)
}
return []byte(strings.Join(annotatedLines, "\n")), linesToShorten
}
func removeAnnotations(contents []byte) []byte {
cleanedLines := []string{}
lines := strings.Split(string(contents), "\n")
for _, line := range lines {
if !isAnnotation(line) {
cleanedLines = append(cleanedLines, line)
}
}
return []byte(strings.Join(cleanedLines, "\n"))
}
func lineLen(line string) int {
length := 0
for _, char := range line {
if char == '\t' {
length += tabLen
} else {
length += 1
}
}
return length
}
func isAnnotation(line string) bool {
return strings.HasPrefix(
strings.Trim(line, " \t"),
"// prettylines:shorten:",
)
}
func parseAnnotation(line string) int {
if isAnnotation(line) {
components := strings.SplitN(line, ":", 3)
val, err := strconv.Atoi(components[2])
if err != nil {
return -1
}
return val
}
return -1
}
func isComment(line string) bool {
return strings.HasPrefix(strings.Trim(line, " \t"), "//")
}