| 1 |
package config |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
"os" |
| 7 |
"os/user" |
| 8 |
"path/filepath" |
| 9 |
"runtime" |
| 10 |
"strings" |
| 11 |
"time" |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
var ( |
| 16 |
name = "Smallstep CLI" |
| 17 |
buildTime = "N/A" |
| 18 |
commit = "N/A" |
| 19 |
) |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
const StepPathEnv = "STEPPATH" |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
const HomeEnv = "HOME" |
| 28 |
|
| 29 |
|
| 30 |
var stepPath string |
| 31 |
|
| 32 |
|
| 33 |
var homePath string |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
func StepPath() string { |
| 39 |
return stepPath |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
func Home() string { |
| 45 |
return homePath |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
func StepAbs(path string) string { |
| 58 |
if filepath.IsAbs(path) { |
| 59 |
return path |
| 60 |
} |
| 61 |
|
| 62 |
slashed := filepath.ToSlash(path) |
| 63 |
switch { |
| 64 |
case strings.HasPrefix(slashed, "~/"): |
| 65 |
return filepath.Join(homePath, path[2:]) |
| 66 |
case strings.HasPrefix(slashed, "./"), strings.HasPrefix(slashed, "../"): |
| 67 |
if abs, err := filepath.Abs(path); err == nil { |
| 68 |
return abs |
| 69 |
} |
| 70 |
return path |
| 71 |
default: |
| 72 |
return filepath.Join(stepPath, path) |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
func init() { |
| 77 |
l := log.New(os.Stderr, "", 0) |
| 78 |
|
| 79 |
|
| 80 |
homePath = os.Getenv(HomeEnv) |
| 81 |
if homePath == "" { |
| 82 |
usr, err := user.Current() |
| 83 |
if err == nil && usr.HomeDir != "" { |
| 84 |
homePath = usr.HomeDir |
| 85 |
} else { |
| 86 |
l.Fatalf("Error obtaining home directory, please define environment variable %s.", HomeEnv) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
stepPath = os.Getenv(StepPathEnv) |
| 92 |
if stepPath == "" { |
| 93 |
stepPath = filepath.Join(homePath, ".step") |
| 94 |
} |
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
if fi, err := os.Stat(stepPath); err != nil { |
| 101 |
os.MkdirAll(stepPath, 0700) |
| 102 |
} else if !fi.IsDir() { |
| 103 |
l.Fatalf("File '%s' is not a directory.", stepPath) |
| 104 |
} |
| 105 |
|
| 106 |
homePath = filepath.Clean(homePath) |
| 107 |
stepPath = filepath.Clean(stepPath) |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
func Set(n, v, t string) { |
| 112 |
name = n |
| 113 |
buildTime = t |
| 114 |
commit = v |
| 115 |
} |
| 116 |
|
| 117 |
|
| 118 |
func Version() string { |
| 119 |
out := commit |
| 120 |
if commit == "N/A" { |
| 121 |
out = "0000000-dev" |
| 122 |
} |
| 123 |
|
| 124 |
return fmt.Sprintf("%s/%s (%s/%s)", |
| 125 |
name, out, runtime.GOOS, runtime.GOARCH) |
| 126 |
} |
| 127 |
|
| 128 |
|
| 129 |
func ReleaseDate() string { |
| 130 |
out := buildTime |
| 131 |
if buildTime == "N/A" { |
| 132 |
out = time.Now().UTC().Format("2006-01-02 15:04 MST") |
| 133 |
} |
| 134 |
|
| 135 |
return out |
| 136 |
} |