/
pathFormatter.go
137 lines (95 loc) · 2.31 KB
/
pathFormatter.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package util
import (
"embed"
"errors"
"io/ioutil"
"os"
"path"
"sync"
)
//go:embed default_setting.json
//go:embed language
//go:embed default_maps
var f embed.FS
type PathFormatter interface {
GetPath(of ...string) string
}
type pathFormatter struct {
root string
}
var instance PathFormatter
var once sync.Once
func GetPathFormatter() PathFormatter {
once.Do(func() {
workingDir, ok := os.LookupEnv("HOME")
if !ok {
CheckErr(errors.New("HOME not exist"))
}
workingDir = path.Join(workingDir, "nonogram")
instance = newPathFormatter(workingDir)
_, err := os.ReadDir(workingDir)
if err != nil {
os.Mkdir(workingDir, 0755)
initialize()
}
})
return instance
}
func newPathFormatter(root string) PathFormatter {
p := new(pathFormatter)
p.root = root
return p
}
func initialize() {
os.Mkdir(instance.GetPath("maps"), 0755)
os.Mkdir(instance.GetPath("language"), 0755)
copyFile("default_setting.json", instance.GetPath("setting.json"))
copyDir("language", "language")
copyDir("default_maps", "maps")
}
func copyDir(from string, to string) {
files, _ := f.ReadDir(from)
for _, file := range files {
copyFile(from+string(os.PathSeparator)+file.Name(), instance.GetPath(to, file.Name()))
}
}
func copyFile(from string, to string) {
data, _ := f.ReadFile(from)
CheckErr(ioutil.WriteFile(to, data, 0644))
}
func (p *pathFormatter) GetPath(target ...string) string {
current := p.root
for _, element := range target {
current = path.Join(current, element)
}
return current
}
func (p *pathFormatter) moveFile(fileName, from, to string) {
f := path.Join(from, fileName)
t := path.Join(to, fileName)
CheckErr(os.Rename(f, t))
}
func (p *pathFormatter) MoveBase(to string) {
list := getAllFilesFrom(p.root)
for _, name := range list {
p.moveFile(name, p.root, to)
}
p.root = to
}
//getAllFilesFrom gets and returns absolute path.
func getAllFilesFrom(parentDirectory string) []string {
result := make([]string, 0)
files, _ := os.ReadDir(parentDirectory)
for _, file := range files {
if file.IsDir() {
inner := getAllFilesFrom(parentDirectory + file.Name())
for i := range inner {
inner[i] = path.Join(inner[i], file.Name())
}
result = append(result, inner...)
} else {
result = append(result, parentDirectory+file.Name())
}
}
return result
}