Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

helper.go 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 storage
  5. import (
  6. "reflect"
  7. "code.gitea.io/gitea/modules/json"
  8. )
  9. // Mappable represents an interface that can MapTo another interface
  10. type Mappable interface {
  11. MapTo(v interface{}) error
  12. }
  13. // toConfig will attempt to convert a given configuration cfg into the provided exemplar type.
  14. //
  15. // It will tolerate the cfg being passed as a []byte or string of a json representation of the
  16. // exemplar or the correct type of the exemplar itself
  17. func toConfig(exemplar, cfg interface{}) (interface{}, error) {
  18. // First of all check if we've got the same type as the exemplar - if so it's all fine.
  19. if reflect.TypeOf(cfg).AssignableTo(reflect.TypeOf(exemplar)) {
  20. return cfg, nil
  21. }
  22. // Now if not - does it provide a MapTo function we can try?
  23. if mappable, ok := cfg.(Mappable); ok {
  24. newVal := reflect.New(reflect.TypeOf(exemplar))
  25. if err := mappable.MapTo(newVal.Interface()); err == nil {
  26. return newVal.Elem().Interface(), nil
  27. }
  28. // MapTo has failed us ... let's try the json route ...
  29. }
  30. // OK we've been passed a byte array right?
  31. configBytes, ok := cfg.([]byte)
  32. if !ok {
  33. // oh ... it's a string then?
  34. var configStr string
  35. configStr, ok = cfg.(string)
  36. configBytes = []byte(configStr)
  37. }
  38. if !ok {
  39. // hmm ... can we marshal it to json?
  40. var err error
  41. configBytes, err = json.Marshal(cfg)
  42. ok = err == nil
  43. }
  44. if !ok {
  45. // no ... we've tried hard enough at this point - throw an error!
  46. return nil, ErrInvalidConfiguration{cfg: cfg}
  47. }
  48. // OK unmarshal the byte array into a new copy of the exemplar
  49. newVal := reflect.New(reflect.TypeOf(exemplar))
  50. if err := json.Unmarshal(configBytes, newVal.Interface()); err != nil {
  51. // If we can't unmarshal it then return an error!
  52. return nil, ErrInvalidConfiguration{cfg: cfg, err: err}
  53. }
  54. return newVal.Elem().Interface(), nil
  55. }