/
gfile_search.go
58 lines (54 loc) · 1.55 KB
/
gfile_search.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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/bjxujiang/gf.
package gfile
import (
"bytes"
"errors"
"fmt"
"github.com/bjxujiang/gf/container/garray"
)
// Search searches file by name <name> in following paths with priority:
// prioritySearchPaths, Pwd()、SelfDir()、MainPkgPath().
// It returns the absolute file path of <name> if found, or en empty string if not found.
func Search(name string, prioritySearchPaths ...string) (realPath string, err error) {
// Check if it's a absolute path.
realPath = RealPath(name)
if realPath != "" {
return
}
// Search paths array.
array := garray.NewStrArray()
array.Append(prioritySearchPaths...)
array.Append(Pwd(), SelfDir())
if path := MainPkgPath(); path != "" {
array.Append(path)
}
// Remove repeated items.
array.Unique()
// Do the searching.
array.RLockFunc(func(array []string) {
path := ""
for _, v := range array {
path = RealPath(v + Separator + name)
if path != "" {
realPath = path
break
}
}
})
// If it fails searching, it returns formatted error.
if realPath == "" {
buffer := bytes.NewBuffer(nil)
buffer.WriteString(fmt.Sprintf("cannot find file/folder \"%s\" in following paths:", name))
array.RLockFunc(func(array []string) {
for k, v := range array {
buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v))
}
})
err = errors.New(buffer.String())
}
return
}