Skip to content

Instantly share code, notes, and snippets.

@zacharysyoung
Last active January 26, 2023 21:51
Show Gist options
  • Save zacharysyoung/64b6593f7d0314d0eb29bbc9ef121f1e to your computer and use it in GitHub Desktop.
Save zacharysyoung/64b6593f7d0314d0eb29bbc9ef121f1e to your computer and use it in GitHub Desktop.
Print directory/file tree.
package main
// Print directory tree from first arg.
//
// https://gist.github.com/zacharysyoung/64b6593f7d0314d0eb29bbc9ef121f1e
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
)
// Starting depth of "root"; subtract from any depth to root tree at column 0.
var rootDepth = -1
func getDepth(path string) (depth int) {
for path != "." {
depth++
path = filepath.Dir(path)
}
return
}
const (
padStr = " "
dirPrefix = "- "
filePrefix = " "
)
var (
dir, file string // path components for every traversed file object
depth int // how deep in the tree any file object is
pad string // repeat padStr by depth times
prefix string // dir or file prefix
)
func walkfunc(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
dir, file = filepath.Split(path)
depth = getDepth(dir) - rootDepth
// fmt.Printf("% 2d dir: % -20q file: % -20q isDir: %5t\n", depth, dir, file, info.IsDir())
pad = strings.Repeat(padStr, depth)
prefix = filePrefix
if info.IsDir() {
prefix = dirPrefix
}
fmt.Printf("%s%s%s\n", pad, prefix, file)
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("usage: %s PATH\n", os.Args[0])
fmt.Println("exit 1")
os.Exit(1)
}
root := os.Args[1]
// fmt.Printf("Printing tree for %q\n", root)
root = filepath.Clean(root)
rootDepth = getDepth(root)
if err := filepath.Walk(root, walkfunc); err != nil {
log.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment