Browse Source

Merge pull request #89 from documatrix/export_to_time

Runtime.ExportTo() can now export date strings to time.Time targets
Dmitry Panov 6 years ago
parent
commit
1b2d25ba9a
2 changed files with 46 additions and 0 deletions
  1. 10 0
      runtime.go
  2. 36 0
      runtime_test.go

+ 10 - 0
runtime.go

@@ -9,6 +9,7 @@ import (
 	"math/rand"
 	"math/rand"
 	"reflect"
 	"reflect"
 	"strconv"
 	"strconv"
+	"time"
 
 
 	"golang.org/x/text/collate"
 	"golang.org/x/text/collate"
 
 
@@ -23,6 +24,7 @@ const (
 var (
 var (
 	typeCallable = reflect.TypeOf(Callable(nil))
 	typeCallable = reflect.TypeOf(Callable(nil))
 	typeValue    = reflect.TypeOf((*Value)(nil)).Elem()
 	typeValue    = reflect.TypeOf((*Value)(nil)).Elem()
+	typeTime     = reflect.TypeOf(time.Time{})
 )
 )
 
 
 type global struct {
 type global struct {
@@ -1245,6 +1247,14 @@ func (r *Runtime) toReflectValue(v Value, typ reflect.Type) (reflect.Value, erro
 		return reflect.ValueOf(v.Export()).Convert(typ), nil
 		return reflect.ValueOf(v.Export()).Convert(typ), nil
 	}
 	}
 
 
+	if typ == typeTime && et.Kind() == reflect.String {
+		time, ok := dateParse(v.String())
+		if !ok {
+			return reflect.Value{}, fmt.Errorf("Could not convert string %v to %v", v, typ)
+		}
+		return reflect.ValueOf(time), nil
+	}
+
 	switch typ.Kind() {
 	switch typ.Kind() {
 	case reflect.Slice:
 	case reflect.Slice:
 		if o, ok := v.(*Object); ok {
 		if o, ok := v.(*Object); ok {

+ 36 - 0
runtime_test.go

@@ -589,6 +589,42 @@ func TestRuntime_ExportToStructWithPtrValues(t *testing.T) {
 
 
 }
 }
 
 
+func TestRuntime_ExportToTime(t *testing.T) {
+	const SCRIPT = `
+	var dateStr = "2018-08-13T15:02:13+02:00";
+	var str = "test123";
+	`
+
+	vm := New()
+	_, err := vm.RunString(SCRIPT)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	var ti time.Time
+	err = vm.ExportTo(vm.Get("dateStr"), &ti)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if ti.Format(time.RFC3339) != "2018-08-13T15:02:13+02:00" {
+		t.Fatalf("Unexpected value: '%s'", ti.Format(time.RFC3339))
+	}
+
+	err = vm.ExportTo(vm.Get("str"), &ti)
+	if err == nil {
+		t.Fatal("Expected err to not be nil")
+	}
+
+	var str string
+	err = vm.ExportTo(vm.Get("dateStr"), &str)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if str != "2018-08-13T15:02:13+02:00" {
+		t.Fatalf("Unexpected value: '%s'", str)
+	}
+}
+
 func TestRuntime_ExportToFunc(t *testing.T) {
 func TestRuntime_ExportToFunc(t *testing.T) {
 	const SCRIPT = `
 	const SCRIPT = `
 	function f(param) {
 	function f(param) {