summaryrefslogtreecommitdiff
path: root/main.go
blob: 6e38d5f95b09cd93d9f16418294d205091e1e65d (plain)
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
package main

import (
	"github.com/golang/protobuf/proto"
	"github.com/ry/v8worker2"
	"io/ioutil"
	"os"
)

func ReadFileSync(filename string) []byte {
	buf, err := ioutil.ReadFile(filename)
	msg := &Msg{Kind: Msg_DATA_RESPONSE}
	if err != nil {
		msg.Error = err.Error()
	} else {
		msg.Data = buf
	}
	out, err := proto.Marshal(msg)
	if err != nil {
		panic(err)
	}
	return out
}

func recv(buf []byte) []byte {
	msg := &Msg{}
	err := proto.Unmarshal(buf, msg)
	if err != nil {
		panic(err)
	}
	switch msg.Kind {
	case Msg_READ_FILE_SYNC:
		return ReadFileSync(msg.Path)
	case Msg_EXIT:
		os.Exit(int(msg.Code))
	default:
		panic("Unexpected message")
	}

	return nil
}

func loadAsset(w *v8worker2.Worker, path string) {
	data, err := Asset(path)
	if err != nil {
		panic("asset not found")
	}
	err = w.Load(path, string(data))
	if err != nil {
		panic(err)
	}
}

func main() {
	worker := v8worker2.New(recv)
	loadAsset(worker, "dist/main.js")
	cwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	out, err := proto.Marshal(&Msg{
		Kind: Msg_START,
		Cwd:  cwd,
		Argv: os.Args,
	})
	if err != nil {
		panic(err)
	}
	err = worker.SendBytes(out)
	if err != nil {
		os.Stderr.WriteString(err.Error())
		os.Exit(1)
	}
}