forked from redhat-documentation/vale-at-red-hat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatchingNumberedCallouts.tengo
72 lines (65 loc) · 1.83 KB
/
MatchingNumberedCallouts.tengo
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
/*
Tengo Language
Checks that numbered callouts (<\d+>) are matching
$ tengo MatchingNumberedCallouts.tengo <asciidoc_file_to_validate>
*/
fmt := import("fmt")
os := import("os")
text := import("text")
input := os.args()
scope := os.read_file(input[2])
matches := []
// clean out multi-line comments
scope = text.re_replace("(?s) *(\n////.*?////\n)", scope, "")
//add a newline, it might be missing
scope += "\n"
codeblock_callout_regex := ".+(<\\d+>)+"
callout_regex := "^<(\\d+)>"
codeblock_callouts := []
inside := false
found := false
num_callouts := 0
num_lines := len(text.split(scope, "\n"))
for line in text.split(scope, "\n") {
// trim trailing whitespace
line = text.trim_space(line)
if text.re_match(codeblock_callout_regex, line) {
inside = true
//account for lines with multiple callouts
for i := 1; i < num_lines; i++ {
//text.contains must be str, not regex
str := "<" + i + ">"
if text.contains(line, str) {
codeblock_callouts = append(codeblock_callouts, i)
}
}
} else if text.re_match(callout_regex, line) {
inside = false
found = false
num_callouts = 1
for i in codeblock_callouts {
//cast int > string
j := text.itoa(i)
str := "<" + j + ">"
if text.contains(line, str) {
//setting found allows us to loop through the list of possible matches
found = true
}
num_callouts++
}
if !found {
start := text.index(scope, line)
matches = append(matches, {begin: start, end: start + len(line)})
}
} else if codeblock_callouts && inside == false {
//cycled through num_callouts, reset for next codeblock
if num_callouts == len(codeblock_callouts) {
codeblock_callouts = []
}
}
}
if len(matches) == 0 {
fmt.println("Numbered callouts are balanced")
} else {
fmt.println(matches)
}