-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathutil.go
72 lines (60 loc) · 1.31 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
package gvm
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/andrewkroh/gvm/common"
)
func homeDir() (string, error) {
var homeDir string
if runtime.GOOS == "windows" {
homeDir = os.Getenv("USERPROFILE")
} else {
homeDir = os.Getenv("HOME")
}
if _, err := os.Stat(homeDir); err != nil {
return "", fmt.Errorf("failed to access home dir: %w", err)
}
return homeDir, nil
}
func extractTo(to, file string) (string, error) {
tmpDir := to + ".tmp"
if err := os.Mkdir(tmpDir, 0o755); err != nil {
return "", err
}
defer os.RemoveAll(tmpDir)
if err := common.Extract(file, tmpDir); err != nil {
return "", err
}
// Move into the final location.
if err := common.Rename(filepath.Join(tmpDir, "go"), to); err != nil {
return "", err
}
return to, nil
}
func existsDir(dir string) (bool, error) {
_, err := os.Stat(dir)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func writeJSONFile(filename string, value interface{}) error {
contents, err := json.Marshal(value)
if err != nil {
return err
}
return os.WriteFile(filename, contents, 0o644)
}
func readJSONFile(filename string, to interface{}) error {
contents, err := os.ReadFile(filename)
if err != nil {
return err
}
return json.Unmarshal(contents, to)
}