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

helper.go 2.0 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "encoding/json"
  7. "reflect"
  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. }