This repository has been archived by the owner on Sep 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathparser.go
124 lines (106 loc) · 2.45 KB
/
parser.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
// State Machine Parser
package machine
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/coinbase/step/utils/to"
)
// Takes a file, and a map of Task Function s
func ParseFile(file string) (*StateMachine, error) {
raw, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
json_sm, err := FromJSON(raw)
return json_sm, err
}
func FromJSON(raw []byte) (*StateMachine, error) {
var sm StateMachine
err := json.Unmarshal(raw, &sm)
return &sm, err
}
func (sm *States) UnmarshalJSON(b []byte) error {
// States
var rawStates map[string]*json.RawMessage
err := json.Unmarshal(b, &rawStates)
if err != nil {
return err
}
newStates := States{}
for name, raw := range rawStates {
states, err := unmarshallState(name, raw)
if err != nil {
return err
}
for _, s := range states {
newStates[*s.Name()] = s
}
}
*sm = newStates
return nil
}
type stateType struct {
Type string
}
func unmarshallState(name string, raw_json *json.RawMessage) ([]State, error) {
var err error
// extract type (safer than regex)
var state_type stateType
if err = json.Unmarshal(*raw_json, &state_type); err != nil {
return nil, err
}
var newState State
switch state_type.Type {
case "Pass":
var s PassState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "Task":
var s TaskState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "Choice":
var s ChoiceState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "Wait":
var s WaitState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "Succeed":
var s SucceedState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "Fail":
var s FailState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "Parallel":
var s ParallelState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "Map":
var s MapState
err = json.Unmarshal(*raw_json, &s)
newState = &s
case "TaskFn":
// This is a custom state that adds values to Task to be handled
var s TaskState
err = json.Unmarshal(*raw_json, &s)
// This will inject the Task name into the input
s.Parameters = map[string]interface{}{"Task": name, "Input.$": "$"}
s.Type = to.Strp("Task")
newState = &s
default:
err = fmt.Errorf("Unknown State %q", state_type.Type)
}
// End of loop return error
if err != nil {
return nil, err
}
// Set Name and Defaults
newName := name
newState.SetName(&newName) // Require New Variable Pointer
return []State{newState}, nil
}