-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
130 lines (115 loc) · 2.5 KB
/
group.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
// Copyright 2018 Sevki <s@sevki.org>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package errors provides grouped errors.
package errors // import "sevki.org/x/errors"
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"sync"
)
type levelederror struct {
level int
err error
}
// Group defines a set errors
type Group struct {
prefix string
mu sync.Mutex
errs []error
}
// New creates a new error
var New = errors.New
// NewGroup given a prefix will return an Group with the given prefix.
// Group formats errors like so;
//
// {prefix}: {err msg}
func NewGroup(prefix string) *Group {
return &Group{
prefix: prefix,
errs: make([]error, 0),
}
}
// Add adds a given error to the Group
func (g *Group) Add(err error) *Group {
if err != nil {
g.mu.Lock()
g.errs = append(g.errs, err)
g.mu.Unlock()
}
return g
}
// Newf creates a new error with formatting and adds the new error to the Group
func (g *Group) Newf(format string, a ...interface{}) *Group {
return g.Add(fmt.Errorf(format, a...))
}
// New creates a new error and adds the new error to the Group
func (g *Group) New(s string) *Group {
return g.Add(errors.New(s))
}
// Errored returns true if an error has been added and false if
// no errors have been added.
func (g *Group) Errored() bool {
if g == nil {
panic("group is nil")
}
if len(g.errs) < 1 {
return false
}
for _, child := range g.errs {
switch err := child.(type) {
case *Group:
if err.Errored() {
return true
}
default:
return true
}
}
return false
}
// Error implements the error interface
func (g *Group) Error() string {
buf := bytes.NewBuffer(nil)
g.printError(buf, []string{})
x := buf.String()
if strings.HasSuffix(x, "\n") {
return x[:len(x)-1]
}
return x
}
func (g *Group) printError(w io.Writer, prefixes []string) {
for i, err := range g.errs {
padding := strings.Join(append(prefixes, g.prefix), ": ")
spacePadding := strings.Repeat(" ", len(padding))
switch x := err.(type) {
case *Group:
x.printError(w, append(prefixes, g.prefix))
case error:
a := strings.Split(err.Error(), "\n")
for j, line := range a {
sep := ":"
p := padding
if i == 0 {
// no op
} else {
switch g.errs[i-1].(type) {
case *Group:
// no op
default:
sep = " "
p = spacePadding
}
}
if j > 0 {
sep = "⮎"
p = spacePadding
}
fmt.Fprintf(w, "%s%s %s\n", p, sep, line)
}
}
}
}