tweego/user.go
2020-02-24 14:28:13 -06:00

43 lines
1.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
Copyright © 20142020 Thomas Michael Edwards. All rights reserved.
Use of this source code is governed by a Simplified BSD License which
can be found in the LICENSE file.
*/
package main
import (
"errors"
"os"
"os/user"
"runtime"
)
func userHomeDir() (string, error) {
// Prefer the user's `HOME` environment variable.
if homeDir := os.Getenv("HOME"); homeDir != "" {
return homeDir, nil
}
// Elsewise, use the user's `.HomeDir` info.
if curUser, err := user.Current(); err == nil && curUser.HomeDir != "" {
return curUser.HomeDir, nil
}
// Failovers for Windows, though they should be unnecessary in Go ≥v1.7.
if runtime.GOOS == "windows" {
// Prefer the user's `USERPROFILE` environment variable.
if homeDir := os.Getenv("USERPROFILE"); homeDir != "" {
return homeDir, nil
}
// Elsewise, use the user's `HOMEDRIVE` and `HOMEPATH` environment variables.
homeDrive := os.Getenv("HOMEDRIVE")
homePath := os.Getenv("HOMEPATH")
if homeDrive != "" && homePath != "" {
return homeDrive + homePath, nil
}
}
return "", errors.New("Cannot find user home directory.")
}