This repository was archived by the owner on Feb 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
87 lines (68 loc) · 2 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
)
// AppName defines the default global application name
const AppName string = "net.hlte.daemon"
// LocalDataPath returns the appropriate path for general user-data storage on the given platform.
// If `checkEnvVar` is non-empty, it must contain the name of an environmental variable to source for the path prior to generating one.
func LocalDataPath(checkEnvVar string) (string, error) {
if len(checkEnvVar) > 0 {
envPath := os.Getenv(checkEnvVar)
if len(envPath) > 0 {
return envPath, nil
}
}
switch runtime.GOOS {
case "darwin":
return "Library/Application Support", nil
case "windows":
return "AppData", nil
case "linux":
return fmt.Sprintf(".%s", AppName), nil
}
return "", fmt.Errorf("Unsupported runtime platform '%v'", runtime.GOOS)
}
// InitLocalData will prepare the directory at `path` for use as a local user data store
func InitLocalData(path string) (string, error) {
if path == "" {
userHomeDir, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "user homedir lookup failed: %v\n", err)
return "", err
}
path = userHomeDir
}
absPath, err := filepath.Abs(fmt.Sprintf("%s/%s", path, AppName))
if err != nil {
fmt.Fprintf(os.Stderr, "initLocalData failed: %v\n", err)
return absPath, err
}
absPath = filepath.FromSlash(absPath)
err = os.MkdirAll(absPath, 0700)
if err != nil {
fmt.Fprintf(os.Stderr, "initLocalData MkdirAll failed: %v\n", err)
return absPath, err
}
return absPath, nil
}
// ParseJSON is a convenience function for parsing a JSON file at `path` into the object `intoObj`
func ParseJSON(path string, intoObj interface{}) error {
file, err := os.Open(path)
if err != nil {
fmt.Fprintf(os.Stderr, "parseJSON unable to open '%s': %v\n", path, err)
return err
}
defer file.Close()
dec := json.NewDecoder(file)
err = dec.Decode(intoObj)
if err != nil {
fmt.Fprintf(os.Stderr, "parseJSON failed to decode: %v\n", err)
return err
}
return nil
}