-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
143 lines (122 loc) · 2.32 KB
/
utils.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
138
139
140
141
142
143
package main
import (
"archive/zip"
"crypto/sha1"
"encoding/hex"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
)
func generateResourcePack(resourcePath string) string {
_ = os.RemoveAll("./cache")
_ = os.Mkdir("./cache", 0755)
file, err := os.Create("./cache/temporary.zip")
if err != nil {
log.Println(err)
}
w := zip.NewWriter(file)
walker := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if strings.HasPrefix(info.Name(), ".") || strings.Contains(info.Name(), "~") {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer func(file *os.File) {
_ = file.Close()
}(file)
f, err := w.Create(strings.Replace(path, filepath.Clean(resourcePath)+"/", "", 1))
if err != nil {
return err
}
_, err = io.Copy(f, file)
if err != nil {
return err
}
return nil
}
err = filepath.Walk(resourcePath, walker)
if err != nil {
log.Fatal(err)
}
fileName := file.Name()
_ = w.Close()
_ = file.Close()
file, err = os.Open(fileName)
if err != nil {
log.Fatal(err)
}
h := sha1.New()
_, err = io.Copy(h, file)
if err != nil {
log.Fatal(err)
}
_ = file.Close()
fileHash := hex.EncodeToString(h.Sum(nil))
fileDir := path.Dir(file.Name())
newFileName := path.Join(fileDir, fileHash+".zip")
err = os.Rename(fileName, newFileName)
if err != nil {
log.Fatal(err)
}
return fileHash
}
func watch(watchPath string, onChange func()) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer func(watcher *fsnotify.Watcher) {
err := watcher.Close()
if err != nil {
log.Fatal()
}
}(watcher)
walker := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return nil
}
err = watcher.Add(path)
if err != nil {
log.Fatal(err)
}
return nil
}
err = filepath.Walk(watchPath, walker)
if err != nil {
panic(err)
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if strings.Contains(event.Name, "~") || strings.HasPrefix(event.Name, ".") || event.Has(fsnotify.Chmod) {
continue
}
onChange()
case err, ok := <-watcher.Errors:
if !ok {
return
}
if err != nil {
log.Fatal(err)
}
}
}
}