gfile_search.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. package gfile
  7. import (
  8. "bytes"
  9. "fmt"
  10. "github.com/gogf/gf/errors/gcode"
  11. "github.com/gogf/gf/errors/gerror"
  12. "github.com/gogf/gf/container/garray"
  13. )
  14. // Search searches file by name <name> in following paths with priority:
  15. // prioritySearchPaths, Pwd()、SelfDir()、MainPkgPath().
  16. // It returns the absolute file path of <name> if found, or en empty string if not found.
  17. func Search(name string, prioritySearchPaths ...string) (realPath string, err error) {
  18. // Check if it's a absolute path.
  19. realPath = RealPath(name)
  20. if realPath != "" {
  21. return
  22. }
  23. // Search paths array.
  24. array := garray.NewStrArray()
  25. array.Append(prioritySearchPaths...)
  26. array.Append(Pwd(), SelfDir())
  27. if path := MainPkgPath(); path != "" {
  28. array.Append(path)
  29. }
  30. // Remove repeated items.
  31. array.Unique()
  32. // Do the searching.
  33. array.RLockFunc(func(array []string) {
  34. path := ""
  35. for _, v := range array {
  36. path = RealPath(v + Separator + name)
  37. if path != "" {
  38. realPath = path
  39. break
  40. }
  41. }
  42. })
  43. // If it fails searching, it returns formatted error.
  44. if realPath == "" {
  45. buffer := bytes.NewBuffer(nil)
  46. buffer.WriteString(fmt.Sprintf("cannot find file/folder \"%s\" in following paths:", name))
  47. array.RLockFunc(func(array []string) {
  48. for k, v := range array {
  49. buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v))
  50. }
  51. })
  52. err = gerror.NewCode(gcode.CodeOperationFailed, buffer.String())
  53. }
  54. return
  55. }