Exemplo n.º 1
0
func reflectValue(f *reflect.StructField, v reflect.Value) *Ident {
	ident := new(Ident)

	// Evaluate primitive types.
	switch f.Type.Kind() {
	case reflect.String:
		ident.Name = v.String()

	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		ident.Name = fmt.Sprint(v.Int())

	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		ident.Name = fmt.Sprint(v.Uint())

	case reflect.Float32, reflect.Float64:
		ident.Name = fmt.Sprint(v.Float())

	case reflect.Bool:
		ident.Name = fmt.Sprint(v.Bool())

	case reflect.Complex64, reflect.Complex128:
		ident.Name = fmt.Sprint(v.Complex())

	case reflect.Struct:
		// Check for interface and custom types.
		switch x := v.Interface().(type) {
		case Identifier:
			ident = x.Ident()

		case time.Time:
			ident.Name = chrono.Format(x)

		case fmt.Stringer:
			ident.Name = x.String()
		}

	case reflect.Interface, reflect.Ptr:
		if v.IsNil() {
			return nil
		}

		// Check for interface and custom types.
		switch x := v.Interface().(type) {
		case Identifier:
			ident = x.Ident()

		case time.Time:
			ident.Name = chrono.Format(x)

		case fmt.Stringer:
			ident.Name = x.String()
		}

	default:
		logrus.Debugf("origins: skipping unsupported field %s (%s type)", f.Name, f.Type.Kind())
		return nil
	}

	return ident
}
Exemplo n.º 2
0
func TestReflect(t *testing.T) {
	now := time.Now()

	f := File{
		Name:     "test.csv",
		Size:     13432,
		Modified: now,
		Owner:    "joe",
		Perm:     0755,
		other:    true,
	}

	facts, err := Reflect(f)

	if err != nil {
		t.Fatal(err)
	}

	// Perm and other are ommitted.
	assert.Equal(t, 4, len(facts))

	// Inspect the facts.
	assert.Equal(t, "13432", facts[1].Value.Name)
	assert.Equal(t, chrono.Format(now), facts[2].Value.Name)
	assert.Equal(t, "owner", facts[3].Attribute.Name)
	assert.Equal(t, "users", facts[3].Value.Domain)
	assert.Equal(t, "joe", facts[3].Value.Name)
}