-
Notifications
You must be signed in to change notification settings - Fork 49
/
states.go
71 lines (59 loc) · 1.55 KB
/
states.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
package common
import (
"encoding/json"
)
func getStateMapping() []string {
return []string{"WAITING", "RUNNING", "FINISHED", "FAILED"}
}
type ImageBuildState int
const (
IBWaiting ImageBuildState = iota
IBRunning
IBFinished
IBFailed
)
// CustomJsonConversionError is thrown when parsing strings into enumerations
type CustomJsonConversionError struct {
reason string
}
// Error returns the error as a string
func (err *CustomJsonConversionError) Error() string {
return err.reason
}
// CustomTypeError is thrown when parsing strings into enumerations
type CustomTypeError struct {
reason string
}
// Error returns the error as a string
func (err *CustomTypeError) Error() string {
return err.reason
}
// ToString converts ImageBuildState into a human readable string
func (ibs ImageBuildState) ToString() string {
return getStateMapping()[int(ibs)]
}
func unmarshalStateHelper(data []byte, mapping []string) (int, error) {
var stringInput string
err := json.Unmarshal(data, &stringInput)
if err != nil {
return 0, err
}
for n, str := range mapping {
if str == stringInput {
return n, nil
}
}
return 0, &CustomJsonConversionError{"invalid image build status:" + stringInput}
}
// UnmarshalJSON converts a JSON string into an ImageBuildState
func (ibs *ImageBuildState) UnmarshalJSON(data []byte) error {
val, err := unmarshalStateHelper(data, getStateMapping())
if err != nil {
return err
}
*ibs = ImageBuildState(val)
return nil
}
func (ibs ImageBuildState) MarshalJSON() ([]byte, error) {
return json.Marshal(getStateMapping()[ibs])
}