Skip to content

Commit 016685d

Browse files
committed
Update client agent rewrites to request API
1 parent b582a77 commit 016685d

File tree

3 files changed

+123
-66
lines changed

3 files changed

+123
-66
lines changed

cmd/internal/migrations/v3/client_usage.go

Lines changed: 45 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ var (
2929
headerSetPattern = regexp.MustCompile(`^([ \t]*)(\w+)\.Header\.Set\(([^,]+),\s*([^)]*)\)\s*$`)
3030
requestURIPattern = regexp.MustCompile(`^([ \t]*)(\w+)\.SetRequestURI\((.*)\)\s*$`)
3131
parseCallPattern = regexp.MustCompile(`^([ \t]*)if\s+err\s*:=\s*(\w+)\.Parse\(\);\s*err\s*!=\s*nil\s*{\s*$`)
32-
requestBodyPattern = regexp.MustCompile(`^([ \t]*)(\w+)\.SetBody(?:String)?\((.*)\)\s*$`)
32+
requestBodyPattern = regexp.MustCompile(`^([ \t]*)(\w+)\.(SetBody(?:String)?)\((.*)\)\s*$`)
3333
structAssignPattern = regexp.MustCompile(`^([ \t]*)if\s+([^,]+?)\s*,\s*([^,]+?)\s*,\s*errs\s*([:=]?)=\s*(\w+)\.Struct\((.*)\);\s*len\(errs\)\s*>\s*0\s*{\s*$`)
3434
bytesAssignPattern = regexp.MustCompile(`^([ \t]*)([^,]+),\s*([^,]+),\s*errs\s*(=|:=)\s*(\w+)\.Bytes\(\)\s*$`)
3535
stringAssignPattern = regexp.MustCompile(`^([ \t]*)([^,]+),\s*([^,]+),\s*errs\s*(=|:=)\s*(\w+)\.String\(\)\s*$`)
@@ -175,6 +175,7 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
175175
uriExpr := ""
176176
headers := make(map[string]string)
177177
bodyExpr := ""
178+
bodyIsString := false
178179

179180
j := reqLine + 1
180181
for ; j < len(lines); j++ {
@@ -195,7 +196,8 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
195196
continue
196197
}
197198
if m := requestBodyPattern.FindStringSubmatch(l); len(m) > 0 && m[2] == reqVar {
198-
bodyExpr = strings.TrimSpace(m[3])
199+
bodyExpr = strings.TrimSpace(m[4])
200+
bodyIsString = m[3] == "SetBodyString"
199201
continue
200202
}
201203
if parseCallPattern.MatchString(l) {
@@ -275,8 +277,6 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
275277
structMatch := structAssignPattern.FindStringSubmatch(lines[structStart])
276278
bytesMatch := bytesAssignPattern.FindStringSubmatch(lines[structStart])
277279
stringMatch := stringAssignPattern.FindStringSubmatch(lines[structStart])
278-
methodName := methodFromExpr(methodExpr)
279-
configLine := buildConfig(headers, bodyExpr)
280280

281281
if len(structMatch) == 0 && len(bytesMatch) == 0 && len(stringMatch) == 0 {
282282
structStart = parseEnd
@@ -286,6 +286,34 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
286286

287287
errName := chooseErrName(out, lines, i)
288288

289+
out = append(out, fmt.Sprintf("%s%s := client.New()", indent, agentVar))
290+
out = append(out, fmt.Sprintf("%s%s := %s.R()", indent, reqVar, agentVar))
291+
if methodExpr != "" {
292+
out = append(out, fmt.Sprintf("%s%s.SetMethod(%s)", indent, reqVar, methodLiteral(methodExpr)))
293+
}
294+
if uriExpr != "" {
295+
out = append(out, fmt.Sprintf("%s%s.SetURL(%s)", indent, reqVar, uriExpr))
296+
}
297+
298+
if len(headers) > 0 {
299+
keys := make([]string, 0, len(headers))
300+
for k := range headers {
301+
keys = append(keys, k)
302+
}
303+
sort.Strings(keys)
304+
for _, k := range keys {
305+
out = append(out, fmt.Sprintf("%s%s.SetHeader(%s, %s)", indent, reqVar, k, headers[k]))
306+
}
307+
}
308+
309+
if bodyExpr != "" {
310+
rawBody := bodyExpr
311+
if bodyIsString {
312+
rawBody = fmt.Sprintf("[]byte(%s)", bodyExpr)
313+
}
314+
out = append(out, fmt.Sprintf("%s%s.SetRawBody(%s)", indent, reqVar, rawBody))
315+
}
316+
289317
switch {
290318
case len(structMatch) > 0 && structMatch[5] == agentVar:
291319
if len(preservedLines) > 0 {
@@ -317,7 +345,7 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
317345
continue
318346
}
319347

320-
respLine := fmt.Sprintf("%sresp, %s %s client.%s(%s%s)", indent, errName, errAssign, methodName, uriExpr, configLine)
348+
respLine := fmt.Sprintf("%sresp, %s %s %s.Send()", indent, errName, errAssign, reqVar)
321349

322350
out = append(out, respLine)
323351
out = append(out, fmt.Sprintf("%sif %s != nil {", parseIndent, errName))
@@ -365,7 +393,7 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
365393
statusDeclared := statusVar != "" && (identifierDeclaredInLines(preservedLines, statusVar) || identifierDeclared(out, lines, i, statusVar))
366394
bodyDeclared := bodyVar != "" && (identifierDeclaredInLines(preservedLines, bodyVar) || identifierDeclared(out, lines, i, bodyVar))
367395

368-
respLine := fmt.Sprintf("%sresp, %s %s client.%s(%s%s)", indent, errName, errAssign, methodName, uriExpr, configLine)
396+
respLine := fmt.Sprintf("%sresp, %s %s %s.Send()", indent, errName, errAssign, reqVar)
369397
out = append(out, respLine)
370398
out = append(out, fmt.Sprintf("%sif %s != nil {", parseIndent, errName))
371399
out = append(out, replaceErrIdentifier(parseBody[:len(parseBody)-1], errName, false)...)
@@ -404,7 +432,7 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
404432
statusDeclared := statusVar != "" && (identifierDeclaredInLines(preservedLines, statusVar) || identifierDeclared(out, lines, i, statusVar))
405433
bodyDeclared := bodyVar != "" && (identifierDeclaredInLines(preservedLines, bodyVar) || identifierDeclared(out, lines, i, bodyVar))
406434

407-
respLine := fmt.Sprintf("%sresp, %s %s client.%s(%s%s)", indent, errName, errAssign, methodName, uriExpr, configLine)
435+
respLine := fmt.Sprintf("%sresp, %s %s %s.Send()", indent, errName, errAssign, reqVar)
408436
out = append(out, respLine)
409437
out = append(out, fmt.Sprintf("%sif %s != nil {", parseIndent, errName))
410438
out = append(out, replaceErrIdentifier(parseBody[:len(parseBody)-1], errName, false)...)
@@ -432,7 +460,7 @@ func rewriteAcquireAgentBlocksWithAlias(content, alias string) (string, bool) {
432460
continue
433461
default:
434462
errAssign := errAssignmentOperator(errName, out, lines, i)
435-
respLine := fmt.Sprintf("%s_, %s %s client.%s(%s%s)", indent, errName, errAssign, methodName, uriExpr, configLine)
463+
respLine := fmt.Sprintf("%s_, %s %s %s.Send()", indent, errName, errAssign, reqVar)
436464
out = append(out, respLine)
437465
out = append(out, fmt.Sprintf("%sif %s != nil {", parseIndent, errName))
438466
out = append(out, replaceErrIdentifier(parseBody[:len(parseBody)-1], errName, false)...)
@@ -620,51 +648,26 @@ func declaredInVarBlockLine(name, trimmed string) bool {
620648
return true
621649
}
622650

623-
func methodFromExpr(expr string) string {
651+
func methodLiteral(expr string) string {
624652
lower := strings.ToLower(expr)
625653
switch {
654+
case strings.Contains(lower, "methodget"):
655+
return "\"GET\""
626656
case strings.Contains(lower, "methodpost"):
627-
return "Post"
657+
return "\"POST\""
628658
case strings.Contains(lower, "methodput"):
629-
return "Put"
659+
return "\"PUT\""
630660
case strings.Contains(lower, "methodpatch"):
631-
return "Patch"
661+
return "\"PATCH\""
632662
case strings.Contains(lower, "methoddelete"):
633-
return "Delete"
663+
return "\"DELETE\""
634664
case strings.Contains(lower, "methodhead"):
635-
return "Head"
665+
return "\"HEAD\""
636666
default:
637-
return "Get"
667+
return expr
638668
}
639669
}
640670

641-
func buildConfig(headers map[string]string, body string) string {
642-
if len(headers) == 0 && body == "" {
643-
return ""
644-
}
645-
646-
var keys []string
647-
for k := range headers {
648-
keys = append(keys, k)
649-
}
650-
sort.Strings(keys)
651-
652-
var parts []string
653-
if len(keys) > 0 {
654-
var headerParts []string
655-
for _, k := range keys {
656-
headerParts = append(headerParts, fmt.Sprintf("%s: %s", k, headers[k]))
657-
}
658-
parts = append(parts, fmt.Sprintf("Header: map[string]string{%s}", strings.Join(headerParts, ", ")))
659-
}
660-
661-
if body != "" {
662-
parts = append(parts, "Body: "+body)
663-
}
664-
665-
return fmt.Sprintf(", client.Config{%s}", strings.Join(parts, ", "))
666-
}
667-
668671
func rewriteClientExamplesWithAlias(content, alias string) (string, bool) {
669672
patterns := buildAliasPatterns(alias)
670673

cmd/internal/migrations/v3/client_usage_internal_test.go

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -65,20 +65,25 @@ func handler(ctx *fiber.Ctx, code string) error {
6565
t map[string]any
6666
)
6767
68-
resp, err := client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?code=%s", code), client.Config{Header: map[string]string{"accept": "application/json"}})
69-
if err != nil {
70-
return err
71-
}
72-
if err == nil {
73-
retCode = resp.StatusCode()
74-
retBody = resp.Body()
75-
err = resp.JSON(&t)
76-
}
77-
if err != nil {
78-
return ctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
79-
"err": err,
80-
})
81-
}
68+
a := client.New()
69+
req := a.R()
70+
req.SetMethod("POST")
71+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?code=%s", code))
72+
req.SetHeader("accept", "application/json")
73+
resp, err := req.Send()
74+
if err != nil {
75+
return err
76+
}
77+
if err == nil {
78+
retCode = resp.StatusCode()
79+
retBody = resp.Body()
80+
err = resp.JSON(&t)
81+
}
82+
if err != nil {
83+
return ctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
84+
"err": err,
85+
})
86+
}
8287
8388
_ = retCode
8489
_ = retBody

cmd/internal/migrations/v3/client_usage_test.go

Lines changed: 59 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,12 @@ func handler(ctx *fiber.Ctx, code string) error {
318318
t map[string]any
319319
)
320320
321-
resp, err := client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?code=%s", code), client.Config{Header: map[string]string{"accept": "application/json"}})
321+
a := client.New()
322+
req := a.R()
323+
req.SetMethod("POST")
324+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?code=%s", code))
325+
req.SetHeader("accept", "application/json")
326+
resp, err := req.Send()
322327
if err != nil {
323328
return err
324329
}
@@ -397,10 +402,15 @@ import (
397402
)
398403
399404
func handler(ctx *fiber.Ctx, code string) error {
405+
a := client.New()
406+
req := a.R()
407+
req.SetMethod("POST")
408+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?code=%s", code))
409+
req.SetHeader("accept", "application/json")
400410
var retCode int
401411
var retBody []byte
402412
var t map[string]any
403-
resp, clientErr := client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?code=%s", code), client.Config{Header: map[string]string{"accept": "application/json"}})
413+
resp, clientErr := req.Send()
404414
if clientErr != nil {
405415
return clientErr
406416
}
@@ -591,7 +601,11 @@ import (
591601
)
592602
593603
func main() {
594-
resp, err := client.Get("https://httpbin.org/json")
604+
a := client.New()
605+
req := a.R()
606+
req.SetMethod("GET")
607+
req.SetURL("https://httpbin.org/json")
608+
resp, err := req.Send()
595609
if err != nil {
596610
panic(err)
597611
}
@@ -671,7 +685,13 @@ import (
671685
)
672686
673687
func main() {
674-
resp, err := client.Post("https://httpbin.org/post", client.Config{Header: map[string]string{"Content-Type": "application/json"}, Body: "{\"demo\":true}"})
688+
a := client.New()
689+
req := a.R()
690+
req.SetMethod("POST")
691+
req.SetURL("https://httpbin.org/post")
692+
req.SetHeader("Content-Type", "application/json")
693+
req.SetRawBody([]byte("{\"demo\":true}"))
694+
resp, err := req.Send()
675695
if err != nil {
676696
panic(err)
677697
}
@@ -1067,7 +1087,12 @@ var (
10671087
)
10681088
10691089
func handler(code string) {
1070-
resp, err := client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code), client.Config{Header: map[string]string{"accept": "application/json"}})
1090+
a := client.New()
1091+
req := a.R()
1092+
req.SetMethod("POST")
1093+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code))
1094+
req.SetHeader("accept", "application/json")
1095+
resp, err := req.Send()
10711096
if err != nil {
10721097
fmt.Printf("could not create HTTP request: %v", err)
10731098
}
@@ -1142,7 +1167,12 @@ var (
11421167
)
11431168
11441169
func handler(code string) {
1145-
_, err := client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code), client.Config{Header: map[string]string{"accept": "application/json"}})
1170+
a := client.New()
1171+
req := a.R()
1172+
req.SetMethod("POST")
1173+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code))
1174+
req.SetHeader("accept", "application/json")
1175+
_, err := req.Send()
11461176
if err != nil {
11471177
log.Errorf("could not create HTTP request: %v", err)
11481178
}
@@ -1203,7 +1233,12 @@ var (
12031233
12041234
func handler(code string) {
12051235
var err error
1206-
_, err = client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code), client.Config{Header: map[string]string{"accept": "application/json"}})
1236+
a := client.New()
1237+
req := a.R()
1238+
req.SetMethod("POST")
1239+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code))
1240+
req.SetHeader("accept", "application/json")
1241+
_, err = req.Send()
12071242
if err != nil {
12081243
panic(err)
12091244
}
@@ -1266,7 +1301,12 @@ var (
12661301
)
12671302
12681303
func handler(code string) {
1269-
_, clientErr := client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code), client.Config{Header: map[string]string{"accept": "application/json"}})
1304+
a := client.New()
1305+
req := a.R()
1306+
req.SetMethod("POST")
1307+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code))
1308+
req.SetHeader("accept", "application/json")
1309+
_, clientErr := req.Send()
12701310
if clientErr != nil {
12711311
log.Errorf("could not create HTTP request: %v", clientErr)
12721312
}
@@ -1330,7 +1370,12 @@ var (
13301370
)
13311371
13321372
func handler(code string) {
1333-
_, err := client.Post(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code), client.Config{Header: map[string]string{"accept": "application/json"}})
1373+
a := client.New()
1374+
req := a.R()
1375+
req.SetMethod("POST")
1376+
req.SetURL(fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", ClientID, ClientSecret, code))
1377+
req.SetHeader("accept", "application/json")
1378+
_, err := req.Send()
13341379
if err != nil {
13351380
fmt.Printf("could not create HTTP request: %v", err)
13361381
}
@@ -1387,7 +1432,11 @@ import (
13871432
func handler(url string) {
13881433
var errs []error
13891434
1390-
_, err := client.Get(url)
1435+
a := client.New()
1436+
req := a.R()
1437+
req.SetMethod("GET")
1438+
req.SetURL(url)
1439+
_, err := req.Send()
13911440
if err != nil {
13921441
errs = append(errs, err)
13931442
}

0 commit comments

Comments
 (0)