122 lines
2.1 KiB
Go
122 lines
2.1 KiB
Go
package main
|
|
|
|
// TODO: read a file line by line
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
type heading struct {
|
|
text string
|
|
level int
|
|
line int
|
|
parent *heading
|
|
}
|
|
|
|
func is_heading(line string) bool {
|
|
if strings.HasPrefix(line, "#") {
|
|
return true
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
|
|
func get_heading_level(heading_text string) int {
|
|
level := 0
|
|
for i := 0; heading_text[i] == '#'; i++ {
|
|
level += 1
|
|
}
|
|
return level
|
|
}
|
|
|
|
func count_levels(headings []heading) [6]int {
|
|
level_count := [6]int{}
|
|
|
|
for index, _ := range headings {
|
|
switch headings[index].level {
|
|
case 1:
|
|
level_count[0]++
|
|
case 2:
|
|
level_count[1]++
|
|
case 3:
|
|
level_count[2]++
|
|
case 4:
|
|
level_count[3]++
|
|
case 5:
|
|
level_count[4]++
|
|
case 6:
|
|
level_count[5]++
|
|
}
|
|
}
|
|
|
|
return level_count
|
|
}
|
|
|
|
func get_parents(headings []heading) {
|
|
for index, _ := range headings {
|
|
if index == 0 {
|
|
headings[index].parent = nil
|
|
continue
|
|
}
|
|
|
|
for i := (index - 1); i >= 0; i-- {
|
|
if headings[i].level < headings[index].level {
|
|
headings[index].parent = &headings[i]
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func print_children(heading *heading, headings []heading) {
|
|
fmt.Printf("pointer of parent: %p\n", heading)
|
|
|
|
for index, _ := range headings {
|
|
if headings[index].parent == heading {
|
|
fmt.Printf("Header of parent %p: %s\n", heading, headings[index].text)
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
file_content_raw, err := os.ReadFile(os.Args[1])
|
|
|
|
var headings []heading = nil
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
var file_content string = string(file_content_raw)
|
|
|
|
file_lines := strings.Split(file_content, "\n")
|
|
|
|
for index, value := range file_lines {
|
|
if is_heading(value) {
|
|
headings = append(
|
|
headings, heading{value, get_heading_level(value), (index + 1), nil})
|
|
}
|
|
}
|
|
|
|
get_parents(headings)
|
|
|
|
// print all children that do not have a parent
|
|
//print_children(nil, headings)
|
|
|
|
// print all children of the second header
|
|
print_children(&headings[1], headings)
|
|
|
|
fmt.Printf("%v\n", headings)
|
|
|
|
header_level_count := count_levels(headings)
|
|
|
|
for i := 0; i < 6; i++ {
|
|
if header_level_count[i] != 0 {
|
|
fmt.Printf("Header %d occurs %d times.\n", (i + 1), header_level_count[i])
|
|
}
|
|
}
|
|
}
|