-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (77 loc) · 2.02 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
)
func readDirCustom(dirname string, printFiles bool) ([]os.FileInfo, error) {
var dirsOnly []os.FileInfo
files, err := ioutil.ReadDir(dirname)
if !printFiles {
for _, f := range files {
if f.IsDir() {
dirsOnly = append(dirsOnly, f)
}
}
return dirsOnly, err
}
return files, err
}
func printFile(out io.Writer, prefix string, name string, printFiles bool, size int64, isDir bool, isLast bool) {
var graphSymbols, sizeSymbols string
if isLast {
graphSymbols = "└───"
} else {
graphSymbols = "├───"
}
if size == 0 {
sizeSymbols = "(empty)"
} else {
sizeSymbols = "(" + strconv.FormatInt(size, 10) + "b)"
}
if isDir {
fmt.Fprintf(out, "%v%v%v\n", prefix, graphSymbols, name)
} else {
fmt.Fprintf(out, "%v%v%v "+sizeSymbols+"\n", prefix, graphSymbols, name)
}
}
func dirTreeRecur(out io.Writer, path string, printFiles bool, prefix string) error {
files, err := readDirCustom(path, printFiles)
for index, f := range files {
if index == len(files)-1 {
if f.IsDir() {
printFile(out, prefix, f.Name(), printFiles, 0, true, true)
dirTreeRecur(out, path+string(os.PathSeparator)+f.Name(), printFiles, prefix+" ")
} else {
printFile(out, prefix, f.Name(), printFiles, f.Size(), false, true)
}
} else {
if f.IsDir() {
printFile(out, prefix, f.Name(), printFiles, 0, true, false)
dirTreeRecur(out, path+string(os.PathSeparator)+f.Name(), printFiles, prefix+"│ ")
} else {
printFile(out, prefix, f.Name(), printFiles, f.Size(), false, false)
}
}
}
return err
}
func dirTree(out io.Writer, path string, printFiles bool) error {
//fmt.Println(path)
return dirTreeRecur(out, path, printFiles, "")
}
func main() {
out := os.Stdout
path := "."
if len(os.Args) == 2 || len(os.Args) == 3 {
//panic("usage go run main.go . [-f]")
path = os.Args[1]
}
printFiles := len(os.Args) == 3 && os.Args[2] == "-f"
err := dirTree(out, path, printFiles)
if err != nil {
panic(err.Error())
}
}