github.com/coreservice-io/utils@v0.3.0/path_util/path.go (about)

     1  package path_util
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  )
     7  
     8  // exists returns whether the given file or directory exists, when err exist not sure
     9  func AbsPathExist(path string) (bool, error) {
    10  	_, err := os.Stat(path)
    11  	if err == nil {
    12  		return true, nil
    13  	}
    14  	if os.IsNotExist(err) {
    15  		return false, nil
    16  	}
    17  	return false, err
    18  }
    19  
    20  // input a relative path or a absolute path
    21  // return (abs_path,exist,err)
    22  // if op-system file error then nothing meaningful
    23  func SmartPathExist(abs_or_rel_path string) (string, bool, error) {
    24  
    25  	//check abs path or relative path
    26  	is_abs := filepath.IsAbs(abs_or_rel_path)
    27  	if is_abs {
    28  		//check if abs path exist
    29  		abs_exist, err := AbsPathExist(abs_or_rel_path)
    30  		if err != nil {
    31  			return "", false, err
    32  		}
    33  		if abs_exist {
    34  			return abs_or_rel_path, true, nil
    35  		} else {
    36  			return abs_or_rel_path, false, nil
    37  		}
    38  	} else {
    39  
    40  		//rel to exe
    41  		exist, err := AbsPathExist(ExE_Path(abs_or_rel_path))
    42  		if err != nil {
    43  			return "", false, err
    44  		}
    45  		if exist {
    46  			return ExE_Path(abs_or_rel_path), true, nil
    47  		}
    48  
    49  		////////for debug mode direct run go run ./
    50  		/////////if user run from root as working directory
    51  		currDir, err := os.Getwd()
    52  		if err != nil {
    53  			return "", false, err
    54  		}
    55  
    56  		w_path := filepath.Join(currDir, abs_or_rel_path)
    57  		w_p_exist, err := AbsPathExist(w_path)
    58  		if err != nil {
    59  			return "", false, err
    60  		}
    61  		if w_p_exist {
    62  			return w_path, true, nil
    63  		}
    64  		//////////////////////////////////
    65  		return ExE_Path(abs_or_rel_path), false, nil
    66  	}
    67  }