Skip to content

Instantly share code, notes, and snippets.

@docapotamus
Created July 2, 2016 16:33
Show Gist options
  • Save docapotamus/33b0254be9a8a8acfd8078e6a7a60344 to your computer and use it in GitHub Desktop.
Save docapotamus/33b0254be9a8a8acfd8078e6a7a60344 to your computer and use it in GitHub Desktop.
Directory tree generator
package main
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
)
// Form of a directory tree
type Node struct {
path string
children []Node
}
var (
pwd string
)
func walk(path string, node Node) (Node, error) {
f, err := os.Open(path)
if err != nil {
return node, nil
}
names, err := f.Readdirnames(-1)
f.Close()
if err != nil {
return node, nil
}
sort.Strings(names)
for _, name := range names {
filename := filepath.Join(path, name)
fileInfo, _ := os.Lstat(filename)
newNode := Node{
path: filename,
}
if fileInfo.IsDir() {
newNode, err = walk(filename, newNode)
}
node.children = append(node.children, newNode)
}
return node, nil
}
func PrintTree(indent int, node Node) {
fmt.Printf("%s\n", node.path)
for _, child := range node.children {
if len(child.children) > 0 {
PrintTree(indent+1, child)
} else {
fmt.Printf("%s%s\n", strings.Repeat("\t", indent), child.path)
}
}
}
func main() {
pwd = "/"
node, _ := walk(pwd, Node{
path: pwd,
})
PrintTree(0, node)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment