-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockcheck.go
115 lines (93 loc) · 2.12 KB
/
blockcheck.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
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
)
func readBlockContents(scanner *bufio.Scanner) (string, error) {
blockStarted := false
contents := ""
for scanner.Scan() {
line := scanner.Text()
if blockStarted {
if strings.HasPrefix(line, "```") {
return contents + "\n", nil
}
if contents == "" {
contents = line
} else {
contents = contents + "\n" + line
}
} else if strings.HasPrefix(line, "```") {
blockStarted = true
} else {
return "", errors.New("Expected a code block (```) after BLOCKCHECK comment")
}
}
return "", errors.New("Reached EOF before finding end of code block (```)")
}
func checkFile(markdownFile string) int {
f, err := os.Open(markdownFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer f.Close()
scanner := bufio.NewScanner(f)
re := regexp.MustCompile("<!-- blockcheck ([^ -]+) ?-->")
checks := 0
for scanner.Scan() {
line := scanner.Text()
if match := re.FindStringSubmatch(line); match != nil {
blockContents, err := readBlockContents(scanner)
if err != nil {
fmt.Printf(err.Error())
os.Exit(1)
}
relativePath := filepath.Dir(markdownFile)
compareFile := filepath.Join(relativePath, string(os.PathSeparator), match[1])
compareContents, err := ioutil.ReadFile(compareFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if string(compareContents) != blockContents {
fmt.Printf("Block in %s does not match %s\n", markdownFile, compareFile)
os.Exit(1)
}
checks++
}
}
return checks
}
func main() {
verbose := flag.Bool("v", false, "Print verbose output")
flag.Parse()
var fileNames []string
if flag.NArg() == 0 {
// Read file names from stdin.
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
fileNames = strings.Split(strings.Trim(string(input), "\n"), "\n")
} else {
fileNames = flag.Args()
}
for _, f := range fileNames {
if *verbose {
fmt.Printf("%s: ", f)
}
checks := checkFile(f)
if *verbose {
fmt.Printf("%d passed\n", checks)
}
}
}