gfile_search.go 1.6 KB

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