github.com/zhongdalu/gf@v1.0.0/g/os/gfile/gfile_search.go (about)

     1  // Copyright 2017-2018 gf Author(https://github.com/zhongdalu/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/zhongdalu/gf.
     6  
     7  package gfile
     8  
     9  import (
    10  	"bytes"
    11  	"errors"
    12  	"fmt"
    13  	"github.com/zhongdalu/gf/g/container/garray"
    14  )
    15  
    16  // Search searches file by name <name> in following paths with priority:
    17  // prioritySearchPaths, Pwd()、SelfDir()、MainPkgPath().
    18  // It returns the absolute file path of <name> if found, or en empty string if not found.
    19  func Search(name string, prioritySearchPaths ...string) (realPath string, err error) {
    20  	// Check if it's a absolute path.
    21  	realPath = RealPath(name)
    22  	if realPath != "" {
    23  		return
    24  	}
    25  	// TODO move search paths to internal package variable.
    26  	// Search paths array.
    27  	array := garray.NewStringArray(true)
    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 file/folder \"%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 = errors.New(buffer.String())
    56  	}
    57  	return
    58  }