1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-25 15:29:32 -05:00
denoland-deno/os.go

103 lines
2.4 KiB
Go
Raw Normal View History

2018-05-19 05:53:29 -04:00
package main
import (
"github.com/golang/protobuf/proto"
"io/ioutil"
"os"
"strings"
)
const assetPrefix string = "/$asset$/"
2018-05-21 23:00:36 -04:00
func InitOS() {
2018-05-21 22:07:40 -04:00
Sub("os", func(buf []byte) []byte {
msg := &Msg{}
check(proto.Unmarshal(buf, msg))
switch msg.Payload.(type) {
case *Msg_Exit:
payload := msg.GetExit()
os.Exit(int(*payload.Code))
2018-05-21 22:07:40 -04:00
case *Msg_SourceCodeFetch:
payload := msg.GetSourceCodeFetch()
return HandleSourceCodeFetch(*payload.ModuleSpecifier, *payload.ContainingFile)
2018-05-21 22:07:40 -04:00
case *Msg_SourceCodeCache:
payload := msg.GetSourceCodeCache()
return HandleSourceCodeCache(*payload.Filename, *payload.SourceCode,
*payload.OutputCode)
2018-05-21 22:07:40 -04:00
default:
panic("[os] Unexpected message " + string(buf))
}
return nil
})
2018-05-19 05:53:29 -04:00
}
func HandleSourceCodeFetch(moduleSpecifier string, containingFile string) (out []byte) {
2018-05-19 05:56:02 -04:00
assert(moduleSpecifier != "", "moduleSpecifier shouldn't be empty")
2018-05-19 05:53:29 -04:00
res := &Msg{}
var sourceCodeBuf []byte
var err error
defer func() {
if err != nil {
var errStr = err.Error()
res.Error = &errStr
2018-05-19 05:53:29 -04:00
}
out, err = proto.Marshal(res)
check(err)
}()
moduleName, filename, err := ResolveModule(moduleSpecifier, containingFile)
if err != nil {
return
}
//println("HandleSourceCodeFetch", "moduleSpecifier", moduleSpecifier,
// "containingFile", containingFile, "filename", filename)
2018-05-19 05:56:02 -04:00
if isRemote(moduleName) {
2018-05-19 05:53:29 -04:00
sourceCodeBuf, err = FetchRemoteSource(moduleName, filename)
} else if strings.HasPrefix(moduleName, assetPrefix) {
f := strings.TrimPrefix(moduleName, assetPrefix)
sourceCodeBuf, err = Asset("dist/" + f)
} else {
2018-05-19 05:56:02 -04:00
assert(moduleName == filename,
2018-05-19 05:53:29 -04:00
"if a module isn't remote, it should have the same filename")
sourceCodeBuf, err = ioutil.ReadFile(moduleName)
}
if err != nil {
return
}
outputCode, err := LoadOutputCodeCache(filename, sourceCodeBuf)
if err != nil {
return
}
var sourceCode = string(sourceCodeBuf)
2018-05-19 05:53:29 -04:00
res.Payload = &Msg_SourceCodeFetchRes{
SourceCodeFetchRes: &SourceCodeFetchResMsg{
ModuleName: &moduleName,
Filename: &filename,
SourceCode: &sourceCode,
OutputCode: &outputCode,
2018-05-19 05:53:29 -04:00
},
}
return
}
func HandleSourceCodeCache(filename string, sourceCode string,
outputCode string) []byte {
fn := CacheFileName(filename, []byte(sourceCode))
outputCodeBuf := []byte(outputCode)
err := ioutil.WriteFile(fn, outputCodeBuf, 0600)
res := &Msg{}
if err != nil {
var errStr = err.Error()
res.Error = &errStr
2018-05-19 05:53:29 -04:00
}
out, err := proto.Marshal(res)
check(err)
return out
}