/
error_collection.go
117 lines (102 loc) · 2.39 KB
/
error_collection.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
/*
RexRegistry Dataset Delivery
Copyright (C) 2019 Prometheus Research, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package validation
import (
"fmt"
)
type Error struct {
Message string
Record uint32
Column string
}
func (e Error) String() string {
if e.Column != "" {
return fmt.Sprintf(
"Record %d, Column %s: %s",
e.Record,
e.Column,
e.Message,
)
} else if e.Record != 0 {
return fmt.Sprintf("Record %d: %s", e.Record, e.Message)
} else {
return e.Message
}
}
type ErrorCollection struct {
Errors map[string][]Error
}
func (ec ErrorCollection) FileError(
file string,
message string,
params ...interface{},
) {
ec.ValueError(file, 0, "", message, params...)
}
func (ec ErrorCollection) RecordError(
file string,
record uint32,
message string,
params ...interface{},
) {
ec.ValueError(file, record, "", message, params...)
}
func (ec ErrorCollection) ValueError(
file string,
record uint32,
column string,
message string,
params ...interface{},
) {
_, ok := ec.Errors[file]
if !ok {
ec.Errors[file] = make([]Error, 0)
}
ec.Errors[file] = append(
ec.Errors[file],
Error{
Message: fmt.Sprintf(message, params...),
Record: record,
Column: column,
},
)
}
func (ec ErrorCollection) HasErrors() bool {
for file := range ec.Errors {
if ec.FileHasErrors(file) {
return true
}
}
return false
}
func (ec ErrorCollection) FileHasErrors(file string) bool {
errors, ok := ec.Errors[file]
if ok {
return len(errors) > 0
}
return false
}
func (ec ErrorCollection) GetFiles() []string {
files := make([]string, 0, len(ec.Errors))
for file := range ec.Errors {
files = append(files, file)
}
return files
}
func NewErrorCollection() ErrorCollection {
return ErrorCollection{
Errors: make(map[string][]Error),
}
}