decred.org/dcrdex@v1.0.5/dex/path.go (about)

     1  // This code is available on the terms of the project LICENSE.md file,
     2  // also available online at https://blueoakcouncil.org/license/1.0.0.
     3  
     4  package dex
     5  
     6  import (
     7  	"os"
     8  	"os/user"
     9  	"path/filepath"
    10  	"runtime"
    11  	"strings"
    12  )
    13  
    14  // CleanAndExpandPath expands environment variables and leading ~ in the
    15  // passed path, cleans the result, and returns it.
    16  func CleanAndExpandPath(path string) string {
    17  	// Nothing to do when no path is given.
    18  	if path == "" {
    19  		return path
    20  	}
    21  
    22  	// NOTE: The os.ExpandEnv doesn't work with Windows cmd.exe-style
    23  	// %VARIABLE%, but the variables can still be expanded via POSIX-style
    24  	// $VARIABLE.
    25  	path = os.ExpandEnv(path)
    26  
    27  	if !strings.HasPrefix(path, "~") {
    28  		return filepath.Clean(path)
    29  	}
    30  
    31  	// Expand initial ~ to the current user's home directory, or ~otheruser
    32  	// to otheruser's home directory.  On Windows, both forward and backward
    33  	// slashes can be used.
    34  	path = path[1:]
    35  
    36  	var pathSeparators string
    37  	if runtime.GOOS == "windows" {
    38  		pathSeparators = string(os.PathSeparator) + "/"
    39  	} else {
    40  		pathSeparators = string(os.PathSeparator)
    41  	}
    42  
    43  	userName := ""
    44  	if i := strings.IndexAny(path, pathSeparators); i != -1 {
    45  		userName = path[:i]
    46  		path = path[i:]
    47  	}
    48  
    49  	homeDir := ""
    50  	var u *user.User
    51  	var err error
    52  	if userName == "" {
    53  		u, err = user.Current()
    54  	} else {
    55  		u, err = user.Lookup(userName)
    56  	}
    57  	if err == nil {
    58  		homeDir = u.HomeDir
    59  	}
    60  	// Fallback to CWD if user lookup fails or user has no home directory.
    61  	if homeDir == "" {
    62  		homeDir = "."
    63  	}
    64  
    65  	return filepath.Join(homeDir, path)
    66  }
    67  
    68  // FilesExists reports whether the named file or directory exists.
    69  func FileExists(name string) bool {
    70  	_, err := os.Stat(name)
    71  	return !os.IsNotExist(err)
    72  }