package main // TODO: read a file line by line import ( "fmt" "log" "os" "path" "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 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 print_children_recursive(heading *heading, headings []heading) { for index, _ := range headings { if headings[index].parent == heading { fmt.Printf("Child of parent %p: %s (%p)\n", heading, headings[index].text, &headings[index]) print_children_recursive(&headings[index], headings) } } } func parse_file(file_name string) []heading { file_content_raw, err := os.ReadFile(file_name) var headings []heading if err != nil { log.Fatal(err) } file_lines := strings.Split(string(file_content_raw), "\n") for index, value := range file_lines { if is_heading(value) { headings = append( headings, heading{value, get_heading_level(value), (index + 1), nil}) } } return headings } func main() { file_name := os.Args[1] var headings []heading = nil headings = parse_file(file_name) get_parents(headings) print_children_recursive(nil, headings) fmt.Printf("%v\n", headings) fmt.Println(path.Base(file_name)) tree(-1, "", headings) }