-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathconfig.go
84 lines (67 loc) · 1.8 KB
/
config.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
package main
import (
_ "embed"
"log"
"os"
"path/filepath"
"strings"
)
func isExists(dirPath string, confPath string) (dir bool, conf bool) {
_, dirErr := os.Stat(dirPath)
if dirErr != nil && !os.IsNotExist(dirErr) {
log.Fatalf("failed to access path %v", dirErr)
}
_, confErr := os.Stat(confPath)
if confErr != nil && !os.IsNotExist(confErr) {
log.Fatalf("failed to access config %v", confErr)
}
return !os.IsNotExist(dirErr), !os.IsNotExist(confErr)
}
//go:embed .lab
var configTemplate string
func Setup() (string, string, string) {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal("failed to get user home directory", err)
}
configDirectory := homeDir
var displayPath string
customLabPath := os.Getenv("LABPATH")
if customLabPath != "" {
customLabPath = strings.TrimSuffix(customLabPath, "/") + "/"
}
if customLabPath != "" {
if strings.HasPrefix(customLabPath, "~") {
customLabPath = strings.Replace(customLabPath, "~", homeDir, 1)
}
configDirectory = customLabPath
if strings.HasPrefix(customLabPath, homeDir) {
displayPath = "~" + customLabPath[len(homeDir):] + "lab/"
} else {
displayPath = customLabPath + "lab/"
}
} else {
displayPath = "~/lab/"
}
labDir := filepath.Join(configDirectory, "lab")
confFile := filepath.Join(labDir, ".lab")
hasDir, hasConf := isExists(labDir, confFile)
if !hasDir {
err := os.MkdirAll(labDir, 0o755)
if err != nil {
log.Fatalf("failed to create directory %v", err)
}
}
if !hasConf {
newConfigFile, err := os.Create(confFile)
if err != nil {
log.Fatalf("failed to create config file %v", err)
}
defer newConfigFile.Close()
_, err = newConfigFile.Write([]byte(configTemplate))
if err != nil {
log.Fatalf("failed to write to config file", err)
}
}
return labDir, confFile, displayPath
}