Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
125 lines (106 loc) · 2.23 KB
/
Copy pathmain.go
File metadata and controls
125 lines (106 loc) · 2.23 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"bytes"
"fmt"
"io"
"os"
"sort"
)
func main() {
out := os.Stdout
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())
}
}
func DirTree(out io.Writer, path string, files bool) error {
err := GetDirsTree(out, path, files, "")
if err != nil {
return err
}
return nil
}
func GetDirsTree(out io.Writer, path string, files bool, nesting string) error {
file, err := os.Open(path)
if err != nil {
return err
}
dirs, err := file.ReadDir(0)
sort.Slice(dirs, func(i, j int) bool {
return dirs[i].Name() < dirs[j].Name()
})
var count int
if files {
count = len(dirs)
} else {
count = 0
for _, item := range dirs {
if item.IsDir() {
count++
}
}
}
for i := 0; i < len(dirs); i++ {
item := dirs[i]
if item.IsDir() {
count--
err := showInfo(out, item, count, nesting, true)
if err != nil {
return err
}
newPath := fmt.Sprintf("%s%s%s", path, string(os.PathSeparator), item.Name())
if count == 0 {
err = GetDirsTree(out, newPath, files, nesting+"0")
} else {
err = GetDirsTree(out, newPath, files, nesting+"1")
}
if err != nil {
return err
}
} else if files {
count--
err := showInfo(out, item, count, nesting, false)
if err != nil {
return err
}
}
}
return nil
}
func showInfo(out io.Writer, item os.DirEntry, count int, nesting string, isDir bool) error {
buffer := bytes.Buffer{}
for _, item := range nesting {
if string(item) == "1" {
buffer.WriteString("│\t")
} else {
buffer.WriteString("\t")
}
}
if count == 0 {
buffer.WriteString("└───")
} else if count != 0 {
buffer.WriteString("├───")
}
if isDir {
fmt.Fprint(out, buffer.String(), item.Name(), "\n")
} else {
fileInfo, err := item.Info()
if err != nil {
return err
}
var size string
if fileInfo.Size() == 0 {
size = " (empty)"
} else {
size = fmt.Sprintf(" (%db)", fileInfo.Size())
//size = "(" + strconv.Itoa(int(fileInfo.Size())) + "b" + ")"
}
fmt.Fprint(out, buffer.String(), item.Name(), size, "\n")
}
return nil
}