This repository has been archived on 2025-01-17. You can view files and clone it, but cannot push or open issues or pull requests.
mdtoc/main.go

74 lines
1.1 KiB
Go
Raw Normal View History

2024-04-29 09:30:05 +02:00
package main
// TODO: read a file line by line
import (
"fmt"
"log"
"os"
"path"
2024-04-29 09:30:05 +02:00
"strings"
)
2024-04-30 10:50:58 +02:00
type heading struct {
2024-05-06 01:34:25 +02:00
text string
level int
line int
2024-04-30 10:50:58 +02:00
}
2024-04-29 09:30:05 +02:00
func is_heading(line string) bool {
if strings.HasPrefix(line, "#") {
return true
} else {
return false
}
}
func Get_heading_level(heading_text string) int {
2024-04-29 09:30:05 +02:00
level := 0
2024-04-30 10:50:58 +02:00
for i := 0; heading_text[i] == '#'; i++ {
2024-04-29 09:30:05 +02:00
level += 1
if i == (len(heading_text) - 1) {
break
}
2024-04-29 09:30:05 +02:00
}
return level
}
2024-05-05 08:17:49 +02:00
func parse_file(file_name string) []heading {
var headings []heading
2024-04-29 09:30:05 +02:00
file_content_raw, err := os.ReadFile(file_name)
2024-04-29 09:30:05 +02:00
if err != nil {
log.Fatal(err)
}
2024-05-05 08:17:49 +02:00
file_lines := strings.Split(string(file_content_raw), "\n")
2024-04-29 09:30:05 +02:00
is_codeblock := false
2024-04-30 10:59:47 +02:00
for index, value := range file_lines {
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)})
2024-04-29 09:30:05 +02:00
}
}
2024-05-05 08:17:49 +02:00
return headings
}
2024-04-29 09:30:05 +02:00
2024-05-05 08:17:49 +02:00
func main() {
file_name := os.Args[1]
2024-05-05 08:17:49 +02:00
var headings []heading = nil
2024-05-01 15:42:23 +02:00
2024-05-05 08:17:49 +02:00
headings = parse_file(file_name)
fmt.Println(path.Base(file_name))
2024-05-06 01:09:44 +02:00
tree(-1, "", headings)
2024-04-29 09:30:05 +02:00
}