iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌲

Representing Tree Structures in Go

に公開
2023/11/18

What is this?

I created a package that allows you to achieve output similar to the Linux tree command results using Go source code (this is a promotion for it).
Before publishing this article, I wrote another one titled "CLI/Web for outputting tree from Markdown format input". I am reusing the code used in the CLI introduced in that article.

Demo

I think it's quickest to just show you, so here is a sample below.

package main

import (
	"fmt"
	"os"

	"github.com/ddddddO/gtree"
)

func main() {
	var root *gtree.Node
	root = gtree.NewRoot("root")
	root.Add("child 1").Add("child 2")
	root.Add("child 1").Add("child 3")
	child4 := root.Add("child 4")

	var child7 *gtree.Node
	child7 = child4.Add("child 5").Add("child 6").Add("child 7")
	child7.Add("child 8")

	if err := gtree.OutputProgrammably(os.Stdout, root); err != nil {
		fmt.Println(err)
		return
	}
}

The execution result of the above is as follows.

root
├── child 1
│   ├── child 2
│   └── child 3
└── child 4
    └── child 5
        └── child 6
            └── child 7
                └── child 8

In this way, you can generate and output a group of nodes that make up a tree using Go code.

When can it be used?

...I haven't thought of any yet. However, I thought that depending on the user, various things could be represented in a tree structure.
For example, here is a program that outputs something like a Linux tree result when the results of the find command are passed to standard input and the Go code is executed.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/ddddddO/gtree"
)

// $ cd github.com/ddddddO/gtree
// $ find . -type d -name .git -prune -o -type f -print
// ./config.go
// ./node_generator_test.go
// ./example/like_cli/adapter/indentation.go
// ./example/like_cli/adapter/executor.go
// ./example/like_cli/main.go
// ./example/find_pipe_programmable-gtree/main.go
// ...
// $ find . -type d -name .git -prune -o -type f -print | go run example/find_pipe_programmable-gtree/main.go
func main() {
	var (
		root *gtree.Node
		node *gtree.Node
	)
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()              // e.g.) "./example/find_pipe_programmable-gtree/main.go"
		splited := strings.Split(line, "/") // e.g.) [. example find_pipe_programmable-gtree main.go]

		for i, s := range splited {
			if root == nil {
				root = gtree.NewRoot(s) // s := "."
				node = root
				continue
			}
			if i == 0 {
				continue
			}

			tmp := node.Add(s)
			node = tmp
		}
		node = root
	}

	if err := gtree.OutputProgrammably(os.Stdout, root); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	// Output:
	// .
	// ├── config.go
	// ├── node_generator_test.go
	// ├── example
	// │   ├── like_cli
	// │   │   ├── adapter
	// │   │   │   ├── indentation.go
	// │   │   │   └── executor.go
	// │   │   └── main.go
	// │   ├── find_pipe_programmable-gtree
	// │   │   └── main.go
	// │   ├── go-list_pipe_programmable-gtree
	// │   │   └── main.go
	// │   └── programmable
	// │       └── main.go
	// ├── file_considerer.go
	// ...
}

I thought that if you pipe arbitrary commands and have a Go program like the one above execute them, the possibilities would expand.

Addendum

The above involved defining a tree in code and outputting it with the gtree.OutputProgrammably function. If you want to modify the tree in some way (such as using an external library), the gtree.WalkProgrammably function might be useful. Here is some sample code:

package main

import (
	"fmt"
	"os"

	"github.com/ddddddO/gtree"
)

func main() {
	root := gtree.NewRoot("root")
	root.Add("child 1").Add("child 2").Add("child 3")
	root.Add("child 5")
	root.Add("child 1").Add("child 2").Add("child 4")

	callback := func(wn *gtree.WalkerNode) error {
		fmt.Println(wn.Row())
		return nil
	}

	if err := gtree.WalkProgrammably(root, callback); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	// Output:
	// root
	// ├── child 1
	// │   └── child 2
	// │       ├── child 3
	// │       └── child 4
	// └── child 5

	callback2 := func(wn *gtree.WalkerNode) error {
		fmt.Println("WalkerNode's methods called...")
		fmt.Printf("\tName     : %s\n", wn.Name())
		fmt.Printf("\tBranch   : %s\n", wn.Branch())
		fmt.Printf("\tRow      : %s\n", wn.Row())
		fmt.Printf("\tLevel    : %d\n", wn.Level())
		fmt.Printf("\tPath     : %s\n", wn.Path())
		fmt.Printf("\tHasChild : %t\n", wn.HasChild())
		return nil
	}

	if err := gtree.WalkProgrammably(root, callback2); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	// Output:
	// WalkerNode's methods called...
	//         Name     : root
	//         Branch   : 
	//         Row      : root
	//         Level    : 1
	//         Path     : root
	//         HasChild : true
	// WalkerNode's methods called...
	//         Name     : child 1
	//         Branch   : ├──
	//         Row      : ├── child 1
	//         Level    : 2
	//         Path     : root/child 1
	//         HasChild : true
	// WalkerNode's methods called...
	//         Name     : child 2
	//         Branch   : │   └──
	//         Row      : │   └── child 2
	//         Level    : 3
	//         Path     : root/child 1/child 2
	//         HasChild : true
	// WalkerNode's methods called...
	//         Name     : child 3
	//         Branch   : │       ├──
	//         Row      : │       ├── child 3
	//         Level    : 4
	//         Path     : root/child 1/child 2/child 3
	//         HasChild : false
	// WalkerNode's methods called...
	//         Name     : child 4
	//         Branch   : │       └──
	//         Row      : │       └── child 4
	//         Level    : 4
	//         Path     : root/child 1/child 2/child 4
	//         HasChild : false
	// WalkerNode's methods called...
	//         Name     : child 5
	//         Branch   : └──
	//         Row      : └── child 5
	//         Level    : 2
	//         Path     : root/child 5
	//         HasChild : false
}

In this way, this is a mechanism that allows the user to execute their own defined functions for each node making up the tree. It recursively traverses each child node starting from the Root node (the node created with the gtree.NewRoot function) and processes them using the defined function.

As a test, let's try modifying the program introduced in the "When can it be used?" section.

package main

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/ddddddO/gtree"
)

// Example:
// $ cd github.com/ddddddO/gtree
// $ find . -type d -name .git -prune -o -type f -print
// ./config.go
// ./node_generator_test.go
// ./example/like_cli/adapter/indentation.go
// ./example/like_cli/adapter/executor.go
// ./example/like_cli/main.go
// ./example/find_pipe_programmable-gtree/main.go
// ...
// $ find . -type d -name .git -prune -o -type f -print | go run example/find_pipe_programmable-gtree/main.go
// << See "Output:" below. >>
func main() {
	var (
		root *gtree.Node
		node *gtree.Node
	)
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()              // e.g.) "./example/find_pipe_programmable-gtree/main.go"
		splited := strings.Split(line, "/") // e.g.) [. example find_pipe_programmable-gtree main.go]

		for i, s := range splited {
			if root == nil {
				root = gtree.NewRoot(s) // s := "."
				node = root
				continue
			}
			if i == 0 {
				continue
			}

			tmp := node.Add(s)
			node = tmp
		}
		node = root
	}

	base, err := os.Getwd()
	if err != nil {
		os.Exit(1)		
	}
	callback := func(wn *gtree.WalkerNode) error {
		path := filepath.Join(base, wn.Path())
		file, err := os.Open(path)
		if err != nil {
			return err
		}
		defer file.Close()

		finfo, err := file.Stat()
		if err != nil {
			return err
		}

		fmt.Printf("[%07d] : %-70s : %s\n", finfo.Size(), wn.Row(), wn.Path())
		return nil
	}

	if err := gtree.WalkProgrammably(root, callback); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	// Output:
	// [0004096] : .                                                                      : .
	// [0002664] : ├── config.go                                                          : config.go
	// [0005133] : ├── node_generator_test.go                                             : node_generator_test.go
	// [0004096] : ├── example                                                            : example
	// [0001687] : │   ├── README.md                                                      : example/README.md
	// [0004096] : │   ├── noexist                                                        : example/noexist
	// [0000000] : │   │   └── xxx                                                        : example/noexist/xxx
	// [0004096] : │   ├── like_cli                                                       : example/like_cli
	// [0004096] : │   │   ├── adapter                                                    : example/like_cli/adapter
	// [0000770] : │   │   │   ├── indentation.go                                         : example/like_cli/adapter/indentation.go
	// [0000080] : │   │   │   └── executor.go                                            : example/like_cli/adapter/executor.go
	// [0003652] : │   │   └── main.go                                                    : example/like_cli/main.go
	// [0004096] : │   ├── find_pipe_programmable-gtree                                   : example/find_pipe_programmable-gtree
	// [0000796] : │   │   ├── README.md                                                  : example/find_pipe_programmable-gtree/README.md
	// [0124908] : │   │   ├── main.go                                                    : example/find_pipe_programmable-gtree/main.go
	// [0000420] : │   │   ├── go.mod                                                     : example/find_pipe_programmable-gtree/go.mod
	// [0003039] : │   │   └── go.sum                                                     : example/find_pipe_programmable-gtree/go.sum
	// [0004096] : │   ├── go-list_pipe_programmable-gtree                                : example/go-list_pipe_programmable-gtree
	// [0000618] : │   │   ├── README.md                                                  : example/go-list_pipe_programmable-gtree/README.md
	// [0003840] : │   │   ├── main.go                                                    : example/go-list_pipe_programmable-gtree/main.go
	// [0000423] : │   │   ├── go.mod                                                     : example/go-list_pipe_programmable-gtree/go.mod
	// [0003039] : │   │   └── go.sum                                                     : example/go-list_pipe_programmable-gtree/go.sum
	// [0004096] : │   └── programmable                                                   : example/programmable
	// [0014286] : │       └── main.go                                                    : example/programmable/main.go
	// [0000424] : ├── file_considerer.go                                                 : file_considerer.go
	// [0001972] : ├── node.go                                                            : node.go
	// [0002891] : ├── simple_tree_grower.go                                              : simple_tree_grower.go
	// [0000977] : ├── node_generator.go                                                  : node_generator.go
	// ...

The execution result is hard to read, so here is a screenshot.

  • Size of each file
  • Tree display
  • Path of each file

I made it output the above information.
You can use node information because it can be retrieved from the methods of the WalkerNode struct.

Others

Installation

Go 1.18 or higher is required.

go get github.com/ddddddO/gtree

Repository

https://github.com/ddddddO/gtree

Documentation

https://pkg.go.dev/github.com/ddddddO/gtree

Thoughts

At one point, the code I was writing started to become so complex that I almost gave up. However, after taking a little break and thinking it over, I managed to come up with a simple implementation, which reminded me that taking time to clear your head is important.
Also, by repeatedly performing small refactorings (making variable and method names more descriptive, splitting files by role, etc.), even though I initially started creating it as a CLI, providing it as a package went quite smoothly. Refactoring is important.
In addition, I learned things like how to create GoDoc and that Go requires editing go.mod from v2 onwards.

Update Information

  • 2022/08/17 Wasm support added and hosted on GitHub Pages🎉
  • 2022/01/15 Added a function to create directories and files🎉
  • 2021/11/20 Added support for JSON/YAML/TOML output🎉
  • Added a library-exclusive feature that allows users to define their own branch formats🎉
    • A sample is available here🙇

Discussion