forked from syumai/workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
109 lines (101 loc) · 2.16 KB
/
main.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
package main
import (
"bytes"
"embed"
"flag"
"fmt"
"io"
"os"
"path"
)
//go:embed assets
var assets embed.FS
const (
assetDirPath = "assets"
commonDirPath = "assets/common"
defaultBuildDirPath = "build"
)
func main() {
var mode string
var buildDirPath string
flag.StringVar(&mode, "mode", string(ModeTinygo), `build mode: tinygo or go`)
flag.StringVar(&buildDirPath, "o", defaultBuildDirPath, `output dir path: defaults to "build"`)
flag.Parse()
if !Mode(mode).IsValid() {
flag.PrintDefaults()
os.Exit(1)
return
}
if err := runMain(Mode(mode), buildDirPath); err != nil {
fmt.Fprintf(os.Stderr, "err: %v", err)
os.Exit(1)
}
}
func runMain(mode Mode, buildDirPath string) error {
if err := os.RemoveAll(buildDirPath); err != nil {
return err
}
if err := os.MkdirAll(buildDirPath, os.ModePerm); err != nil {
return err
}
if err := copyWasmExecJS(mode, buildDirPath); err != nil {
return err
}
if err := copyCommonAssets(buildDirPath); err != nil {
return err
}
return nil
}
func copyWasmExecJS(mode Mode, buildDirPath string) error {
var fileName string
switch mode {
case ModeTinygo:
fileName = "wasm_exec_tinygo.js"
case ModeGo:
fileName = "wasm_exec_go.js"
default:
return fmt.Errorf("unexpected mode: %s", mode)
}
destPath := path.Join(buildDirPath, "wasm_exec.js")
originPath := path.Join(assetDirPath, fileName)
if err := copyFile(destPath, originPath); err != nil {
return err
}
return nil
}
func copyCommonAssets(buildDirPath string) error {
entries, err := assets.ReadDir(commonDirPath)
if err != nil {
return err
}
for _, entry := range entries {
destPath := path.Join(buildDirPath, entry.Name())
originPath := path.Join(commonDirPath, entry.Name())
if err := copyFile(destPath, originPath); err != nil {
return err
}
}
return nil
}
func copyFile(destPath, originPath string) error {
f, err := assets.ReadFile(originPath)
if err != nil {
return err
}
if err != nil {
return err
}
dest, err := os.Create(destPath)
if err != nil {
return err
}
defer dest.Close()
_, err = io.Copy(dest, bytes.NewReader(f))
if err != nil {
return err
}
if err != nil {
return err
}
return nil
}