github.com/dnephin/dobi@v0.15.0/utils/fs/expanduser.go (about)

     1  package fs
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  )
     9  
    10  // ExpandUser expands the ~ in a path to the users home directory
    11  // TODO: find a lib, or move to a lib
    12  // TODO: os.user can't be used with cross compiling
    13  func ExpandUser(path string) (string, error) {
    14  	if !strings.HasPrefix(path, "~") {
    15  		return path, nil
    16  	}
    17  
    18  	parts := strings.Split(path, fmt.Sprintf("%c", filepath.Separator))
    19  	username := strings.TrimPrefix(parts[0], "~")
    20  	switch username {
    21  	case "":
    22  		parts[0] = os.Getenv("HOME")
    23  		return filepath.Join(parts...), nil
    24  	default:
    25  		return path, fmt.Errorf("expanding ~user/ paths are not supported yet")
    26  	}
    27  }