File: string.go

package info (click to toggle)
golang-github-maxatome-go-testdeep 1.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,416 kB
  • sloc: perl: 1,012; yacc: 130; makefile: 2
file content (222 lines) | stat: -rw-r--r-- 5,131 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright (c) 2018-2022, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

package util

import (
	"bytes"
	"fmt"
	"io"
	"reflect"
	"strconv"
	"strings"

	"github.com/maxatome/go-testdeep/helpers/tdutil"
	"github.com/maxatome/go-testdeep/internal/dark"
	"github.com/maxatome/go-testdeep/internal/types"
)

// ToString does its best to stringify val.
func ToString(val any) string {
	if val == nil {
		return "nil"
	}

	switch tval := val.(type) {
	case reflect.Value:
		newVal, ok := dark.GetInterface(tval, true)
		if ok {
			return ToString(newVal)
		}

	case []reflect.Value:
		var buf strings.Builder
		SliceToString(&buf, tval)
		return buf.String()

		// no "(string) " prefix for printable strings
	case string:
		return tdutil.FormatString(tval)

		// no "(int) " prefix for ints
	case int:
		return strconv.Itoa(tval)

		// no "(float64) " prefix for float64s
	case float64:
		s := strconv.FormatFloat(tval, 'g', -1, 64)
		if strings.ContainsAny(s, "e.IN") { // I for Inf, N for NaN
			return s
		}
		return s + ".0" // to distinguish from ints

		// no "(bool) " prefix for booleans
	case bool:
		return TernStr(tval, "true", "false")

	case types.TestDeepStringer:
		return tval.String()
	}

	return tdutil.SpewString(val)
}

// IndentString indents str lines (from 2nd one = 1st line is not
// indented) by indent.
func IndentString(str, indent string) string {
	return strings.ReplaceAll(str, "\n", "\n"+indent)
}

// IndentStringIn indents str lines (from 2nd one = 1st line is not
// indented) by indent and write it to w.
func IndentStringIn(w io.Writer, str, indent string) {
	repl := strings.NewReplacer("\n", "\n"+indent)
	repl.WriteString(w, str) //nolint: errcheck
}

// IndentColorizeStringIn indents str lines (from 2nd one = 1st line
// is not indented) by indent and write it to w. Before each end of
// line, colOff is inserted, and after each indent on new line, colOn
// is inserted.
func IndentColorizeStringIn(w io.Writer, str, indent, colOn, colOff string) {
	if str != "" {
		if colOn == "" && colOff == "" {
			IndentStringIn(w, str, indent)
			return
		}
		repl := strings.NewReplacer("\n", colOff+"\n"+indent+colOn)
		io.WriteString(w, colOn)  //nolint: errcheck
		repl.WriteString(w, str)  //nolint: errcheck
		io.WriteString(w, colOff) //nolint: errcheck
	}
}

// SliceToString stringifies items slice into buf then returns buf.
func SliceToString(buf *strings.Builder, items []reflect.Value) *strings.Builder {
	buf.WriteByte('(')

	begLine := strings.LastIndexByte(buf.String(), '\n') + 1
	prefix := strings.Repeat(" ", buf.Len()-begLine)

	if len(items) < 2 {
		if len(items) > 0 {
			buf.WriteString(IndentString(ToString(items[0]), prefix))
		}
	} else {
		buf.WriteString(IndentString(ToString(items[0]), prefix))
		for _, item := range items[1:] {
			buf.WriteString(",\n")
			buf.WriteString(prefix)
			buf.WriteString(IndentString(ToString(item), prefix))
		}
	}
	buf.WriteByte(')')

	return buf
}

// TypeFullName returns the t type name with packages fully visible
// instead of the last package part in t.String().
func TypeFullName(t reflect.Type) string {
	var b bytes.Buffer
	typeFullName(&b, t)
	return b.String()
}

func typeFullName(b *bytes.Buffer, t reflect.Type) {
	if t.Name() != "" {
		if pkg := t.PkgPath(); pkg != "" {
			fmt.Fprintf(b, "%s.", pkg)
		}
		b.WriteString(t.Name())
		return
	}

	switch t.Kind() {
	case reflect.Ptr:
		b.WriteByte('*')
		typeFullName(b, t.Elem())

	case reflect.Slice:
		b.WriteString("[]")
		typeFullName(b, t.Elem())

	case reflect.Array:
		fmt.Fprintf(b, "[%d]", t.Len())
		typeFullName(b, t.Elem())

	case reflect.Map:
		b.WriteString("map[")
		typeFullName(b, t.Key())
		b.WriteByte(']')
		typeFullName(b, t.Elem())

	case reflect.Struct:
		b.WriteString("struct {")
		if num := t.NumField(); num > 0 {
			for i := 0; i < num; i++ {
				sf := t.Field(i)
				if !sf.Anonymous {
					b.WriteByte(' ')
					b.WriteString(sf.Name)
				}
				b.WriteByte(' ')
				typeFullName(b, sf.Type)
				b.WriteByte(';')
			}
			b.Truncate(b.Len() - 1)
			b.WriteByte(' ')
		}
		b.WriteByte('}')

	case reflect.Func:
		b.WriteString("func(")
		if num := t.NumIn(); num > 0 {
			for i := 0; i < num; i++ {
				if i == num-1 && t.IsVariadic() {
					b.WriteString("...")
					typeFullName(b, t.In(i).Elem())
				} else {
					typeFullName(b, t.In(i))
				}
				b.WriteString(", ")
			}
			b.Truncate(b.Len() - 2)
		}
		b.WriteByte(')')

		if num := t.NumOut(); num > 0 {
			if num == 1 {
				b.WriteByte(' ')
			} else {
				b.WriteString(" (")
			}
			for i := 0; i < num; i++ {
				typeFullName(b, t.Out(i))
				b.WriteString(", ")
			}
			b.Truncate(b.Len() - 2)
			if num > 1 {
				b.WriteByte(')')
			}
		}

	case reflect.Chan:
		switch t.ChanDir() {
		case reflect.RecvDir:
			b.WriteString("<-chan ")
		case reflect.SendDir:
			b.WriteString("chan<- ")
		case reflect.BothDir:
			b.WriteString("chan ")
		}
		typeFullName(b, t.Elem())

	default:
		// Fallback to default implementation
		b.WriteString(t.String())
	}
}