-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkarma.go
564 lines (469 loc) · 12.1 KB
/
karma.go
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// Package karma provides a simple way to return and display hierarchical
// messages or errors.
//
// Transforms:
//
// can't pull remote 'origin': can't run git fetch 'origin' 'refs/tokens/*:refs/tokens/*': exit status 128
//
// Into:
//
// can't pull remote 'origin'
// └─ can't run git fetch 'origin' 'refs/tokens/*:refs/tokens/*'
// └─ exit status 128
package karma // import "github.com/reconquest/karma-go"
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"unicode"
)
const (
// BranchDelimiterASCII represents a simple ASCII delimiter for hierarchy
// branches.
//
// Use: karma.BranchDelimiter = karma.BranchDelimiterASCII
BranchDelimiterASCII = `\_ `
// BranchDelimiterBox represents UTF8 delimiter for hierarchy branches.
//
// Use: karma.BranchDelimiter = karma.BranchDelimiterBox
BranchDelimiterBox = `└─ `
// BranchChainerASCII represents a simple ASCII chainer for hierarchy
// branches.
//
// Use: karma.BranchChainer = karma.BranchChainerASCII
BranchChainerASCII = `| `
// BranchChainerBox represents UTF8 chainer for hierarchy branches.
//
// Use: karma.BranchChainer = karma.BranchChainerBox
BranchChainerBox = `│ `
// BranchSplitterASCII represents a simple ASCII splitter for hierarchy
// branches.
//
// Use: karma.BranchSplitter = karma.BranchSplitterASCII
BranchSplitterASCII = `+ `
// BranchSplitterBox represents UTF8 splitter for hierarchy branches.
//
// Use: karma.BranchSplitter = karma.BranchSplitterBox
BranchSplitterBox = `├─ `
)
var (
// BranchDelimiter set delimiter each nested message text will be started
// from.
BranchDelimiter = BranchDelimiterBox
// BranchChainer set chainer each nested message tree text will be started
// from.
BranchChainer = BranchChainerBox
// BranchSplitter set splitter each nested messages splitted by.
BranchSplitter = BranchSplitterBox
// BranchIndent set number of spaces each nested message will be indented by.
BranchIndent = 3
)
var branchIndentation = " "
// Karma represents hierarchy message, linked with nested message.
type Karma struct {
// Reason of message, which can be Karma as well.
Reason Reason
// Message is formatted message, which will be returned when String()
// will be invoked.
Message string
// Context is a key-pair linked list, which represents runtime context
// of the situtation.
Context *Context
}
// Hierarchical represents interface, which methods will be used instead
// of calling String() and Karma() methods.
type Hierarchical interface {
// String returns hierarchical string representation.
String() string
// GetReasons returns slice of nested reasons.
GetReasons() []Reason
// GetMessage returns top-level message.
GetMessage() string
}
// assert that instance of Karma implements Hierarchical interface
var _ Hierarchical = (*Karma)(nil)
// Reason is either `error` or string.
type Reason interface{}
type jsonRepresentation struct {
Reason json.RawMessage `json:"reason,omitempty"`
Message string `json:"message,omitempty"`
Context *Context `json:"context,omitempty"`
}
// Format creates new hierarchical message.
//
// With reason == nil call will be equal to `fmt.Errorf()`.
func Format(
reason Reason,
message string,
args ...interface{},
) Karma {
return Karma{
Message: fmt.Sprintf(message, args...),
Reason: reason,
}
}
// ContextValueFormatter returns string representation of context value when
// Format() is called on Karma struct.
var ContextValueFormatter = func(value interface{}) string {
if value, ok := value.(string); ok {
if value == "" {
return "<empty>"
}
}
switch value := value.(type) {
case string:
return value
case fmt.Stringer:
return fmt.Sprint(value)
case bool:
return strconv.FormatBool(value)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return fmt.Sprint(value)
case float32, float64:
return fmt.Sprint(value)
default:
result, err := json.MarshalIndent(value, "", " ")
if err != nil {
return fmt.Sprintf("unable to marshal value: %s", err)
}
return string(result)
}
}
// Karma returns hierarchical string representation. If no nested
// message was specified, then only current message will be returned.
func (karma Karma) String() string {
karma.Context.Walk(func(name string, value interface{}) {
karma = Push(karma, Push(
name+": "+ContextValueFormatter(value),
))
})
switch value := karma.Reason.(type) {
case nil:
return karma.Message
case []Reason:
return formatReasons(karma, value)
default:
return karma.Message + "\n" +
BranchDelimiter +
strings.Replace(
stringReason(karma.Reason),
"\n",
"\n"+getBranchIndentation(),
-1,
)
}
}
func getBranchIndentation() string {
if len(branchIndentation) != BranchIndent {
branchIndentation = strings.Repeat(" ", BranchIndent)
}
return branchIndentation
}
func stringReason(reason Reason) string {
switch typed := reason.(type) {
case []byte:
return string(typed)
case string:
return typed
case error:
return typed.Error()
default:
return fmt.Sprint(typed)
}
}
// GetReasons returns nested messages
func GetReasons(err error) []Reason {
if karma, ok := getKarma(err); ok {
return karma.GetReasons()
}
return []Reason{err}
}
// Error implements error interface, Karma can be returned as error.
func (karma Karma) Error() string {
return karma.String()
}
// GetReasons returns nested messages, embedded into message.
func (karma Karma) GetReasons() []Reason {
if karma.Reason == nil {
return nil
}
if reasons, ok := karma.Reason.([]Reason); ok {
return reasons
} else {
return []Reason{karma.Reason}
}
}
// GetMessage returns message message
func (karma Karma) GetMessage() string {
if karma.Message == "" {
return fmt.Sprintf("%s", karma.Reason)
} else {
return karma.Message
}
}
// GetContext returns context
func (karma Karma) GetContext() *Context {
return karma.Context
}
// Descend calls specified callback for every nested hierarchical message.
func (karma Karma) Descend(callback func(Reason)) {
// Do not descend into trivial cases, when message is reason, e.g. after
// Reason() call.
if karma.Message == "" {
return
}
for _, reason := range karma.GetReasons() {
switch reason := reason.(type) {
case Karma:
callback(reason)
reason.Descend(callback)
default:
callback(reason)
}
}
}
func (karma Karma) MarshalJSON() ([]byte, error) {
result := jsonRepresentation{
Message: karma.Message,
Context: karma.Context,
}
var err error
switch reason := karma.Reason.(type) {
case json.Marshaler:
result.Reason, err = json.Marshal(reason)
case error:
result.Reason, err = json.Marshal(reason.Error())
default:
result.Reason, err = json.Marshal(reason)
}
if err != nil {
return nil, err
}
return json.Marshal(result)
}
func (karma *Karma) UnmarshalJSON(data []byte) error {
var container jsonRepresentation
err := json.Unmarshal(data, &container)
if err != nil {
return err
}
var reason Karma
if len(container.Reason) > 0 {
err = json.Unmarshal(container.Reason, &reason)
if err != nil {
err = json.Unmarshal(container.Reason, &karma.Reason)
if err != nil {
return err
}
} else {
karma.Reason = reason
}
}
karma.Message = container.Message
karma.Context = container.Context
return nil
}
// Push creates new hierarchy message with multiple branches separated by
// separator, delimited by delimiter and prolongated by prolongator.
func Push(reason Reason, reasons ...Reason) Karma {
parent, ok := reason.(Karma)
if !ok {
parent = Karma{
Message: fmt.Sprint(reason),
}
}
newReasons := parent.GetReasons()
for _, reason := range reasons {
if reason != nil {
newReasons = append(newReasons, reason)
}
}
return Karma{
Message: parent.Message,
Reason: newReasons,
}
}
// Describe creates new context list, which can be used to produce context-rich
// hierarchical message.
func Describe(key string, value interface{}) *Context {
return &Context{
KeyValue: KeyValue{
Key: key,
Value: value,
},
}
}
// Find typed object in given chain of reasons, returns true if reason with the
// same type found, if typed object is addressable, value will be stored in it.
func Find(err Reason, typed interface{}) bool {
indirect := reflect.Indirect(reflect.ValueOf(typed))
indirectType := indirect.Type()
karma, ok := getKarma(err)
if ok {
return find(karma, typed, indirect, indirectType)
}
same := reflect.TypeOf(err) == indirectType
if same {
if indirect.CanAddr() {
indirect.Set(reflect.ValueOf(err))
}
}
return same
}
func find(
karma *Karma,
typed interface{},
indirect reflect.Value,
indirectType reflect.Type,
) bool {
for _, nested := range karma.GetReasons() {
subkarma, ok := getKarma(nested)
if ok {
if find(subkarma, typed, indirect, indirectType) {
return true
}
} else {
same := reflect.TypeOf(nested) == indirectType
if same {
if indirect.CanAddr() {
indirect.Set(reflect.ValueOf(nested))
}
}
return same
}
}
return false
}
// Contains returns true when branch is found in reasons of given chain. Or
// chain has the same value as branch error.
// Useful when you work with result of multi-level error and just wanted to
// check that error contains os.ErrNoExist.
func Contains(chain Reason, branch Reason) bool {
karma, ok := getKarma(chain)
if ok {
return contains(karma, branch)
}
return stringReason(chain) == stringReason(branch)
}
func contains(karma *Karma, reason Reason) bool {
reasonString := fmt.Sprint(reason)
for _, nested := range karma.GetReasons() {
subkarma, ok := getKarma(nested)
if ok {
if contains(subkarma, reason) {
return true
}
} else {
if fmt.Sprint(nested) == reasonString {
return true
}
}
}
return false
}
func getKarma(reason Reason) (*Karma, bool) {
karma, ok := reason.(Karma)
if ok {
return &karma, true
}
pointer, ok := reason.(*Karma)
if ok {
return pointer, true
}
return nil, false
}
func formatReasons(karma Karma, reasons []Reason) string {
message := bytes.NewBufferString(karma.Message)
prolongate := false
for _, reason := range reasons {
if reasons, ok := reason.(Hierarchical); ok {
if len(reasons.GetReasons()) > 0 {
prolongate = true
break
}
}
}
var (
chainerLength = len([]rune(BranchChainer))
splitter = BranchSplitter
chainer = BranchChainer
prolongator = "\n" + strings.TrimRightFunc(
chainer, unicode.IsSpace,
)
)
indentation := chainer
if BranchIndent >= chainerLength {
indentation += strings.Repeat(" ", BranchIndent-chainerLength)
}
for index, reason := range reasons {
if index == len(reasons)-1 {
splitter = BranchDelimiter
if chainerLength < BranchIndent {
chainerLength = BranchIndent
}
indentation = strings.Repeat(" ", chainerLength)
}
if message.Len() != 0 {
message.WriteString("\n")
message.WriteString(splitter)
}
reason := stringReason(reason)
message.WriteString(strings.Replace(
reason,
"\n",
"\n"+indentation,
-1,
))
if prolongate && index < len(reasons)-1 {
if strings.Count(reason, "\n") > 0 {
message.WriteString(prolongator)
}
}
}
return message.String()
}
// Collect function collects multiple errors into a hierarchical one.
// It uses karma.Push to add all errors as children for the parent error.
func Collect(parent Reason, err ...error) Karma {
top, ok := parent.(Karma)
if !ok {
top = Karma{
Message: fmt.Sprint(parent),
}
}
for _, e := range err {
if e != nil {
top = Push(top, e)
}
}
return top
}
func (karma Karma) Is(target error) bool {
return Contains(karma, target)
}
func (karma Karma) Unwrap() error {
return weirdo{k: karma}
}
// well, somehow they managed to come up with Unwrap() and Unwrap() []error
// while we cannot do such methods a normal way, so this weirdo works as a layer
type weirdo struct {
k Karma
}
func (weirdo weirdo) Unwrap() []error {
var result []error
weirdo.k.Descend(func(reason Reason) {
if err, ok := reason.(error); ok {
result = append(result, err)
}
})
return result
}
func (weirdo weirdo) Error() string {
if err, ok := weirdo.k.Reason.(error); ok {
return err.Error()
}
return weirdo.k.Error()
}