Skip to content

Commit

Permalink
Ignore comments in code when generating ToC.
Browse files Browse the repository at this point in the history
  • Loading branch information
erictune committed Jul 13, 2015
1 parent ce25e16 commit 950b11f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
14 changes: 14 additions & 0 deletions cmd/mungedocs/toc.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"bufio"
"bytes"
"fmt"
"regexp"
"strings"
)

Expand Down Expand Up @@ -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")
Expand All @@ -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
Expand Down
4 changes: 4 additions & 0 deletions cmd/mungedocs/toc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down

0 comments on commit 950b11f

Please sign in to comment.