gop

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 21, 2023 License: MIT Imports: 17 Imported by: 3

README

Go Pretty Print Value

Make a random Go value human readable. The output format uses valid golang syntax, so you don't have to learn any new knowledge to understand the output.

Features

  • Uses valid golang syntax to print the data
  • Make rune, []byte, time, etc. data human readable
  • Color output with customizable theme
  • Stable map output with sorted by keys
  • Auto split multiline large string block
  • Prints the path of circular reference
  • Auto format inline json string
  • Low-level API to extend the lib

Usage

Usually, you only need to use gop.P function:

package main

import (
    "time"

    "github.com/ysmood/got/lib/gop"
)

func main() {
    val := map[string]interface{}{
        "bool":   true,
        "number": 1 + 1i,
        "bytes":  []byte{97, 98, 99},
        "lines":  "multiline string\nline two",
        "slice":  []interface{}{1, 2},
        "time":   time.Now(),
        "chan":   make(chan int, 1),
        "struct": struct{ test int32 }{
            test: 13,
        },
        "json": `{"a"   : 1}`,
        "func": func(int) int { return 0 },
    }
    val["slice"].([]interface{})[1] = val["slice"]

    _ = gop.P(val)
}

The output will be something like:

// 2022-05-09T08:33:29.103701+08:00 example/main.go:26 (main.main)
map[string]interface {}/* len=10 */{
    "bool": true,
    "bytes": []byte("abc"),
    "chan": make(chan int, 1)/* 0xc000058070 */,
    "func": (func(int) int)(nil)/* 0x10e8d00 */,
    "json": gop.JSONStr(map[string]interface {}{
        "a": 1.0,
    }, `{"a"   : 1}`),
    "lines": `multiline string
line two`/* len=25 */,
    "number": 1+1i,
    "slice": []interface {}/* len=2 cap=2 */{
        1,
        gop.Circular("slice").([]interface {}),
    },
    "struct": struct { test int32 }{
        test: int32(13),
    },
    "time": gop.Time(`2022-05-09T08:33:29.103013+08:00`, 3979567),
}

Documentation

Overview

Package gop ...

Index

Constants

View Source
const SymbolBase64 = "gop.Base64"

SymbolBase64 for Base64

View Source
const SymbolCircular = "gop.Circular"

SymbolCircular for Circular

View Source
const SymbolDuration = "gop.Duration"

SymbolDuration for Duration

View Source
const SymbolJSONBytes = "gop.JSONBytes"

SymbolJSONBytes for JSONBytes

View Source
const SymbolJSONStr = "gop.JSONStr"

SymbolJSONStr for JSONStr

View Source
const SymbolPtr = "gop.Ptr"

SymbolPtr for Ptr

View Source
const SymbolTime = "gop.Time"

SymbolTime for Time

Variables

View Source
var (
	// Bold style
	Bold = addStyle(1, 22)
	// Faint style
	Faint = addStyle(2, 22)
	// Italic style
	Italic = addStyle(3, 23)
	// Underline style
	Underline = addStyle(4, 24)
	// Blink style
	Blink = addStyle(5, 25)
	// RapidBlink style
	RapidBlink = addStyle(6, 26)
	// Invert style
	Invert = addStyle(7, 27)
	// Hide style
	Hide = addStyle(8, 28)
	// Strike style
	Strike = addStyle(9, 29)

	// Black color
	Black = addStyle(30, 39)
	// Red color
	Red = addStyle(31, 39)
	// Green color
	Green = addStyle(32, 39)
	// Yellow color
	Yellow = addStyle(33, 39)
	// Blue color
	Blue = addStyle(34, 39)
	// Magenta color
	Magenta = addStyle(35, 39)
	// Cyan color
	Cyan = addStyle(36, 39)
	// White color
	White = addStyle(37, 39)

	// BgBlack color
	BgBlack = addStyle(40, 49)
	// BgRed color
	BgRed = addStyle(41, 49)
	// BgGreen color
	BgGreen = addStyle(42, 49)
	// BgYellow color
	BgYellow = addStyle(43, 49)
	// BgBlue color
	BgBlue = addStyle(44, 49)
	// BgMagenta color
	BgMagenta = addStyle(45, 49)
	// BgCyan color
	BgCyan = addStyle(46, 49)
	// BgWhite color
	BgWhite = addStyle(47, 49)

	// None type
	None = Style{}
)
View Source
var NoStyle = func() bool {
	_, noColor := os.LookupEnv("NO_COLOR")

	b, _ := exec.Command("tput", "colors").CombinedOutput()
	n, _ := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 32)
	return noColor || n == 0
}()

NoStyle respects https://no-color.org/ and "tput colors"

View Source
var RegANSI = regexp.MustCompile(`\x1b\[\d+m`)

RegANSI token

View Source
var Stdout io.Writer = os.Stdout

Stdout is the default stdout for gop.P .

View Source
var ThemeDefault = func(t Type) []Style {
	switch t {
	case TypeName:
		return []Style{Cyan}
	case Bool, Chan:
		return []Style{Blue}
	case Rune, Byte, String:
		return []Style{Yellow}
	case Number:
		return []Style{Green}
	case Func:
		return []Style{Magenta}
	case Comment:
		return []Style{White}
	case Nil:
		return []Style{Red}
	case Error:
		return []Style{Underline, Red}
	default:
		return []Style{None}
	}
}

ThemeDefault colors for Sprint

View Source
var ThemeNone = func(t Type) []Style {
	return []Style{None}
}

ThemeNone colors for Sprint

Functions

func Base64

func Base64(s string) []byte

Base64 returns the []byte that s represents

func Circular

func Circular(path ...interface{}) interface{}

Circular reference of the path from the root

func Duration

func Duration(s string) time.Duration

Duration from parsing s

func F

func F(v interface{}) string

F is a shortcut for Format with color

func FixNestedStyle

func FixNestedStyle(s string) string

FixNestedStyle like

<d><a>1<b>2<c>3</d></>4</>5</>

into

<d><a>1</><b>2</><c>3</d></><b>4</><a>5</>

func Format

func Format(ts []*Token, theme Theme) string

Format a list of tokens

func GetPrivateField

func GetPrivateField(v reflect.Value, i int) reflect.Value

GetPrivateField via field index TODO: we can use a LRU cache for the copy of the values, but it might be trivial for just testing.

func GetPrivateFieldByName

func GetPrivateFieldByName(v reflect.Value, name string) reflect.Value

GetPrivateFieldByName is similar with GetPrivateField

func JSONBytes

func JSONBytes(v interface{}, raw string) []byte

JSONBytes returns the raw as []byte

func JSONStr

func JSONStr(v interface{}, raw string) string

JSONStr returns the raw

func P

func P(values ...interface{}) error

P pretty print the values

func Plain

func Plain(v interface{}) string

Plain is a shortcut for Format with plain color

func Ptr

func Ptr(v interface{}) interface{}

Ptr returns a pointer to v

func S

func S(str string, styles ...Style) string

S is the shortcut for Stylize

func StripANSI

func StripANSI(str string) string

StripANSI tokens

func Stylize

func Stylize(str string, styles []Style) string

Stylize string

func Time

func Time(s string, monotonic int) time.Time

Time from parsing s

func VisualizeANSI

func VisualizeANSI(str string) string

VisualizeANSI tokens

Types

type Style

type Style struct {
	Set   string
	Unset string
}

Style type

func GetStyle

func GetStyle(s string) Style

GetStyle from available styles

type Theme

type Theme func(t Type) []Style

Theme to color values

type Token

type Token struct {
	Type    Type
	Literal string
}

Token represents a symbol in value layout

func Tokenize

func Tokenize(v interface{}) []*Token

Tokenize a random Go value

type Type

type Type int

Type of token

const (
	// Nil type
	Nil Type = iota
	// Bool type
	Bool
	// Number type
	Number
	// Float type
	Float
	// Complex type
	Complex
	// String type
	String
	// Byte type
	Byte
	// Rune type
	Rune
	// Chan type
	Chan
	// Func type
	Func
	// Error type
	Error

	// Comment type
	Comment

	// TypeName type
	TypeName

	// ParenOpen type
	ParenOpen
	// ParenClose type
	ParenClose

	// Dot type
	Dot
	// And type
	And

	// SliceOpen type
	SliceOpen
	// SliceItem type
	SliceItem
	// InlineComma type
	InlineComma
	// Comma type
	Comma
	// SliceClose type
	SliceClose

	// MapOpen type
	MapOpen
	// MapKey type
	MapKey
	// Colon type
	Colon
	// MapClose type
	MapClose

	// StructOpen type
	StructOpen
	// StructKey type
	StructKey
	// StructField type
	StructField
	// StructClose type
	StructClose
)

Directories

Path Synopsis
Package main ...
Package main ...

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL