示例#1
0
func TestPascalToSnake(t *testing.T) {
	for _, spec := range []struct {
		input, want string
	}{
		{input: "value", want: "Value"},
		{input: "prefixed_value", want: "PrefixedValue"},
		{input: "foo_id", want: "FooId"},
	} {
		got := internal.PascalFromSnake(spec.input)
		if got != spec.want {
			t.Errorf("internal.PascalFromSnake(%q) = %q; want %q", spec.input, got, spec.want)
		}
	}
}
示例#2
0
func populateFieldValueFromPath(msg proto.Message, fieldPath []string, values []string) error {
	m := reflect.ValueOf(msg)
	if m.Kind() != reflect.Ptr {
		return fmt.Errorf("unexpected type %T: %v", msg, msg)
	}
	m = m.Elem()
	for i, fieldName := range fieldPath {
		isLast := i == len(fieldPath)-1
		if !isLast && m.Kind() != reflect.Struct {
			return fmt.Errorf("non-aggregate type in the mid of path: %s", strings.Join(fieldPath, "."))
		}
		f := m.FieldByName(internal.PascalFromSnake(fieldName))
		if !f.IsValid() {
			glog.Warningf("field not found in %T: %s", msg, strings.Join(fieldPath, "."))
			return nil
		}

		switch f.Kind() {
		case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64:
			m = f
		case reflect.Slice:
			// TODO(yugui) Support []byte
			if !isLast {
				return fmt.Errorf("unexpected repeated field in %s", strings.Join(fieldPath, "."))
			}
			return populateRepeatedField(f, values)
		case reflect.Ptr:
			if f.IsNil() {
				m = reflect.New(f.Type().Elem())
				f.Set(m)
			}
			m = f.Elem()
			continue
		case reflect.Struct:
			m = f
			continue
		default:
			return fmt.Errorf("unexpected type %s in %T", f.Type(), msg)
		}
	}
	switch len(values) {
	case 0:
		return fmt.Errorf("no value of field: %s", strings.Join(fieldPath, "."))
	case 1:
	default:
		glog.Warningf("too many field values: %s", strings.Join(fieldPath, "."))
	}
	return populateField(m, values[0])
}
示例#3
0
// LHS returns a left-hand-side expression in go for this field.
func (c FieldPathComponent) LHS() string {
	if c.Target.Message.File.proto2() {
		return fmt.Sprintf("Get%s()", internal.PascalFromSnake(c.Name))
	}
	return internal.PascalFromSnake(c.Name)
}
示例#4
0
// RHS returns a right-hand-side expression in go for this field.
func (c FieldPathComponent) RHS() string {
	return internal.PascalFromSnake(c.Name)
}