-
Notifications
You must be signed in to change notification settings - Fork 0
/
embed.go
99 lines (83 loc) · 1.93 KB
/
embed.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
//go:build go1.18
// +build go1.18
package starter
import (
"embed"
"io/fs"
"os"
"path/filepath"
"strings"
)
//go:embed extensions/* all:extensions/**/_*
var extensions embed.FS
const (
ExtEntry = "extensions" // Entry directory of extensions
fileMode = 0o755
)
type Extension struct {
// A directory where extensions can be saved for future use in Chrome.
// If no directory is specified, it defaults to a temporary directory.
Base string
}
func entries() ([]fs.DirEntry, error) {
return extensions.ReadDir(ExtEntry)
}
func (e *Extension) Store() error {
entries, err := entries()
if err != nil {
return err
}
dest := e.basedir()
for _, entry := range entries {
if info, _ := entry.Info(); info.IsDir() {
err = fs.WalkDir(extensions, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
base := strings.TrimPrefix(filepath.Dir(path), ExtEntry)
destDir := filepath.Join(dest, base)
if err := os.MkdirAll(destDir, fileMode); err != nil {
return err
}
if !d.IsDir() {
buf, err := fs.ReadFile(extensions, path)
if err != nil {
return err
}
destName := filepath.Join(destDir, filepath.Base(path))
_ = os.WriteFile(destName, buf, fileMode)
}
return nil
})
}
}
return err
}
func (e *Extension) lists() (ls []string) {
entries, err := entries()
if err != nil {
return
}
base := e.basedir()
for _, entry := range entries {
if info, _ := entry.Info(); info.IsDir() {
dir := filepath.Join(base, entry.Name())
ls = append(ls, dir)
}
}
return
}
func (e *Extension) basedir() string {
e.Base, _ = filepath.Abs(e.Base)
fi, err := os.Lstat(e.Base)
if err == nil && fi.IsDir() {
return e.Base
}
if err != nil && os.IsNotExist(err) {
// If dir not exist, try to create it.
if err := os.MkdirAll(e.Base, fileMode); err != nil {
e.Base, _ = os.MkdirTemp(os.TempDir(), "starter-")
}
}
return e.Base
}