-
-
Notifications
You must be signed in to change notification settings - Fork 154
/
rst.go
89 lines (72 loc) · 1.97 KB
/
rst.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
package lint
import (
"bytes"
"errors"
"os/exec"
"regexp"
"strings"
"github.com/errata-ai/vale/v3/internal/core"
)
// reStructuredText configuration.
//
// reCodeBlock is used to convert Sphinx-style code directives to the regular
// `::` for rst2html, including the use of runtime options (e.g., :caption:).
var reCodeBlock = regexp.MustCompile(`.. (?:raw|code(?:-block)?):: (?:[\w-]+)(?:\s+:\w+: .+)*`)
// We replace custom directives with `.. code::`.
//
// See https://github.com/errata-ai/vale/v2/issues/119.
var reSphinx = regexp.MustCompile(`.. (?:glossary|contents)::`)
var rstArgs = []string{
"--quiet",
"--halt=5",
"--report=5",
"--link-stylesheet",
"--no-file-insertion",
"--no-toc-backlinks",
"--no-footnote-backlinks",
"--no-section-numbering",
}
func (l *Linter) lintRST(f *core.File) error {
var html string
rst2html := core.Which([]string{
"rst2html", "rst2html.py", "rst2html-3", "rst2html-3.py"})
python := core.Which([]string{
"python", "py", "python.exe", "python3", "python3.exe", "py3"})
if rst2html == "" || python == "" {
return core.NewE100("lintRST", errors.New("rst2html not found"))
}
s, err := l.Transform(f)
if err != nil {
return err
}
s = reSphinx.ReplaceAllString(s, ".. code::")
s = reCodeBlock.ReplaceAllString(s, "::")
html, err = callRst(s, rst2html, python)
if err != nil {
return core.NewE100(f.Path, err)
}
return l.lintHTMLTokens(f, []byte(html), 0)
}
func callRst(text, lib, _ string) (string, error) {
var out bytes.Buffer
cmd := exec.Command(lib, rstArgs...)
cmd.Stdin = strings.NewReader(text)
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return "", err
}
html := out.String()
html = strings.ReplaceAll(html, "\r", "")
bodyStart := strings.Index(html, "<body>\n")
if bodyStart < 0 {
bodyStart = -7
}
bodyEnd := strings.Index(html, "\n</body>")
if bodyEnd < 0 || bodyEnd >= len(html) {
bodyEnd = len(html) - 1
if bodyEnd < 0 {
bodyEnd = 0
}
}
return html[bodyStart+7 : bodyEnd], nil
}