Example #1
0
File: csvb.go Project: relops/csvb
func (r *Row) Bind(x interface{}, strategy map[string]string) error {

	for src, dest := range strategy {

		data, ok := r.data[src]

		if ok {
			k, err := reflections.GetFieldKind(x, dest)
			if err != nil {
				return err
			}

			switch k {
			case reflect.String:
				{
					reflections.SetField(x, dest, data)
				}
			case reflect.Int64:
				{
					i, err := strconv.ParseInt(data, 10, 64)
					if err != nil {
						return err
					}
					reflections.SetField(x, dest, i)
				}
			case reflect.Ptr:
				{
					value, err := reflections.GetField(x, dest)
					if err != nil {
						return err
					}
					if reflect.TypeOf(value) == typeDec {
						dec, success := new(inf.Dec).SetString(data)
						if !success {
							fmt.Errorf("Could not parse inf.Dec: %s", data)
						}
						reflections.SetField(x, dest, dec)
					}
				}
			case reflect.Struct:
				{
					value, err := reflections.GetField(x, dest)
					if err != nil {
						return err
					}
					if reflect.TypeOf(value) == typeTime {
						date, err := time.ParseInLocation("2006-01-02 15:04:05", data, r.opts.TimeZone)
						if err != nil {
							return err
						}
						reflections.SetField(x, dest, date)
					}
				}
			}
		}
	}

	return nil
}
Example #2
0
func AssertObjectKeysEqual(t *testing.T, a, b interface{}, keys ...string) {
	assert.True(t, len(keys) > 0, "No keys provided.")
	for _, k := range keys {
		c, err := reflections.GetField(a, k)
		assert.Nil(t, err)
		d, err := reflections.GetField(b, k)
		assert.Nil(t, err)
		assert.Equal(t, c, d, "%s", k)
	}
}
Example #3
0
func (this *CCMomentHandler) LoadModel(moment models.CCMoment) models.Moment {
	fields, _ := reflections.Fields(&models.Moment{})
	//new instance
	momentModel := models.Moment{}

	for i := 0; i < len(fields); i++ {
		has, _ := reflections.HasField(moment, fields[i])
		if has == true {
			fmt.Println("Field Exist------", fields[i])
			if fields[i] == "Volunteer_id" {
				fmt.Println("Volunteer_id Exist------")
				var userObj CCUserHandler
				var volunteerObj CCVolunteerHandler
				var usermodel models.CCUser
				var volunteerModel models.CCVolunteer
				value, err := reflections.GetField(moment, fields[i])

				if err == nil && value != nil {
					str, _ := value.(string)

					volunteerModel, err = volunteerObj.FetchVolunteerForId(str)
					if err == nil {
						fmt.Println("volunteer Exist------", volunteerModel)
						usermodel, err = userObj.FetchUserById(volunteerModel.User_id)
						fmt.Println("User Exist------", usermodel)
						if err == nil {
							responseModel := userObj.LoadModel(usermodel)
							setError := reflections.SetField(&momentModel, fields[i], responseModel) // err != nil
							if setError != nil {
								panic(setError)
							}
						}
					}

				}
			} else {
				value, err := reflections.GetField(moment, fields[i])
				if err == nil {
					fmt.Println("Field Value------", value)
					setError := reflections.SetField(&momentModel, fields[i], value) // err != nil

					if setError != nil {
						panic(setError)
					}

				}
			}

		}

	}
	fmt.Println("Data set to Model --- ", momentModel)
	return momentModel
}
Example #4
0
// GetNextPage provided a collection of resources (Builds or Jobs),
// will update the ListOptions to fetch the next resource page on next call.
func (into *ListOptions) GetNextPage(from interface{}) error {
	if reflect.TypeOf(from).Kind() != reflect.Slice {
		return fmt.Errorf("provided interface{} does not represent a slice")
	}

	slice := reflect.ValueOf(from)
	if slice.Len() == 0 {
		return fmt.Errorf("provided interface{} is a zero sized slice")
	}

	lastElem := slice.Index(slice.Len() - 1).Interface()
	has, _ := reflections.HasField(lastElem, "Number")
	if !has {
		return fmt.Errorf("last element of the provided slice does not have a Number attribute")
	}

	value, err := reflections.GetField(lastElem, "Number")
	if err != nil {
		return err
	}

	// We rely on travis sending us numbers representations here
	// so no real need to check for errors
	number, _ := strconv.ParseUint(value.(string), 10, 64)
	into.AfterNumber = uint(math.Max(float64(number), 0))

	return nil
}
Example #5
0
func (l Loader) validateField(fieldName string, label string, validationRules string) error {
	// Split up the validation rules
	rules := strings.Split(validationRules, ",")

	// Loop through each rule, and perform it
	for _, rule := range rules {
		if rule == "required" {
			if l.fieldValueIsEmpty(fieldName) {
				return l.Errorf("Missing %s.", label)
			}
		} else if rule == "file-exists" {
			value, _ := reflections.GetField(l.Config, fieldName)

			// Make sure the value is converted to a string
			if valueAsString, ok := value.(string); ok {
				// Return an error if the path doesn't exist
				if _, err := os.Stat(valueAsString); err != nil {
					return fmt.Errorf("Could not find %s located at %s", label, value)
				}
			}
		} else {
			return fmt.Errorf("Unknown config validation rule `%s`", rule)
		}
	}

	return nil
}
Example #6
0
func (this *CCUserHandler) LoadModel(user models.CCUser) models.User {
	fields, _ := reflections.Fields(&models.User{})
	//new instance
	userModel := models.User{}

	for i := 0; i < len(fields); i++ {
		has, _ := reflections.HasField(user, fields[i])
		if has == true {
			fmt.Println("Field Exist------", fields[i])

			value, err := reflections.GetField(user, fields[i])
			if err == nil {
				fmt.Println("Field Value------", value)
				setError := reflections.SetField(&userModel, fields[i], value) // err != nil

				if setError != nil {
					panic(setError)
				}

			}

		}

	}
	fmt.Println("Data set to Model --- ", userModel)
	return userModel
}
Example #7
0
func (bot TgBot) sendGenericQuery(path string, ignore string, file string, payload interface{}) ResultWithMessage {
	url := bot.buildPath(path)
	switch val := payload.(type) {
	//WebHook
	case SetWebhookQuery:
		return bot.genericSendPostData(url, val)
	case SetWebhookCertQuery:
		return bot.sendConvertingFile(url, ignore, file, val)
	// ID
	case SendPhotoIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendAudioIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendVoiceIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendDocumentIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendStickerIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendVideoIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
		// Path
	case SendPhotoPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendAudioPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendVoicePathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendDocumentPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendStickerPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendVideoPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	default:
		ipath, err := reflections.GetField(val, ignore)
		if err != nil {
			break
		}
		params := convertInterfaceMap(val, []string{ignore})
		return bot.uploadFileWithResult(url, params, file, ipath)
	}
	errc := 400
	errs := "Wrong Query!"
	return ResultWithMessage{ResultBase{false, &errc, &errs}, nil}
}
Example #8
0
func HandleGlobalFlags(cfg interface{}) {
	// Enable debugging if a Debug option is present
	debug, err := reflections.GetField(cfg, "Debug")
	if debug == true && err == nil {
		logger.SetLevel(logger.DEBUG)
	}

	// Enable HTTP debugging
	debugHTTP, err := reflections.GetField(cfg, "DebugHTTP")
	if debugHTTP == true && err == nil {
		agent.APIClientEnableHTTPDebug()
	}

	// Turn off color if a NoColor option is present
	noColor, err := reflections.GetField(cfg, "NoColor")
	if noColor == true && err == nil {
		logger.SetColors(false)
	}
}
Example #9
0
func (this *CCEventHandler) LoadModel(event models.CCEvent) models.Event {
	fields, _ := reflections.Fields(&models.Event{})
	//new instance
	eventModel := models.Event{}

	for i := 0; i < len(fields); i++ {
		has, _ := reflections.HasField(event, fields[i])
		if has == true {
			fmt.Println("Field Exist------", fields[i])
			if fields[i] == "Created_by" {
				var userObj CCUserHandler
				var usermodel models.CCUser
				value, err := reflections.GetField(event, fields[i])

				if err == nil && value != nil {
					str, _ := value.(string)
					usermodel, err = userObj.FetchUserById(str)
					if err == nil {
						responseModel := userObj.LoadModel(usermodel)
						setError := reflections.SetField(&eventModel, fields[i], responseModel) // err != nil
						if setError != nil {
							panic(setError)
						}
					}
				}
			} else {
				value, err := reflections.GetField(event, fields[i])
				if err == nil {
					fmt.Println("Field Value------", value)
					setError := reflections.SetField(&eventModel, fields[i], value) // err != nil

					if setError != nil {
						panic(setError)
					}
				}
			}

		}

	}
	fmt.Println("Data set to Model --- ", eventModel)
	return eventModel
}
func (t *MyTools) GetValueByNamespace(object interface{}, ns []string) interface{} {
	// current level of namespace
	current := ns[0]
	fields, err := reflections.Fields(object)
	if err != nil {
		fmt.Printf("Could not return fields for object{%v}\n", object)
		return nil
	}

	for _, field := range fields {
		tag, err := reflections.GetFieldTag(object, field, "json")
		if err != nil {
			fmt.Printf("Could not find tag for field{%s}\n", field)
			return nil
		}
		// remove omitempty from tag
		tag = strings.Replace(tag, ",omitempty", "", -1)
		if tag == current {
			val, _ := reflections.GetField(object, field)

			// handling of special cases for slice and map
			switch reflect.TypeOf(val).Kind() {
			case reflect.Slice:
				idx, _ := strconv.Atoi(ns[1])
				val := reflect.ValueOf(val)
				if val.Index(idx).Kind() == reflect.Struct {
					return t.GetValueByNamespace(val.Index(idx).Interface(), ns[2:])
				} else {
					return val.Index(idx).Interface()
				}
			case reflect.Map:
				key := ns[1]
				// try uint64 map (memory_stats case)
				if vi, ok := val.(map[string]uint64); ok {
					return vi[key]
				}
				// try with hugetlb map (hugetlb_stats case)
				val := reflect.ValueOf(val)
				kval := reflect.ValueOf(key)
				if reflect.TypeOf(val.MapIndex(kval).Interface()).Kind() == reflect.Struct {
					return t.GetValueByNamespace(val.MapIndex(kval).Interface(), ns[2:])
				}
			default:
				// last ns, return value found
				if len(ns) == 1 {
					return val
				} else {
					// or go deeper
					return t.GetValueByNamespace(val, ns[1:])
				}
			}
		}
	}
	return nil
}
Example #11
0
func (bot TgBot) sendConvertingFile(url string, ignore string, file string, val interface{}) ResultWithMessage {
	ipath, err := reflections.GetField(val, ignore)
	if err != nil {
		errc := 400
		errs := "Wrong Query!"
		return ResultWithMessage{ResultBase{false, &errc, &errs}, nil}
	}
	fpath := fmt.Sprintf("%+v", ipath)
	params := convertInterfaceMap(val, []string{ignore})
	return bot.uploadFileWithResult(url, params, file, fpath)
}
Example #12
0
func (D *DayOfWeekCalls) PopulateHoursByDays(results []HourByDaysRecord) {
	for i := 0; i < len(results); i++ {
		hourName := fmt.Sprintf("H%d", i)

		dayName := fmt.Sprintf("Day%d", D.DayOfWeek-1)

		valueHour, _ := reflections.GetField(D.SummaryCallsPerHours, hourName)

		_ = reflections.SetField(&results[i], dayName, valueHour)
	}
}
func hookDisableWebpage(payload interface{}, nv *bool) {
	if nv != nil {
		has, _ := reflections.HasField(payload, "DisableWebPagePreview")
		if has {
			value, _ := reflections.GetField(payload, "DisableWebPagePreview")
			bvalue := value.(*bool)
			if bvalue == nil {
				reflections.SetField(payload, "DisableWebPagePreview", nv)
			}
		}
	}
}
func hookReplyToMessageID(payload interface{}, nv *bool) {
	if nv != nil {
		has, _ := reflections.HasField(payload, "ReplyToMessageID")
		if has {
			value, _ := reflections.GetField(payload, "ReplyToMessageID")
			bvalue := value.(*int)
			if bvalue == nil {
				reflections.SetField(payload, "ReplyToMessageID", nv)
			}
		}
	}
}
func hookOneTimeKeyboard(payload interface{}, nv *bool) {
	if nv != nil {
		has, _ := reflections.HasField(payload, "OneTimeKeyboard")
		if has {
			value, _ := reflections.GetField(payload, "OneTimeKeyboard")
			bvalue := value.(*bool)
			if bvalue == nil {
				reflections.SetField(payload, "OneTimeKeyboard", nv)
			}
		}
	}
}
func hookSelective(payload interface{}, nv *bool) {
	if nv != nil {
		has, _ := reflections.HasField(payload, "Selective")
		if has {
			value, _ := reflections.GetField(payload, "Selective")
			bvalue := value.(*bool)
			if bvalue == nil {
				reflections.SetField(payload, "Selective", nv)
			}
		}
	}
}
Example #17
0
// HandleField sets value for the given field.
func (dc *DeepCopier) HandleField(options *FieldOptions) error {
	v, err := reflections.GetField(dc.Source, options.SourceField)
	if err != nil {
		return err
	}

	value := reflect.ValueOf(v)
	if err := dc.SetFieldValue(dc.Destination, options.DestinationField, value); err != nil {
		return err
	}

	return nil
}
Example #18
0
func (l Loader) cliValueIsSet(cliName string) bool {
	if l.CLI.IsSet(cliName) {
		return true
	} else {
		// cli.Context#IsSet only checks to see if the command was set via the cli, not
		// via the environment. So here we do some hacks to find out the name of the
		// EnvVar, and return true if it was set.
		for _, flag := range l.CLI.Command.Flags {
			name, _ := reflections.GetField(flag, "Name")
			envVar, _ := reflections.GetField(flag, "EnvVar")
			if name == cliName && envVar != "" {
				// Make sure envVar is a string
				if envVarStr, ok := envVar.(string); ok {
					envVarStr = strings.TrimSpace(string(envVarStr))

					return os.Getenv(envVarStr) != ""
				}
			}
		}
	}

	return false
}
func (t *MyTools) GetValueByField(object interface{}, fields []string) interface{} {
	// current level of struct composition
	field := fields[0]
	// reflect value for current composition by name
	val, err := reflections.GetField(object, field)
	if err != nil {
		fmt.Printf("Value for %s not found\n", field)
		return nil
	}
	// if it's the deepest level of struct composition return it's value
	if len(fields) == 1 {
		return val
	}
	// or go deeper
	return t.GetValueByField(val, fields[1:])
}
func ExampleGetField() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	fieldsToExtract := []string{"FirstField", "ThirdField"}

	for _, fieldName := range fieldsToExtract {
		value, err := reflections.GetField(s, fieldName)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(value)
	}
}
Example #21
0
func (l Loader) fieldValueIsEmpty(fieldName string) bool {
	// We need to use the field kind to determine the type of empty test.
	value, _ := reflections.GetField(l.Config, fieldName)
	fieldKind, _ := reflections.GetFieldKind(l.Config, fieldName)

	if fieldKind == reflect.String {
		return value == ""
	} else if fieldKind == reflect.Slice {
		v := reflect.ValueOf(value)
		return v.Len() == 0
	} else if fieldKind == reflect.Bool {
		return value == false
	} else {
		panic(fmt.Sprintf("Can't determine empty-ness for field type %s", fieldKind))
	}

	return false
}
Example #22
0
func (d *Dsn) SetDefaults(defaults map[string]string) error {
	for k, v := range defaults {
		// Check the dsn struct has field
		value, err := reflections.GetField(d, k)
		if err != nil {
			return err
		}

		// If dsn instance field is set to zero value,
		// then override it with provided default value
		if value == "" {
			err := reflections.SetField(d, k, v)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
Example #23
0
// HandleStructField sets the value for the given supported struct field.
func (dc *DeepCopier) HandleStructField(options *FieldOptions) error {
	f, err := reflections.GetField(dc.Source, options.SourceField)
	if err != nil {
		return err
	}

	switch v := f.(type) {
	case pq.NullTime:
		if v.Valid {
			if err := reflections.SetField(dc.Destination, options.DestinationField, &v.Time); err != nil {
				return err
			}
		}
	case time.Time:
		if err := reflections.SetField(dc.Destination, options.DestinationField, v); err != nil {
			return err
		}
	}

	return nil
}
Example #24
0
// Loop through this to get properties via dot notation
func getProperty(obj interface{}, prop string) (interface{}, error) {

	if reflect.TypeOf(obj).Kind() == reflect.Map {

		val := reflect.ValueOf(obj)

		valueOf := val.MapIndex(reflect.ValueOf(prop))

		if valueOf == reflect.Zero(reflect.ValueOf(prop).Type()) {
			return nil, nil
		}

		idx := val.MapIndex(reflect.ValueOf(prop))

		if !idx.IsValid() {
			return nil, nil
		}
		return idx.Interface(), nil
	}

	prop = strings.Title(prop)
	return reflections.GetField(obj, prop)
}
Example #25
0
func (l Loader) normalizeField(fieldName string, normalization string) error {
	if normalization == "filepath" {
		value, _ := reflections.GetField(l.Config, fieldName)
		fieldKind, _ := reflections.GetFieldKind(l.Config, fieldName)

		// Make sure we're normalizing a string filed
		if fieldKind != reflect.String {
			return fmt.Errorf("filepath normalization only works on string fields")
		}

		// Normalize the field to be a filepath
		if valueAsString, ok := value.(string); ok {
			normalizedPath := NormalizeFilePath(valueAsString)
			if err := reflections.SetField(l.Config, fieldName, normalizedPath); err != nil {
				return err
			}
		}
	} else {
		return fmt.Errorf("Unknown normalization `%s`", normalization)
	}

	return nil
}
// HookPayload I hate reflection, sorry for that <3
func hookPayload(payload interface{}, opts DefaultOptionsBot) {
	hookDisableWebpage(payload, opts.DisableWebURL)
	// HookReplyToMessageID(payload, opts.ReplyToMessageID)

	has, _ := reflections.HasField(payload, "ReplyMarkup")

	if has {
		keyint, _ := reflections.GetField(payload, "ReplyMarkup")

		switch val := keyint.(type) {
		case *ForceReply, *ReplyKeyboardHide:
			if val != nil {
				hookSelective(val, opts.Selective)
			}
		case *ReplyKeyboardMarkup:
			if val != nil {
				hookOneTimeKeyboard(val, opts.OneTimeKeyboard)
				hookSelective(val, opts.Selective)
			}
		default:
		}
	}
}
Example #27
0
func formTagFromField(fieldName string, target interface{}) (string, error) {
	fieldKind, err := reflections.GetFieldKind(target, fieldName)
	f, _ := reflections.GetField(target, fieldName)
	fmt.Printf("Field %v\n", f)
	if err != nil {
		return "", err
	}

	choices, _ := reflections.GetFieldTag(target, fieldName, "choices")

	switch fieldKind {
	case reflect.String:
		if choices != "" {
			return "list", nil
		}
		return "input", nil
	case reflect.Slice:

		return "checkbox", nil
	case reflect.Bool:
		return "confirm", nil
	}
	return "", nil
}
Example #28
0
// Deletes references to a document from its related documents
func CascadeDelete(collection *Collection, doc interface{}) {
	// Find out which properties to cascade
	if conv, ok := doc.(interface {
		GetCascade(*Collection) []*CascadeConfig
	}); ok {
		toCascade := conv.GetCascade(collection)

		// Get the ID

		for _, conf := range toCascade {
			if len(conf.ReferenceQuery) == 0 {
				id, err := reflections.GetField(doc, "Id")
				if err != nil {
					panic(err)
				}
				conf.ReferenceQuery = []*ReferenceField{&ReferenceField{"_id", id}}
			}

			cascadeDeleteWithConfig(conf)

		}

	}
}