-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
80 lines (70 loc) · 1.49 KB
/
file.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
package file
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"sort"
)
var cacheData = map[string]any{}
// 获取文件内的所有变量名
func GetFileVariateNameAll(FilePath string) (names []string) {
cache, ok := cacheData["GetFileVariateNameAll"]
mapData := map[string][]string{}
if ok {
if mapData1, ok := cache.(map[string][]string); ok {
mapData = mapData1
if names, ok := mapData[FilePath]; ok {
return names
}
}
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, FilePath, nil, 0)
if err != nil {
fmt.Printf("err = %s", err)
}
for s, object := range f.Scope.Objects {
if object.Kind == ast.Var {
names = append(names, s)
}
}
mapData[FilePath] = names
cacheData["GetFileVariateNameAll"] = mapData
return
}
type byModTime []*os.FileInfo
func (fis byModTime) Len() int {
return len(fis)
}
func (fis byModTime) Swap(i, j int) {
fis[i], fis[j] = fis[j], fis[i]
}
func (fis byModTime) Less(i, j int) bool {
return (*fis[i]).ModTime().Before((*fis[j]).ModTime())
}
// 指定目录下的文件按时间大小排序,从远到近
func SortFile(path string) ([]*os.FileInfo, error) {
dirEntrys, err := os.ReadDir(path)
if err != nil {
return nil, err
}
var files byModTime
files = make(byModTime, len(dirEntrys))
j := 0
for _, dirEntry := range dirEntrys {
if dirEntry.IsDir() {
continue
}
info, err := dirEntry.Info()
if err != nil {
continue
}
files[j] = &info
j++
}
files = files[:j]
sort.Sort(files)
return files, nil
}