add tree doc

This commit is contained in:
Celogeek 2022-01-05 09:39:13 +01:00
parent 45bfc16e7c
commit 8040081cfe
Signed by: celogeek
GPG Key ID: E6B7BDCFC446233A

View File

@ -1,3 +1,21 @@
/*
Tree builder and viewer
This allow you to create a tree of files and display them as a tree or flat view.
Example
t := tree.New()
t.AddPath("a/b/c/d")
t.AddPath("a/b/e/f")
for v := range t.FlatView() {
fmt.Println(v)
}
for v := range t.TreeView() {
fmt.Println(v)
}
*/
package tree
import (
@ -13,6 +31,9 @@ type Tree interface {
TreeView() chan string
}
/*
Create a new tree
*/
func New() Tree {
return &node{
Name: ".",
@ -24,6 +45,20 @@ type node struct {
Nodes map[string]*node
}
/*
Add a node to your tree and return it
You can chain it:
t.Add("a").Add("b").Add("c").Add("d")
Or
c := t
for _, s := range strings.Split("a/b/c/d", "/") {
c = c.Add(s)
}
*/
func (t *node) Add(name string) Tree {
if t.Nodes == nil {
t.Nodes = map[string]*node{}
@ -35,6 +70,12 @@ func (t *node) Add(name string) Tree {
}
return n
}
/*
Add a path to your tree, separated with /
t.AddPath("a/b/c/d")
*/
func (t *node) AddPath(path string) Tree {
n := Tree(t)
for _, name := range strings.Split(path, "/") {
@ -43,6 +84,9 @@ func (t *node) AddPath(path string) Tree {
return n
}
/*
Return a sorted list of children
*/
func (t *node) Children() []*node {
childs := make([]*node, len(t.Nodes))
i := 0
@ -56,10 +100,20 @@ func (t *node) Children() []*node {
return childs
}
/*
Check if your node has a children
*/
func (t *node) HasChildren() bool {
return t.Nodes != nil
}
/*
Return a flat view of your tree
for v := range t.FlatView() {
fmt.Println(v)
}
*/
func (t *node) FlatView() (out chan string) {
out = make(chan string)
go func() {
@ -82,6 +136,13 @@ func (t *node) FlatView() (out chan string) {
return out
}
/*
Return a tree view of your tree
for v := range t.TreeView() {
fmt.Println(v)
}
*/
func (t *node) TreeView() (out chan string) {
out = make(chan string)
treeLinkChar := "│ "