github.com/gogf/gf/v2@v2.7.4/os/gfile/gfile_search.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gfile 8 9 import ( 10 "bytes" 11 "fmt" 12 13 "github.com/gogf/gf/v2/container/garray" 14 "github.com/gogf/gf/v2/errors/gerror" 15 ) 16 17 // Search searches file by name `name` in following paths with priority: 18 // prioritySearchPaths, Pwd()、SelfDir()、MainPkgPath(). 19 // It returns the absolute file path of `name` if found, or en empty string if not found. 20 func Search(name string, prioritySearchPaths ...string) (realPath string, err error) { 21 // Check if it's an absolute path. 22 realPath = RealPath(name) 23 if realPath != "" { 24 return 25 } 26 // Search paths array. 27 array := garray.NewStrArray() 28 array.Append(prioritySearchPaths...) 29 array.Append(Pwd(), SelfDir()) 30 if path := MainPkgPath(); path != "" { 31 array.Append(path) 32 } 33 // Remove repeated items. 34 array.Unique() 35 // Do the searching. 36 array.RLockFunc(func(array []string) { 37 path := "" 38 for _, v := range array { 39 path = RealPath(v + Separator + name) 40 if path != "" { 41 realPath = path 42 break 43 } 44 } 45 }) 46 // If it fails searching, it returns formatted error. 47 if realPath == "" { 48 buffer := bytes.NewBuffer(nil) 49 buffer.WriteString(fmt.Sprintf(`cannot find "%s" in following paths:`, name)) 50 array.RLockFunc(func(array []string) { 51 for k, v := range array { 52 buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v)) 53 } 54 }) 55 err = gerror.New(buffer.String()) 56 } 57 return 58 }