Skip to content

Commit

Permalink
Indent dependening on the minimum header
Browse files Browse the repository at this point in the history
This update should address
ekalinin#8.
  • Loading branch information
potomak committed Apr 6, 2017
1 parent 77a18ae commit bb4eb1f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
23 changes: 17 additions & 6 deletions main.go
Expand Up @@ -171,27 +171,38 @@ func GrabToc(html string, absPath string, depth int) *GHToc {
r := regexp.MustCompile(re)

toc := GHToc{}
groups := make(map[string]string)
minHeaderNum := 6
var groups []map[string]string
for _, match := range r.FindAllStringSubmatch(html, -1) {
group := make(map[string]string)
// fill map for groups
for i, name := range r.SubexpNames() {
if i == 0 || name == "" {
continue
}
groups[name] = removeStuf(match[i])
group[name] = removeStuf(match[i])
}
// update minimum header number
n, _ := strconv.Atoi(group["num"])
if n < minHeaderNum {
minHeaderNum = n
}
groups = append(groups, group)
}

for _, group := range groups {
// format result
n, _ := strconv.Atoi(groups["num"])
n, _ := strconv.Atoi(group["num"])
if depth > 0 && n > depth {
continue
}

link := groups["href"]
link := group["href"]
if len(absPath) > 0 {
link = absPath + link
}
tocItem := strings.Repeat(" ", n-1) + "* " +
"[" + EscapeSpecChars(removeStuf(groups["name"])) + "]" +
tocItem := strings.Repeat(" ", n-minHeaderNum) + "* " +
"[" + EscapeSpecChars(removeStuf(group["name"])) + "]" +
"(" + link + ")"
//fmt.Println(tocItem)
toc = append(toc, tocItem)
Expand Down
28 changes: 27 additions & 1 deletion main_test.go
Expand Up @@ -168,7 +168,7 @@ func Test_GrabTocWithAbspath(t *testing.T) {

func Test_EscapedChars(t *testing.T) {
tocExpected := []string{
" * [mod\\_\\*](#mod_)",
"* [mod\\_\\*](#mod_)",
}

toc := *GrabToc(`
Expand All @@ -184,3 +184,29 @@ func Test_EscapedChars(t *testing.T) {
t.Error("Res :", toc, "\nExpected :", tocExpected)
}
}

func Test_MinHeaderNumber(t *testing.T) {
tocExpected := []string{
"* [foo](#foo)",
" * [bar](#bar)",
}

toc := *GrabToc(`
<h3>
<a id="user-content-" class="anchor" href="#foo" aria-hidden="true">
<span class="octicon octicon-link"></span>
</a>
foo
</h3>
<h4>
<a id="user-content-" class="anchor" href="#bar" aria-hidden="true">
<span class="octicon octicon-link"></span>
</a>
bar
</h3>
`, "", 0)

if toc[0] != tocExpected[0] {
t.Error("Res :", toc, "\nExpected :", tocExpected)
}
}

0 comments on commit bb4eb1f

Please sign in to comment.