73 lines
1.2 KiB
Go
73 lines
1.2 KiB
Go
package main
|
|
|
|
// TODO: read a file line by line
|
|
// use heading struct with
|
|
// line content
|
|
// line number
|
|
// heading level
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
func is_heading(line string) bool {
|
|
if strings.HasPrefix(line, "#") {
|
|
return true
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
|
|
func get_heading_level(heading string) int {
|
|
level := 0
|
|
for i := 0; heading[i] == '#'; i++ {
|
|
level += 1
|
|
}
|
|
return level
|
|
}
|
|
|
|
func print_toc(headings []string) {
|
|
tab_count := 0
|
|
for index, value := range headings {
|
|
if index > 0 {
|
|
prev_level := get_heading_level(headings[index-1])
|
|
cur_level := get_heading_level(headings[index])
|
|
|
|
if cur_level > prev_level {
|
|
tab_count += (cur_level - prev_level)
|
|
} else if cur_level < prev_level {
|
|
tab_count -= (prev_level - cur_level)
|
|
}
|
|
for i := 0; i < tab_count; i++ {
|
|
fmt.Printf("\t")
|
|
}
|
|
}
|
|
fmt.Printf("%s\n", value)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
file_content_raw, err := os.ReadFile(os.Args[1])
|
|
|
|
var headings []string = nil
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
var file_content string = string(file_content_raw)
|
|
|
|
file_lines := strings.Split(file_content, "\n")
|
|
|
|
for _, value := range file_lines {
|
|
if is_heading(value) {
|
|
headings = append(headings, value)
|
|
}
|
|
}
|
|
|
|
print_toc(headings)
|
|
}
|