Ignore comments in code when generating ToC.

pull/6/head
Eric Tune 2015-07-13 09:26:44 -07:00
parent ce25e164e7
commit 950b11f198
2 changed files with 18 additions and 0 deletions

View File

@ -20,6 +20,7 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"fmt" "fmt"
"regexp"
"strings" "strings"
) )
@ -54,8 +55,20 @@ func updateTOC(filePath string, markdown []byte) ([]byte, error) {
func buildTOC(markdown []byte) ([]byte, error) { func buildTOC(markdown []byte) ([]byte, error) {
var buffer bytes.Buffer var buffer bytes.Buffer
scanner := bufio.NewScanner(bytes.NewReader(markdown)) scanner := bufio.NewScanner(bytes.NewReader(markdown))
inBlockQuotes := false
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() 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, "#") noSharps := strings.TrimLeft(line, "#")
numSharps := len(line) - len(noSharps) numSharps := len(line) - len(noSharps)
heading := strings.Trim(noSharps, " \n") 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) tocLine := fmt.Sprintf("%s- [%s](#%s)\n", indent, heading, bookmark)
buffer.WriteString(tocLine) buffer.WriteString(tocLine)
} }
} }
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
return []byte{}, err return []byte{}, err

View File

@ -33,6 +33,10 @@ func Test_buildTOC(t *testing.T) {
"# Title\nLorem ipsum \n## Section Heading\ndolor sit amet\n", "# Title\nLorem ipsum \n## Section Heading\ndolor sit amet\n",
"- [Title](#title)\n - [Section Heading](#section-heading)\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 { for _, c := range cases {
actual, err := buildTOC([]byte(c.in)) actual, err := buildTOC([]byte(c.in))