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