-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
113 lines (94 loc) · 2.45 KB
/
tree.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
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
package list
import (
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/Frank-Mayer/list/internal/utils"
"github.com/pkg/errors"
)
const (
osPathSep = string(os.PathSeparator)
)
func Tree(p string, options *Options) error {
abs, err := filepath.Abs(p)
if err != nil {
return errors.Wrap(err, "could not get absolute path for tree of path "+p)
}
rootLength := len(strings.Split(abs, osPathSep))
err = walk(p, options.Hidden, func(path string, info os.FileInfo, err error) error {
if err != nil {
return errors.Wrap(err, "to level walk function passed error")
}
hidden, err := utils.IsHiddenFile(path)
if err != nil {
return errors.Wrap(err, "could not check if file is hidden for tree at path "+path)
}
if !options.Hidden && hidden {
return nil
}
length := len(strings.Split(path, osPathSep)) - rootLength
print(repeat(segment, length))
err = printStyled(path)
if err != nil {
return errors.Wrap(err, "could not print colored path for tree at path "+path)
}
println()
return nil
})
if err != nil {
return errors.Wrap(err, "could not walk path for tree at path "+p)
}
return nil
}
func repeat(s string, n int) string {
var sb strings.Builder
for i := 0; i < n; i++ {
sb.WriteString(s)
}
return sb.String()
}
func walk(root string, all bool, fn filepath.WalkFunc) error {
q := utils.NewStack[string]()
absRoot, err := filepath.Abs(root)
if err != nil {
return errors.Wrap(err, "could not get absolute path for walk of path "+root)
}
q.Push(absRoot)
for qEntry := q.Pop(); qEntry != nil; qEntry = q.Pop() {
fi, err := os.Lstat(*qEntry)
if err != nil {
return errors.Wrap(err, "could not get file info in walk for path "+*qEntry)
}
if !all {
hidden, err := utils.IsHiddenFile(*qEntry)
if err != nil {
return errors.Wrap(err, "could not check if file is hidden for walk at path "+*qEntry)
}
if hidden {
continue
}
}
if fi.IsDir() {
entries, err := os.ReadDir(*qEntry)
if err != nil {
// if permission denied, continue
if os.IsPermission(err) {
continue
}
return errors.Wrap(err, "could not read directory "+*qEntry)
}
var dirEntry fs.DirEntry
for i := len(entries) - 1; i >= 0; i-- {
dirEntry = entries[i]
path := filepath.Join(*qEntry, dirEntry.Name())
q.Push(path)
}
}
err = fn(*qEntry, fi, nil)
if err != nil {
return errors.Wrap(err, "could not execute walk file tree function for path "+*qEntry)
}
}
return nil
}