code blocks will be ignored, added unit test

This commit is contained in:
bjt-user 2024-05-06 23:12:35 +02:00
parent e9abea6b73
commit 779bd103c6
8 changed files with 50 additions and 6 deletions

View File

@ -1,5 +1,11 @@
all:
go run *.go tests/test.md
go run main.go tree.go test_files/test.md
test:
go run main.go tree.go test_files/test.md
go run main.go tree.go test_files/README.md
go run main.go tree.go test_files/weird_headers.md
go run main.go tree.go test_files/audio.md
clean:
rm -vf main

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module mdtoc
go 1.22.2

19
main.go
View File

@ -24,29 +24,38 @@ func is_heading(line string) bool {
}
}
func get_heading_level(heading_text string) int {
func Get_heading_level(heading_text string) int {
level := 0
for i := 0; heading_text[i] == '#'; i++ {
level += 1
if i == (len(heading_text) - 1) {
break
}
}
return level
}
func parse_file(file_name string) []heading {
file_content_raw, err := os.ReadFile(file_name)
var headings []heading
file_content_raw, err := os.ReadFile(file_name)
if err != nil {
log.Fatal(err)
}
file_lines := strings.Split(string(file_content_raw), "\n")
is_codeblock := false
for index, value := range file_lines {
if is_heading(value) {
if strings.HasPrefix(value, "```") {
is_codeblock = !is_codeblock
}
if !is_codeblock && is_heading(value) {
headings = append(
headings, heading{value, get_heading_level(value), (index + 1)})
headings, heading{value, Get_heading_level(value), (index + 1)})
}
}
return headings

26
main_test.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"log"
"testing"
)
func TestGet_heading_level(t *testing.T) {
level := Get_heading_level("# foo")
if level < 0 || level > 6 {
log.Fatal("Level is not between 0 and 6.")
}
level = Get_heading_level("not a header")
if level != 0 {
log.Fatal("A non header should be level 0!")
}
level = Get_heading_level("#")
if level < 0 || level > 6 {
log.Fatal("Level is not between 0 and 6.")
}
}