github.com/gogf/gf@v1.16.9/os/gfile/gfile_home.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 "github.com/gogf/gf/errors/gcode" 12 "github.com/gogf/gf/errors/gerror" 13 "os" 14 "os/exec" 15 "os/user" 16 "runtime" 17 "strings" 18 ) 19 20 // Home returns absolute path of current user's home directory. 21 // The optional parameter <names> specifies the its sub-folders/sub-files, 22 // which will be joined with current system separator and returned with the path. 23 func Home(names ...string) (string, error) { 24 path, err := getHomePath() 25 if err != nil { 26 return "", err 27 } 28 for _, name := range names { 29 path += Separator + name 30 } 31 return path, nil 32 } 33 34 // getHomePath returns absolute path of current user's home directory. 35 func getHomePath() (string, error) { 36 u, err := user.Current() 37 if nil == err { 38 return u.HomeDir, nil 39 } 40 if "windows" == runtime.GOOS { 41 return homeWindows() 42 } 43 return homeUnix() 44 } 45 46 // homeUnix retrieves and returns the home on unix system. 47 func homeUnix() (string, error) { 48 if home := os.Getenv("HOME"); home != "" { 49 return home, nil 50 } 51 var stdout bytes.Buffer 52 cmd := exec.Command("sh", "-c", "eval echo ~$USER") 53 cmd.Stdout = &stdout 54 if err := cmd.Run(); err != nil { 55 return "", err 56 } 57 58 result := strings.TrimSpace(stdout.String()) 59 if result == "" { 60 return "", gerror.NewCode(gcode.CodeInternalError, "blank output when reading home directory") 61 } 62 63 return result, nil 64 } 65 66 // homeWindows retrieves and returns the home on windows system. 67 func homeWindows() (string, error) { 68 var ( 69 drive = os.Getenv("HOMEDRIVE") 70 path = os.Getenv("HOMEPATH") 71 home = drive + path 72 ) 73 if drive == "" || path == "" { 74 home = os.Getenv("USERPROFILE") 75 } 76 if home == "" { 77 return "", gerror.NewCode(gcode.CodeOperationFailed, "HOMEDRIVE, HOMEPATH, and USERPROFILE are blank") 78 } 79 80 return home, nil 81 }