-
Notifications
You must be signed in to change notification settings - Fork 0
/
curly.go
312 lines (245 loc) · 6.12 KB
/
curly.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package main
import (
"bufio"
"bytes"
"embed"
_ "embed"
"fmt"
"github.com/dop251/goja"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
"github.com/urfave/cli/v2"
"go/format"
"os"
"sort"
"strings"
"text/template"
"time"
)
type Options struct {
NumReqs int
ConcurrentReqs int
SleepDuration time.Duration
IsDump bool
}
//go:embed js/json-to-go.js js/curl-to-go.js js/url-search-params.js
var js embed.FS
//go:embed templates/request.tmpl
var tpl embed.FS
// version will be overridden by build
var version = "latest"
func main() {
app := createApp()
if err := app.Run(os.Args); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func createApp() *cli.App {
opts := Options{}
return &cli.App{
Name: "curly",
Version: version,
Usage: "Converts cURL command from STDIN to golang code and executes it",
UsageText: `curly [-h|--help] [-v|--version] [-r <value>] [-c <value>] [-s <value>] [-d] <command> [<args>]`,
Authors: []*cli.Author{
{
Name: "m1x0n",
Email: "[email protected]",
},
},
CustomAppHelpTemplate: getHelpTemplate(),
Flags: []cli.Flag{
&cli.IntFlag{
Name: "r",
Value: 1,
Usage: "Number of requests",
Destination: &opts.NumReqs,
},
&cli.IntFlag{
Name: "c",
Value: 1,
Usage: "Number of concurrent requests",
Destination: &opts.ConcurrentReqs,
},
&cli.DurationFlag{
Name: "s",
Value: 0,
Usage: "Sleep duration",
Destination: &opts.SleepDuration,
},
&cli.BoolFlag{
Name: "d",
Value: false,
Usage: "Dump generated golang code",
Destination: &opts.IsDump,
},
},
Action: func(cCtx *cli.Context) error {
return runCurly(&opts)
},
}
}
func runCurly(opts *Options) error {
// Grab curl from stdin
curlString, err := readCurl()
if err != nil {
return err
}
// Read aux js functions
scripts, err := readScripts()
if err != nil {
return err
}
// Execute curl2Go with curlString on v8 engine
goString, err := executeOnGoja(curlString, scripts...)
if err != nil {
return err
}
if len(goString) == 0 || goString == "undefined" {
return fmt.Errorf("failed to convert curl properly")
}
// Make code ready to execute standalone
goCode, err := normalizeGoCode(goString, opts)
if err != nil {
return err
}
// Beautify generated code
goCode, err = beautifyGoCode(goCode)
if err != nil {
return err
}
if opts.IsDump {
fmt.Println(goCode)
return nil
}
// Execute(interpret) generated go code in go via
err = executeOnYaegi(goCode)
return err
}
func readCurl() (string, error) {
data := strings.Builder{}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
data.WriteString(scanner.Text())
data.WriteString("\n")
}
return data.String(), nil
}
func readScripts() ([]string, error) {
files := []string{
"js/json-to-go.js",
"js/curl-to-go.js",
"js/url-search-params.js",
}
content := make([]string, 0)
for _, file := range files {
scriptContent, err := js.ReadFile(file)
if err != nil {
return nil, err
}
content = append(content, string(scriptContent))
}
return content, nil
}
// Turns out it requires some not implemented feature by this engine. Silent error in v8go
// ReferenceError: URLSearchParams is not defined at renderComplex (<eval>:252:24(130))
// So we need polyfills for this class.
// It's working with polyfill for URLSearchParams!
func executeOnGoja(curl string, scripts ...string) (string, error) {
vm := goja.New()
// Load scripts to the main context
for _, script := range scripts {
_, err := vm.RunString(script)
if err != nil {
return "", err
}
}
// Get curl2GoFn callable from VM
curlToGoFn, isOk := goja.AssertFunction(vm.Get("curlToGo"))
if !isOk {
return "", fmt.Errorf("goja: Failed to locate curlToGo() function in global VM context")
}
result, err := curlToGoFn(goja.Undefined(), vm.ToValue(curl))
if err != nil {
return "", err
}
return result.String(), nil
}
func executeOnYaegi(code string) error {
i := interp.New(interp.Options{})
var err error
err = i.Use(stdlib.Symbols)
if err != nil {
return err
}
_, err = i.Eval(code)
return err
}
func normalizeGoCode(code string, opts *Options) (string, error) {
t, err := template.ParseFS(tpl, "templates/request.tmpl")
if err != nil {
return "", err
}
var result bytes.Buffer
// Data for template must be a struct/map
data := map[string]interface{}{
"code": code,
"imports": getImports(code),
"opts": opts,
}
err = t.Execute(&result, data)
if err != nil {
return "", err
}
return result.String(), nil
}
func beautifyGoCode(code string) (string, error) {
//1. Replace '// handle err'
beautified := strings.ReplaceAll(code, "// handle err", "fmt.Println(err)\n\treturn")
// 2. Apply go format
formatted, err := format.Source([]byte(beautified))
if err != nil {
return "", err
}
return string(formatted), nil
}
func getImports(code string) []string {
imports := []string{
"net/http",
"io",
"fmt",
"sync",
"time",
}
patternMap := map[string][]string{
"application/json": {"encoding/json", "bytes"},
"url.Values{}": {"net/url"},
"strings.NewReader": {"strings"},
"os.Open": {"os"},
"io.MultiReader": {"io"},
"tls.Config": {"crypto/tls"},
}
for pattern, importList := range patternMap {
if strings.Contains(code, pattern) {
imports = append(imports, importList...)
}
}
sort.Strings(imports)
return imports
}
func getHelpTemplate() string {
examples := `
EXAMPLES:
1. Read cURL command and run it via curly with default params:
echo "curl -X GET https://example.com" | curly
2. Read cURL command and dump generated go code without execution:
echo "curl -X GET https://example.com" | curly -d
3. Read cURL command from clipboard and run generated code in 50 requests with 5 concurrency:
xclip -o | curly -r 50 -c 5
4. Read cURL command from file and run generated code in 10 requests with 1 concurrency and
sleep duration of 1 second:
cat curl.txt | curly -r 10 -s 1s
`
return fmt.Sprintf("%s %s", cli.AppHelpTemplate, examples)
}