print.go.3 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "reflect"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "github.com/muesli/termenv"
  10. )
  11. // 颜色配置枚举
  12. type ColorProfile int
  13. const (
  14. Auto ColorProfile = iota
  15. Dark
  16. Light
  17. NoColor
  18. )
  19. // 打印选项结构
  20. type PrintOptions struct {
  21. ShowTypes bool // 是否显示类型信息
  22. ColorProfile ColorProfile // 颜色配置方案
  23. FloatPrecision int // 浮点数精度(-1表示自动)
  24. }
  25. // 颜色缓存变量
  26. var (
  27. colorType string
  28. colorField string
  29. colorKey string
  30. colorValue string
  31. resetColor string
  32. )
  33. // 初始化颜色配置
  34. func initColors(profile ColorProfile) {
  35. output := termenv.NewOutput(os.Stdout)
  36. style := output.String()
  37. resetColor = style.Reset().String()
  38. switch profile {
  39. case Auto:
  40. if output.HasDarkBackground() {
  41. setDarkThemeColors(output)
  42. } else {
  43. setLightThemeColors(output)
  44. }
  45. case Dark:
  46. setDarkThemeColors(output)
  47. case Light:
  48. setLightThemeColors(output)
  49. case NoColor:
  50. colorType = ""
  51. colorField = ""
  52. colorKey = ""
  53. colorValue = ""
  54. resetColor = ""
  55. }
  56. }
  57. // 暗色主题配色
  58. func setDarkThemeColors(output *termenv.Output) {
  59. colorType = output.String().Foreground(output.Color("#5FAFFF")).String()
  60. colorField = output.String().Foreground(output.Color("#AFF080")).String()
  61. colorKey = output.String().Foreground(output.Color("#FFD700")).String()
  62. colorValue = output.String().Foreground(output.Color("#E0E0E0")).String()
  63. }
  64. // 亮色主题配色
  65. func setLightThemeColors(output *termenv.Output) {
  66. colorType = output.String().Foreground(output.Color("#005FAF")).String()
  67. colorField = output.String().Foreground(output.Color("#008000")).String()
  68. colorKey = output.String().Foreground(output.Color("#AF5F00")).String()
  69. colorValue = output.String().Foreground(output.Color("#404040")).String()
  70. }
  71. // 美观打印入口函数
  72. func PrettyPrint(v interface{}, opts ...PrintOptions) string {
  73. // 设置默认选项
  74. option := PrintOptions{
  75. ShowTypes: true,
  76. ColorProfile: Auto,
  77. FloatPrecision: -1,
  78. }
  79. if len(opts) > 0 {
  80. option = opts[0]
  81. }
  82. // 初始化颜色
  83. initColors(option.ColorProfile)
  84. // 开始递归打印
  85. return prettyPrint(reflect.ValueOf(v), 0, make(map[uintptr]bool), option, []bool{}).String()
  86. }
  87. // 行集合类型
  88. type lines []string
  89. func (l lines) String() string {
  90. return strings.Join(l, "\n")
  91. }
  92. // 核心打印逻辑
  93. func prettyPrint(v reflect.Value, depth int, visited map[uintptr]bool, opts PrintOptions, lastMarkers []bool) lines {
  94. original := v
  95. // 处理指针和接口
  96. for {
  97. switch v.Kind() {
  98. case reflect.Ptr:
  99. if v.IsNil() {
  100. return lines{colorValue + "nil" + resetColor}
  101. }
  102. ptr := v.Pointer()
  103. if visited[ptr] {
  104. return lines{fmt.Sprintf("%s&%p%s", colorValue, v.Interface(), resetColor)}
  105. }
  106. visited[ptr] = true
  107. original = v
  108. v = v.Elem()
  109. case reflect.Interface:
  110. if v.IsNil() {
  111. return lines{colorValue + "nil" + resetColor}
  112. }
  113. v = v.Elem()
  114. default:
  115. goto END_DEREF
  116. }
  117. }
  118. END_DEREF:
  119. var result lines
  120. prefix := buildPrefix(depth, lastMarkers)
  121. // 添加类型行
  122. if opts.ShowTypes && depth == 0 {
  123. typeLine := fmt.Sprintf("%s%s%s", colorType, getTypeName(original, v), resetColor)
  124. result = append(result, typeLine)
  125. }
  126. switch v.Kind() {
  127. case reflect.Struct:
  128. result = append(result, printStruct(v, depth, visited, opts, lastMarkers)...)
  129. case reflect.Map:
  130. result = append(result, printMap(v, depth, visited, opts, lastMarkers)...)
  131. case reflect.Slice, reflect.Array:
  132. result = append(result, printSlice(v, depth, visited, opts, lastMarkers)...)
  133. default:
  134. result = append(result, formatValue(v, prefix, opts))
  135. }
  136. return result
  137. }
  138. // 构建前缀字符串
  139. func buildPrefix(depth int, lastMarkers []bool) string {
  140. if depth == 0 {
  141. return ""
  142. }
  143. var prefix strings.Builder
  144. for i := 0; i < depth-1; i++ {
  145. if i < len(lastMarkers) && lastMarkers[i] {
  146. prefix.WriteString(" ")
  147. } else {
  148. prefix.WriteString("│ ")
  149. }
  150. }
  151. if depth > 0 {
  152. if len(lastMarkers) > 0 && lastMarkers[len(lastMarkers)-1] {
  153. prefix.WriteString("└── ")
  154. } else {
  155. prefix.WriteString("├── ")
  156. }
  157. }
  158. return prefix.String()
  159. }
  160. // 获取类型名称
  161. func getTypeName(original, v reflect.Value) string {
  162. if original.Kind() == reflect.Ptr {
  163. return original.Type().String()
  164. }
  165. return v.Type().String()
  166. }
  167. // 格式化值
  168. func formatValue(v reflect.Value, prefix string, opts PrintOptions) string {
  169. switch v.Kind() {
  170. case reflect.String:
  171. return fmt.Sprintf("%s%s%q%s", prefix, colorValue, v.String(), resetColor)
  172. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  173. return fmt.Sprintf("%s%s%d%s", prefix, colorValue, v.Int(), resetColor)
  174. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  175. return fmt.Sprintf("%s%s%d%s", prefix, colorValue, v.Uint(), resetColor)
  176. case reflect.Float32, reflect.Float64:
  177. return formatFloat(v.Float(), opts.FloatPrecision, prefix)
  178. case reflect.Bool:
  179. return fmt.Sprintf("%s%s%t%s", prefix, colorValue, v.Bool(), resetColor)
  180. default:
  181. return fmt.Sprintf("%s%s%v%s", prefix, colorValue, v.Interface(), resetColor)
  182. }
  183. }
  184. // 格式化浮点数(改进精度处理)
  185. func formatFloat(f float64, precision int, prefix string) string {
  186. var str string
  187. if precision >= 0 {
  188. str = strconv.FormatFloat(f, 'f', precision, 64)
  189. } else {
  190. // 自动处理精度
  191. str = strconv.FormatFloat(f, 'f', -1, 64)
  192. if strings.Contains(str, ".") {
  193. str = strings.TrimRight(str, "0")
  194. str = strings.TrimRight(str, ".")
  195. }
  196. }
  197. return fmt.Sprintf("%s%s%s%s", prefix, colorValue, str, resetColor)
  198. }
  199. // 打印结构体
  200. func printStruct(v reflect.Value, depth int, visited map[uintptr]bool, opts PrintOptions, lastMarkers []bool) lines {
  201. var result lines
  202. fieldCount := v.NumField()
  203. for i := 0; i < fieldCount; i++ {
  204. field := v.Type().Field(i)
  205. fieldValue := v.Field(i)
  206. isLast := i == fieldCount-1
  207. newMarkers := append(lastMarkers, isLast)
  208. subLines := prettyPrint(fieldValue, depth+1, visited, opts, newMarkers)
  209. // 字段头
  210. fieldHeader := fmt.Sprintf("%s%s%s:",
  211. buildPrefix(depth+1, newMarkers[:len(newMarkers)-1]),
  212. colorField,
  213. field.Name,
  214. )
  215. if len(subLines) == 0 {
  216. result = append(result, fieldHeader+colorValue+"<invalid>"+resetColor)
  217. continue
  218. }
  219. // 合并字段头和数据
  220. result = append(result, fieldHeader+strings.TrimPrefix(subLines[0], buildPrefix(depth+1, newMarkers)))
  221. result = append(result, subLines[1:]...)
  222. }
  223. return result
  224. }
  225. // 打印Map
  226. func printMap(v reflect.Value, depth int, visited map[uintptr]bool, opts PrintOptions, lastMarkers []bool) lines {
  227. var result lines
  228. keys := v.MapKeys()
  229. sort.Slice(keys, func(i, j int) bool {
  230. return fmt.Sprintf("%v", keys[i]) < fmt.Sprintf("%v", keys[j])
  231. })
  232. for i, key := range keys {
  233. isLast := i == len(keys)-1
  234. newMarkers := append(lastMarkers, isLast)
  235. keyLines := prettyPrint(key, depth+1, visited, opts, newMarkers)
  236. valueLines := prettyPrint(v.MapIndex(key), depth+1, visited, opts, newMarkers)
  237. // Key头
  238. keyHeader := fmt.Sprintf("%s%s%s:",
  239. buildPrefix(depth+1, newMarkers[:len(newMarkers)-1]),
  240. colorKey,
  241. strings.Join(keyLines, ""),
  242. )
  243. // 合并Key和Value
  244. if len(valueLines) > 0 {
  245. result = append(result, keyHeader+strings.TrimPrefix(valueLines[0], buildPrefix(depth+1, newMarkers)))
  246. result = append(result, valueLines[1:]...)
  247. } else {
  248. result = append(result, keyHeader+"<invalid>")
  249. }
  250. }
  251. return result
  252. }
  253. // 打印Slice/Array
  254. func printSlice(v reflect.Value, depth int, visited map[uintptr]bool, opts PrintOptions, lastMarkers []bool) lines {
  255. var result lines
  256. for i := 0; i < v.Len(); i++ {
  257. isLast := i == v.Len()-1
  258. newMarkers := append(lastMarkers, isLast)
  259. elemLines := prettyPrint(v.Index(i), depth+1, visited, opts, newMarkers)
  260. result = append(result, elemLines...)
  261. }
  262. return result
  263. }
  264. // 测试结构体
  265. type Person struct {
  266. Name string
  267. Age int
  268. Hobbies []string
  269. Address struct {
  270. City string
  271. State string
  272. }
  273. Metadata map[string]interface{}
  274. }
  275. func main() {
  276. p := Person{
  277. Name: "Alice",
  278. Age: 30,
  279. Hobbies: []string{"Reading", "Hiking"},
  280. Metadata: map[string]interface{}{
  281. "id": 123,
  282. "scores": []float64{98.5, 87.2000, 100.0},
  283. "nested": map[string]interface{}{"a": 1, "b": 2},
  284. },
  285. }
  286. p.Address.City = "New York"
  287. p.Address.State = "NY"
  288. p.Metadata["self_ref"] = &p
  289. fmt.Println("=== 默认输出(自动颜色适配)===")
  290. fmt.Println(PrettyPrint(p))
  291. fmt.Println("\n=== 显示类型+亮色主题+浮点精度2位 ===")
  292. fmt.Println(PrettyPrint(p, PrintOptions{
  293. ShowTypes: true,
  294. ColorProfile: Light,
  295. FloatPrecision: 2,
  296. }))
  297. fmt.Println("\n=== 不显示类型+暗色主题 ===")
  298. fmt.Println(PrettyPrint(p, PrintOptions{
  299. ShowTypes: false,
  300. ColorProfile: Dark,
  301. }))
  302. }