Skip to content

Instantly share code, notes, and snippets.

@wiredprairie wiredprairie/tree.go
Created Nov 18, 2016

Embed
What would you like to do?
Code for small app that outputs a tree to the console of a directory path
package main
/*
The MIT License (MIT)
Copyright (c) 2016 WiredPrairie.us
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
"runtime"
"github.com/fatih/color"
)
// ascending file sorter
type bySizeAsc []os.FileInfo
func (f bySizeAsc) Len() int { return len(f) }
func (f bySizeAsc) Less(i, j int) bool { return f[i].Size() < f[j].Size() }
func (f bySizeAsc) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
// descending file sorter
type bySizeDesc []os.FileInfo
func (f bySizeDesc) Len() int { return len(f) }
func (f bySizeDesc) Less(i, j int) bool { return f[i].Size() >= f[j].Size() }
func (f bySizeDesc) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
// general stuff used everywhere
var (
folderColor = color.New(color.BgGreen).Add(color.FgBlack)
fileColor = color.New(color.BgBlack).Add(color.FgGreen)
flagNoColor = flag.Bool("no-color", false, "Disable color output")
flagSortBySizeDesc = flag.Bool("size-desc", false, "Sort files by size Descending")
flagSortBySizeAsc = flag.Bool("size-asc", false, "Sort files by size Ascending")
)
func main() {
flag.Parse() // check for flags
if *flagNoColor {
color.NoColor = true // just disable colors
}
argsWithoutProg := os.Args[1:]
var startDir = "."
if len(argsWithoutProg) > 0 {
startDir = argsWithoutProg[len(argsWithoutProg)-1]
// remove an extra directory separator character that might be there
if strings.HasSuffix(startDir, "\\") || strings.HasSuffix(startDir, "/") {
startDir = startDir[:len(startDir)-1]
}
}
// workaround an issue where folders with > 250 characters cause
// issues with the Go libraries only on Windows
if runtime.GOOS == "windows" {
startDir = "\\\\?\\" + startDir
}
walkSub(startDir, 0)
}
func walkSub(dir string, indent int) {
files, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
indentation := strings.Repeat("│   ", indent)
_, clippedDir := filepath.Split(dir)
if len(files) > 0 { // are we done?
fmt.Print(indentation + "├── ")
} else {
fmt.Print(indentation + "└── ")
}
folderColor.Print(clippedDir)
fmt.Println()
if len(files) == 0 {
return
}
switch {
case *flagSortBySizeDesc:
sort.Sort(bySizeDesc(files))
case *flagSortBySizeAsc:
sort.Sort(bySizeAsc(files))
}
// directories first
for _, file := range files {
if file.IsDir() {
subdir := filepath.Join(dir, file.Name())
walkSub(subdir, indent+1)
}
}
// then files
lastFileIndex := len(files) - 1
for i, file := range files {
filename := file.Name()
//fileInfo, err := os.Lstat(filename)
if !file.IsDir() && filename != "." {
if i == lastFileIndex {
fmt.Print(indentation + "└── ")
} else {
fmt.Print(indentation + "├── ")
}
fileColor.Print(file.Name())
fmt.Println()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.