Skip to content

Commit

Permalink
cmd: add cross-platform GetHomePath() (#552)
Browse files Browse the repository at this point in the history
  • Loading branch information
yaoharry authored and bobheadxi committed Feb 12, 2019
1 parent 31dc8e0 commit 9fb4c29
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
36 changes: 36 additions & 0 deletions local/env.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,42 @@
package local

import (
"errors"
"os"
"runtime"
)

const (
// EnvSSHPassphrase is the key used to fetch PEM key passphrases
EnvSSHPassphrase = "PEM_PASSPHRASE"
)

// GetHomePath returns the homepath based on the operating system used
func GetHomePath() (string, error) {
if runtime.GOOS == "windows" {
// Performs check for HOME env variable first
if home := os.Getenv("HOME"); home != "" {
return home, nil
}

// Performs check for USERPROFILE as backup
if home := os.Getenv("USERPROFILE"); home != "" {
return home, nil
}

// Builds HOME from HOMEDRIVE and HOMEPATH as default
var drive = os.Getenv("HOMEDRIVE")
var path = os.Getenv("HOMEPATH")
var home = drive + path
if drive == "" || path == "" {
return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE environment variables are blank")
}

return home, nil
}
// Unix system as default
if home := os.Getenv("HOME"); home != "" {
return home, nil
}
return "", errors.New("HOME environment variable is blank")
}
14 changes: 14 additions & 0 deletions local/env_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package local

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestGetHomePath(t *testing.T) {
env, err := GetHomePath()
assert.NoError(t, err)
assert.NotEqual(t, env, "")
assert.DirExists(t, env)
}

0 comments on commit 9fb4c29

Please sign in to comment.