feat: add fromJSON support (#352)

This commit is contained in:
Owen 2020-09-02 04:55:29 +08:00 committed by GitHub
parent b6f1df4d2f
commit d521fa5bba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 0 deletions

View File

@ -132,6 +132,7 @@ func (rc *RunContext) newVM() *otto.Otto {
vmFormat,
vmJoin,
vmToJSON,
vmFromJSON,
vmAlways,
rc.vmCancelled(),
rc.vmSuccess(),
@ -219,6 +220,20 @@ func vmToJSON(vm *otto.Otto) {
_ = vm.Set("toJson", toJSON)
}
func vmFromJSON(vm *otto.Otto) {
fromJSON := func(str string) map[string]interface{} {
var dat map[string]interface{}
err := json.Unmarshal([]byte(str), &dat)
if err != nil {
logrus.Errorf("Unable to unmarshal: %v", err)
return dat
}
return dat
}
_ = vm.Set("fromJSON", fromJSON)
_ = vm.Set("fromJson", fromJSON)
}
func (rc *RunContext) vmHashFiles() func(*otto.Otto) {
return func(vm *otto.Otto) {
_ = vm.Set("hashFiles", func(path string) string {

View File

@ -80,6 +80,8 @@ func TestEvaluate(t *testing.T) {
{"join('hello','mona')", "hello mona", ""},
{"toJSON({'foo':'bar'})", "{\n \"foo\": \"bar\"\n}", ""},
{"toJson({'foo':'bar'})", "{\n \"foo\": \"bar\"\n}", ""},
{"(fromJSON('{\"foo\":\"bar\"}')).foo", "bar", ""},
{"(fromJson('{\"foo\":\"bar\"}')).foo", "bar", ""},
{"hashFiles('**/package-lock.json')", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", ""},
{"success()", "true", ""},
{"failure()", "false", ""},