From 21606057757acdd49efc9fead5980d71b28d9917 Mon Sep 17 00:00:00 2001 From: Johannes Rothe Date: Tue, 6 Sep 2022 22:13:42 +0200 Subject: [PATCH] Write pagetree as html --- .gitignore | 1 + main.go | 62 +++++++++++++++++++++++++++++++++++++----------------- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/.gitignore b/.gitignore index adf8f72..0ede670 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ # Go workspace file go.work +*.html diff --git a/main.go b/main.go index fb3bb7d..08e60ce 100644 --- a/main.go +++ b/main.go @@ -3,38 +3,56 @@ package main import ( "encoding/base64" "encoding/json" + "fmt" "io" "log" "net/http" - "strings" + "os" + "text/template" "github.com/alexflint/go-arg" ) type NodeData struct { - id string - title string + Id string + Title string } type Node struct { - children []*Node - data NodeData + Children []*Node + Data NodeData } -func (n Node) printChildren(level int) { - log.Printf("%v%v", strings.Repeat("\t", level), n.data.title) - // leaf note - if len(n.children) == 0 { - return +func (n Node) writeHTML(w io.Writer) { + tmpl, err := template.New("root").Parse(` + {{ define "tree" }} + {{ if gt (len .Children) 0 }} + + {{ end }} + {{ end }} + + {{ template "tree" . }} + + `) + if err != nil { + fmt.Println("ERROR creating template") } - for _, child := range n.children { - child.printChildren(level + 1) + err = tmpl.Execute(w, n) + if err != nil { + fmt.Printf("ERROR executing template: %v", err) } } func (n *Node) getChildWithID(id string) (node *Node, hasChild bool) { - for _, c := range n.children { - if c.data.id == id { + for _, c := range n.Children { + if c.Data.Id == id { return c, true } } @@ -43,7 +61,7 @@ func (n *Node) getChildWithID(id string) (node *Node, hasChild bool) { } func (n *Node) addChild(child *Node) { - n.children = append(n.children, child) + n.Children = append(n.Children, child) } type spaceResult struct { @@ -147,7 +165,7 @@ func getSpaceChildren(url, user, token string) spaceResult { func createPageTree(s *spaceResult) { var parent *Node - root := Node{data: NodeData{title: "root"}} + root := Node{Data: NodeData{Title: "root"}} for _, page := range s.Results { parent = &root // ignore the root node @@ -165,15 +183,21 @@ func createPageTree(s *spaceResult) { parent = node continue } - n := Node{data: NodeData{id: ancestor.ID, title: ancestor.Title}} + n := Node{Data: NodeData{Id: ancestor.ID, Title: ancestor.Title}} parent.addChild(&n) parent = &n } // create leaf node - n := Node{data: NodeData{id: page.ID, title: page.Title}} + n := Node{Data: NodeData{Id: page.ID, Title: page.Title}} parent.addChild(&n) } - root.printChildren(0) + fname := "tree.html" + f, err := os.Create(fname) + if err != nil { + log.Fatalf("Failed to open %v", fname) + } + defer f.Close() + root.writeHTML(f) } func main() {