You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

helper.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package queue
  5. import (
  6. "encoding/json"
  7. "reflect"
  8. )
  9. // toConfig will attempt to convert a given configuration cfg into the provided exemplar type.
  10. //
  11. // It will tolerate the cfg being passed as a []byte or string of a json representation of the
  12. // exemplar or the correct type of the exemplar itself
  13. func toConfig(exemplar, cfg interface{}) (interface{}, error) {
  14. if reflect.TypeOf(cfg).AssignableTo(reflect.TypeOf(exemplar)) {
  15. return cfg, nil
  16. }
  17. configBytes, ok := cfg.([]byte)
  18. if !ok {
  19. configStr, ok := cfg.(string)
  20. if !ok {
  21. return nil, ErrInvalidConfiguration{cfg: cfg}
  22. }
  23. configBytes = []byte(configStr)
  24. }
  25. newVal := reflect.New(reflect.TypeOf(exemplar))
  26. if err := json.Unmarshal(configBytes, newVal.Interface()); err != nil {
  27. return nil, ErrInvalidConfiguration{cfg: cfg, err: err}
  28. }
  29. return newVal.Elem().Interface(), nil
  30. }
  31. // unmarshalAs will attempt to unmarshal provided bytes as the provided exemplar
  32. func unmarshalAs(bs []byte, exemplar interface{}) (data Data, err error) {
  33. if exemplar != nil {
  34. t := reflect.TypeOf(exemplar)
  35. n := reflect.New(t)
  36. ne := n.Elem()
  37. err = json.Unmarshal(bs, ne.Addr().Interface())
  38. data = ne.Interface().(Data)
  39. } else {
  40. err = json.Unmarshal(bs, &data)
  41. }
  42. return
  43. }
  44. // assignableTo will check if provided data is assignable to the same type as the exemplar
  45. // if the provided exemplar is nil then it will always return true
  46. func assignableTo(data Data, exemplar interface{}) bool {
  47. if exemplar == nil {
  48. return true
  49. }
  50. // Assert data is of same type as exemplar
  51. t := reflect.TypeOf(data)
  52. exemplarType := reflect.TypeOf(exemplar)
  53. return t.AssignableTo(exemplarType) && data != nil
  54. }