forked from elsaland/quickjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
103 lines (88 loc) · 2.11 KB
/
utils.go
File metadata and controls
103 lines (88 loc) · 2.11 KB
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
package quickjs
/*
#cgo CFLAGS: -D_GNU_SOURCE
#cgo CFLAGS: -DCONFIG_BIGNUM
#cgo CFLAGS: -fno-asynchronous-unwind-tables
#cgo LDFLAGS: -lm -lpthread
#include "bridge.h"
*/
import "C"
import (
MD5 "crypto/md5"
"encoding/hex"
"fmt"
"github.com/imroc/req"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"reflect"
"unicode"
)
var keyMapStructure = "mapstructure"
func isExportedName(name string) bool {
if len(name) > 0 {
firstChar := name[0]
return unicode.IsLetter(rune(firstChar)) && unicode.IsUpper(rune(firstChar))
}
return false
}
func getFieldName(field reflect.StructField) string {
tag := field.Tag.Get(keyMapStructure)
if len(tag) > 0 {
return tag
}
return field.Name
}
func GetRefCount(ctx *C.JSContext, value C.JSValue) int64 {
rt := int64(C.GetValueRefCount(ctx, value))
return rt
}
// GoJSObject shortcut
type GoJSObject map[string]interface{}
// GoJSArray shortcut
type GoJSArray []interface{}
func md5(value string) string {
h := MD5.New()
io.WriteString(h, value)
return hex.EncodeToString(h.Sum(nil))
}
// loadTypeScriptSource with local fs cache
func loadTypeScriptSource(version string) (code string, err error) {
var content []byte
// jsDelivr is a really awesome CDN
url := fmt.Sprintf("https://cdn.jsdelivr.net/npm/typescript@%v/lib/typescript.min.js", version)
cacheLocation := filepath.Join(os.TempDir(), fmt.Sprintf("typescript-%v.ts", version))
stat, err := os.Stat(cacheLocation)
if err == nil {
if stat.IsDir() {
err = fmt.Errorf("'%v' is a directory, please remove it firstly", cacheLocation)
return
}
// read from local fs cache
content, err = ioutil.ReadFile(cacheLocation)
if err != nil {
return code, err
}
} else if os.IsNotExist(err) {
// get source from remote
res, err := req.Get(url)
if err != nil {
return code, err
}
resp := res.Response()
if resp.StatusCode != http.StatusOK {
return code, fmt.Errorf(resp.Status)
}
content, err = ioutil.ReadAll(resp.Body)
if err != nil {
return code, err
}
// write back to local cache
ioutil.WriteFile(cacheLocation, content, 0644)
} else {
return
}
return string(content), nil
}