-
Notifications
You must be signed in to change notification settings - Fork 2
/
folders.go
122 lines (108 loc) · 2.27 KB
/
folders.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
114
115
116
117
118
119
120
121
122
package folders
import (
"encoding/json"
"log"
"os"
"path"
"path/filepath"
"strings"
)
type File struct {
Name string
}
type Folder struct {
FileName string
Name string
Files []*File
Folders map[string]*Folder
}
func (f *Folder) String() string {
j, _ := json.Marshal(f)
return string(j)
}
// FindFoldersTree - возвращает дерево каталогов и файлов, начиная с директории dir
func FindFoldersTree(dir string, NeedFolders, NeedFiles, NeedDot bool, MassExclude []string) *Folder {
dir = path.Clean(dir)
var tree *Folder
var nodes = map[string]interface{}{}
var walkFun filepath.WalkFunc = func(p string, info os.FileInfo, err error) error {
if info == nil {
return nil
}
// проверка кроме MassExclude
if len(MassExclude) > 0 {
for _, v := range MassExclude {
if info.Name() == v {
return nil
}
if p == v {
return nil
}
}
}
if info.IsDir() {
nodes[p] = &Folder{p, path.Base(p), []*File{}, map[string]*Folder{}}
} else {
nodes[p] = &File{path.Base(p)}
}
return nil
}
err := filepath.Walk(dir, walkFun)
if err != nil {
log.Fatal(err)
}
for key, value := range nodes {
var parentFolder *Folder
if key == dir {
tree = value.(*Folder)
continue
} else {
var ok bool
parentFolder, ok = nodes[path.Dir(key)].(*Folder)
if !ok {
continue
}
}
// найдём название Папки/Файла
var Name string
//var FolderName string
switch value.(type) {
case *File:
Name = value.(*File).Name
case *Folder:
{
Name = value.(*Folder).Name
//FolderName = value.(*Folder).FileName
}
}
// проверка скрытые файлы с точкой
if NeedDot == false && strings.HasPrefix(Name, ".") {
continue
}
//// проверка кроме MassExclude
//if len(MassExclude) > 0 {
// for _, v := range MassExclude {
// if Name == v {
// continue
// }
// if FolderName == v {
// continue
// }
// }
//}
//
switch v := value.(type) {
case *File:
if NeedFiles == false {
break
}
parentFolder.Files = append(parentFolder.Files, v)
case *Folder:
if NeedFolders == false {
break
}
parentFolder.Folders[v.Name] = v
}
}
return tree
}