mirror of https://github.com/k3s-io/k3s
Ignore comments in code when generating ToC.
parent
ce25e164e7
commit
950b11f198
|
@ -20,6 +20,7 @@ import (
|
|||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
|
@ -54,8 +55,20 @@ func updateTOC(filePath string, markdown []byte) ([]byte, error) {
|
|||
func buildTOC(markdown []byte) ([]byte, error) {
|
||||
var buffer bytes.Buffer
|
||||
scanner := bufio.NewScanner(bytes.NewReader(markdown))
|
||||
inBlockQuotes := false
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
match, err := regexp.Match("^```", []byte(line))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if match {
|
||||
inBlockQuotes = !inBlockQuotes
|
||||
continue
|
||||
}
|
||||
if inBlockQuotes {
|
||||
continue
|
||||
}
|
||||
noSharps := strings.TrimLeft(line, "#")
|
||||
numSharps := len(line) - len(noSharps)
|
||||
heading := strings.Trim(noSharps, " \n")
|
||||
|
@ -65,6 +78,7 @@ func buildTOC(markdown []byte) ([]byte, error) {
|
|||
tocLine := fmt.Sprintf("%s- [%s](#%s)\n", indent, heading, bookmark)
|
||||
buffer.WriteString(tocLine)
|
||||
}
|
||||
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return []byte{}, err
|
||||
|
|
|
@ -33,6 +33,10 @@ func Test_buildTOC(t *testing.T) {
|
|||
"# Title\nLorem ipsum \n## Section Heading\ndolor sit amet\n",
|
||||
"- [Title](#title)\n - [Section Heading](#section-heading)\n",
|
||||
},
|
||||
{
|
||||
"# Title\nLorem ipsum \n## Section Heading\ndolor sit amet\n```bash\n#!/bin/sh\n```",
|
||||
"- [Title](#title)\n - [Section Heading](#section-heading)\n",
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
actual, err := buildTOC([]byte(c.in))
|
||||
|
|
Loading…
Reference in New Issue