printgetter.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package printutils
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. "yunion.io/x/jsonutils"
  20. "yunion.io/x/pkg/gotypes"
  21. "yunion.io/x/pkg/utils"
  22. )
  23. func getter2json(obj interface{}) jsonutils.JSONObject {
  24. jsonDict := jsonutils.NewDict()
  25. objValue := reflect.ValueOf(obj)
  26. objType := reflect.TypeOf(obj)
  27. // log.Debugf("getter2json %d", objValue.NumMethod())
  28. for i := 0; i < objValue.NumMethod(); i += 1 {
  29. methodValue := objValue.Method(i)
  30. method := objType.Method(i)
  31. methodName := method.Name
  32. methodType := methodValue.Type()
  33. if strings.HasPrefix(methodName, "Get") && methodType.NumIn() == 0 && methodType.NumOut() >= 1 {
  34. fieldName := utils.CamelSplit(methodName[3:], "_")
  35. out := methodValue.Call([]reflect.Value{})
  36. if len(out) == 1 && !gotypes.IsNil(out[0].Interface()) {
  37. jsonDict.Add(jsonutils.Marshal(out[0].Interface()), fieldName)
  38. } else if len(out) == 2 {
  39. err, ok := out[1].Interface().(error)
  40. if ok {
  41. if err != nil && !gotypes.IsNil(out[0].Interface()) {
  42. jsonDict.Add(jsonutils.Marshal(out[0].Interface()), fieldName)
  43. }
  44. }
  45. }
  46. }
  47. }
  48. return jsonDict
  49. }
  50. func PrintGetterList(data interface{}, columns []string) {
  51. dataValue := reflect.ValueOf(data)
  52. if dataValue.Kind() != reflect.Slice {
  53. fmt.Println("Invalid list data")
  54. return
  55. }
  56. jsonList := make([]jsonutils.JSONObject, dataValue.Len())
  57. for i := 0; i < dataValue.Len(); i += 1 {
  58. jsonList[i] = getter2json(dataValue.Index(i).Interface())
  59. }
  60. list := &ListResult{
  61. Data: jsonList,
  62. Total: dataValue.Len(),
  63. Limit: 0,
  64. Offset: 0,
  65. }
  66. PrintJSONList(list, columns)
  67. }
  68. func PrintGetterObject(obj interface{}) {
  69. PrintJSONObject(getter2json(obj))
  70. }