-
Notifications
You must be signed in to change notification settings - Fork 13
/
copyembed.go
95 lines (74 loc) · 1.4 KB
/
copyembed.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
package util
import (
"embed"
"errors"
"io"
"io/fs"
"log"
"os"
"path/filepath"
)
func CopyFileFromEmbed(src embed.FS, srcPath string, dstPath string) (err error) {
srcFile, err := src.Open(srcPath)
if err != nil {
return
}
defer srcFile.Close()
_, err = os.Stat(dstPath)
if err == nil || !errors.Is(err, fs.ErrNotExist) {
log.Printf("Destination file %s already exists, skipping", dstPath)
return
}
err = os.MkdirAll(filepath.Dir(dstPath), 0755)
if err != nil {
return
}
dstFile, err := os.Create(dstPath)
if err != nil {
return
}
defer func() {
if e := dstFile.Close(); e != nil {
err = e
}
}()
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return
}
err = dstFile.Sync()
if err != nil {
return
}
return
}
func CopyDirFromEmbed(src embed.FS, srcPath string, dstPath string) (err error) {
entries, err := fs.ReadDir(src, srcPath)
if err != nil {
return
}
err = os.MkdirAll(dstPath, 0755)
if err != nil {
return
}
for _, entry := range entries {
srcPath := filepath.Join(srcPath, entry.Name())
dstPath := filepath.Join(dstPath, entry.Name())
if entry.IsDir() {
err = CopyDirFromEmbed(src, srcPath, dstPath)
if err != nil {
return
}
} else {
// Skip symlinks.
if entry.Type()&fs.ModeSymlink != 0 {
continue
}
err = CopyFileFromEmbed(src, srcPath, dstPath)
if err != nil {
return
}
}
}
return
}