forked from danielgtaylor/openapi-cli-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.go
103 lines (88 loc) · 2.19 KB
/
input.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
package cli
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/glenroy37/openapi-cli-generator/shorthand"
"github.com/rs/zerolog/log"
yaml "gopkg.in/yaml.v2"
)
// DeepAssign recursively merges a source map into the target.
func DeepAssign(target, source map[string]interface{}) {
for k, v := range source {
if vm, ok := v.(map[string]interface{}); ok {
if _, ok := target[k]; ok {
if tkm, ok := target[k].(map[string]interface{}); ok {
DeepAssign(tkm, vm)
} else {
target[k] = vm
}
} else {
target[k] = vm
}
} else {
target[k] = v
}
}
}
// GetBody returns the request body if one was passed either as shorthand
// arguments or via stdin.
func GetBody(mediaType string, args []string) (string, error) {
var body string
info, err := os.Stdin.Stat()
if err != nil {
return "", err
}
if (info.Mode() & os.ModeCharDevice) == 0 {
// Data is available on stdin
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return "", err
}
body = string(input)
log.Debug().Msgf("Body from stdin is: %s", body)
}
if len(args) > 0 {
bodyInput := strings.Join(args, " ")
result, err := shorthand.ParseAndBuild("stdin", bodyInput)
if err != nil {
return "", err
}
if strings.Contains(mediaType, "json") {
if body != "" {
// Have a body from stdin. Should be JSON, so let's merge.
var curBody map[string]interface{}
if err := json.Unmarshal([]byte(body), &curBody); err != nil {
return "", err
}
DeepAssign(curBody, result)
result = curBody
}
marshalled, err := json.Marshal(result)
if err != nil {
return "", err
}
body = string(marshalled)
} else if strings.Contains(mediaType, "yaml") {
if body != "" {
// Have a body from stdin. Should be YAML, so let's merge.
var curBody map[string]interface{}
if err := yaml.Unmarshal([]byte(body), &curBody); err != nil {
return "", err
}
DeepAssign(curBody, result)
result = curBody
}
marshalled, err := yaml.Marshal(result)
if err != nil {
return "", err
}
body = string(marshalled)
} else {
return "", fmt.Errorf("Not sure how to marshal %s", mediaType)
}
}
return body, nil
}