-
Notifications
You must be signed in to change notification settings - Fork 138
/
static.go
102 lines (86 loc) · 2.42 KB
/
static.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
package main
import (
"embed"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/sirupsen/logrus"
)
//go:embed static
var static embed.FS
func extract(efs embed.FS, dirEntries []fs.DirEntry, origin, target string) error {
for _, dirEntry := range dirEntries {
info, err := dirEntry.Info()
if err != nil {
return err
}
perm := info.Mode().Perm()
if dirEntry.IsDir() {
logrus.Debugf("[static] extract -> %s %s", filepath.Join(target, dirEntry.Name()), perm.String())
err := os.MkdirAll(filepath.Join(target, dirEntry.Name()), perm)
if err != nil {
return err
}
entries, err := efs.ReadDir(filepath.Join(origin, dirEntry.Name()))
if err != nil {
return err
}
err = extract(efs, entries, filepath.Join(origin, dirEntry.Name()), filepath.Join(target, dirEntry.Name()))
if err != nil {
return err
}
} else {
sf, err := static.Open(filepath.Join(origin, dirEntry.Name()))
if err != nil {
return err
}
defer func() { _ = sf.Close() }()
logrus.Debugf("[static] extract -> %s %s", filepath.Join(target, dirEntry.Name()), perm.String())
df, err := os.OpenFile(filepath.Join(target, dirEntry.Name()), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, perm)
if err != nil {
return err
}
defer func() { _ = df.Close() }()
_, err = io.Copy(df, sf)
if err != nil {
return err
}
}
}
return nil
}
func ExtractFiles() {
logrus.Info("[static] creating storage dir...")
info, err := os.Stat(conf.ClashHome)
if err == nil {
if !info.IsDir() {
logrus.Fatalf("[static] clash home path is not a dir")
}
if !conf.ForceExtract {
logrus.Infof("[static] storage dir %s already exist, skip extract...", conf.ClashHome)
return
}
} else {
if os.IsNotExist(err) {
if err = os.MkdirAll(conf.ClashHome, 0755); err != nil {
logrus.Fatalf("[static] failed to create storage dir: %v", err)
}
} else {
logrus.Fatalf("[static] failed to read storage dir: %v", err)
}
}
logrus.Info("[static] copy static files...")
dirEntries, err := static.ReadDir("static")
if err != nil {
logrus.Fatalf("[static] failed to read embed dir: %v", err)
}
err = extract(static, dirEntries, "static", conf.ClashHome)
if err != nil {
logrus.Fatalf("[static] failed to extract embed files: %v", err)
}
err = os.Chmod(filepath.Join(conf.ClashHome, InternalClashBinName), 0755)
if err != nil {
logrus.Fatalf("[static] failed to update internal clash bin mode: %v", err)
}
}