|
| 1 | +package lint |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "os/exec" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/errata-ai/vale/v3/internal/core" |
| 10 | + "github.com/errata-ai/vale/v3/internal/nlp" |
| 11 | + "github.com/errata-ai/vale/v3/internal/system" |
| 12 | +) |
| 13 | + |
| 14 | +func (l Linter) lintMDX(f *core.File) error { |
| 15 | + var html string |
| 16 | + var err error |
| 17 | + |
| 18 | + exe := system.Which([]string{"mdx2vast"}) |
| 19 | + if exe == "" { |
| 20 | + return core.NewE100("lintMDX", errors.New("mdx2vast not found")) |
| 21 | + } |
| 22 | + |
| 23 | + s, err := l.Transform(f) |
| 24 | + if err != nil { |
| 25 | + return err |
| 26 | + } |
| 27 | + |
| 28 | + html, err = callVast(f, s, exe) |
| 29 | + if err != nil { |
| 30 | + return core.NewE100(f.Path, err) |
| 31 | + } |
| 32 | + |
| 33 | + // NOTE: This is required to avoid finding matches inside info strings. For |
| 34 | + // example, if we're looking for 'json' we many incorrectly report the |
| 35 | + // location as being in an infostring like '```json'. |
| 36 | + // |
| 37 | + // See https://github.com/errata-ai/vale/v2/issues/248. |
| 38 | + body := reExInfo.ReplaceAllStringFunc(f.Content, func(m string) string { |
| 39 | + parts := strings.Split(m, "`") |
| 40 | + |
| 41 | + // This ensures that we respect the number of opening backticks, which |
| 42 | + // could be more than 3. |
| 43 | + // |
| 44 | + // See https://github.com/errata-ai/vale/v2/issues/271. |
| 45 | + tags := strings.Repeat("`", len(parts)-1) |
| 46 | + span := strings.Repeat("*", nlp.StrLen(parts[len(parts)-1])) |
| 47 | + |
| 48 | + return tags + span |
| 49 | + }) |
| 50 | + |
| 51 | + // NOTE: This is required to avoid finding matches inside link references. |
| 52 | + body = reLinkRef.ReplaceAllStringFunc(body, func(m string) string { |
| 53 | + return "][" + strings.Repeat("*", nlp.StrLen(m)-3) + "]" |
| 54 | + }) |
| 55 | + body = reLinkDef.ReplaceAllStringFunc(body, func(m string) string { |
| 56 | + return "[" + strings.Repeat("*", nlp.StrLen(m)-3) + "]:" |
| 57 | + }) |
| 58 | + |
| 59 | + // NOTE: This is required to avoid finding matches inside ordered lists. |
| 60 | + body = reNumericList.ReplaceAllStringFunc(body, func(m string) string { |
| 61 | + return strings.Repeat("*", nlp.StrLen(m)) |
| 62 | + }) |
| 63 | + |
| 64 | + f.Content = body |
| 65 | + return l.lintHTMLTokens(f, []byte(html), 0) |
| 66 | +} |
| 67 | + |
| 68 | +func callVast(_ *core.File, text, exe string) (string, error) { |
| 69 | + var out bytes.Buffer |
| 70 | + var eut bytes.Buffer |
| 71 | + |
| 72 | + cmd := exec.Command(exe) |
| 73 | + cmd.Stdin = strings.NewReader(text) |
| 74 | + cmd.Stdout = &out |
| 75 | + cmd.Stderr = &eut |
| 76 | + |
| 77 | + if err := cmd.Run(); err != nil { |
| 78 | + return "", errors.New(eut.String()) |
| 79 | + } |
| 80 | + |
| 81 | + return out.String(), nil |
| 82 | +} |
0 commit comments