forked from Gitlink/gitlink-cli
Merge PR #234: feat(api): 增强单次调用模板变量与预演能力
# Conflicts: # cmd/api/api.go # cmd/api/api_test.go # doc/changes/api-single-request-templates.md
This commit is contained in:
commit
55e0e1b32c
14
README.md
14
README.md
|
|
@ -724,6 +724,20 @@ Get-Content issue.json | gitlink-cli api POST /Gitlink/forgeplus/issues --body-s
|
|||
|
||||
# With query parameters
|
||||
gitlink-cli api GET /Gitlink/forgeplus/commits --query 'page=1&limit=5'
|
||||
|
||||
# Render owner/repo from git context or explicit variables
|
||||
gitlink-cli api POST /:owner/:repo/issues --body '{"subject":"Bug","description":"..."}'
|
||||
|
||||
# Reuse template variables in a single request
|
||||
gitlink-cli api POST /v1/{{owner}}/{{repo}}/issues/{{number}}/journals \
|
||||
--body '{"notes":"handled by {{actor}}"}' \
|
||||
--var owner=Gitlink --var repo=gitlink-cli --var number=42 --var actor=bot
|
||||
|
||||
# Preview a rendered single request without sending it
|
||||
gitlink-cli api POST /v1/{{owner}}/{{repo}}/issues \
|
||||
--body-file issue.json \
|
||||
--var owner=Gitlink --var repo=gitlink-cli \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
## Global Parameters
|
||||
|
|
|
|||
|
|
@ -588,6 +588,20 @@ Get-Content issue.json | gitlink-cli api POST /Gitlink/forgeplus/issues --body-s
|
|||
|
||||
# 带查询参数
|
||||
gitlink-cli api GET /Gitlink/forgeplus/commits --query 'page=1&limit=5'
|
||||
|
||||
# 从 git 上下文或显式 owner/repo 渲染路径占位符
|
||||
gitlink-cli api POST /:owner/:repo/issues --body '{"subject":"Bug","description":"..."}'
|
||||
|
||||
# 在单次请求中复用模板变量
|
||||
gitlink-cli api POST /v1/{{owner}}/{{repo}}/issues/{{number}}/journals \
|
||||
--body '{"notes":"handled by {{actor}}"}' \
|
||||
--var owner=Gitlink --var repo=gitlink-cli --var number=42 --var actor=bot
|
||||
|
||||
# 先预览渲染后的单次请求,再决定是否真正发送
|
||||
gitlink-cli api POST /v1/{{owner}}/{{repo}}/issues \
|
||||
--body-file issue.json \
|
||||
--var owner=Gitlink --var repo=gitlink-cli \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
## 全局参数
|
||||
|
|
|
|||
327
cmd/api/api.go
327
cmd/api/api.go
|
|
@ -5,17 +5,16 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/gitlink-org/gitlink-cli/cmd/cmdutil"
|
||||
"github.com/gitlink-org/gitlink-cli/internal/client"
|
||||
gitcontext "github.com/gitlink-org/gitlink-cli/internal/context"
|
||||
repoContext "github.com/gitlink-org/gitlink-cli/internal/context"
|
||||
"github.com/gitlink-org/gitlink-cli/internal/i18n"
|
||||
"github.com/gitlink-org/gitlink-cli/internal/output"
|
||||
)
|
||||
|
|
@ -32,8 +31,9 @@ func NewAPICmd(translators ...*i18n.Translator) *cobra.Command {
|
|||
Example: ` gitlink-cli api GET /users/me
|
||||
gitlink-cli api GET /projects --query 'page=1&limit=10'
|
||||
gitlink-cli api POST /:owner/:repo/issues --body '{"subject":"Bug","description":"..."}'
|
||||
gitlink-cli api GET /{{owner}}/{{repo}}/pulls --var owner=Gitlink --var repo=gitlink-cli
|
||||
gitlink-cli api POST /:owner/:repo/issues --body-file issue.json
|
||||
gitlink-cli api POST /v1/{{owner}}/{{repo}}/issues/{{number}}/journals --body '{"notes":"handled by {{actor}}"}' --var owner=Gitlink --var repo=gitlink-cli --var number=42 --var actor=bot
|
||||
gitlink-cli api POST /v1/{{owner}}/{{repo}}/issues --body-file issue.json --var owner=Gitlink --var repo=gitlink-cli --dry-run
|
||||
gitlink-cli api --batch-file plan.json --dry-run
|
||||
gitlink-cli api --batch-file plan.json --var owner=Gitlink --var repo=gitlink-cli`,
|
||||
Args: validateAPIArgs,
|
||||
|
|
@ -71,28 +71,18 @@ func runAPI(c *cobra.Command, args []string) error {
|
|||
}
|
||||
|
||||
method := strings.ToUpper(args[0])
|
||||
path := args[1]
|
||||
|
||||
body, err := readJSONBody(c)
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
|
||||
vars, err := parseBatchVars(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var query url.Values
|
||||
queryStr, _ := c.Flags().GetString("query")
|
||||
if queryStr != "" {
|
||||
var err error
|
||||
query, err = url.ParseQuery(queryStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid query string: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
headers, err := parseAPIHeaders(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
request, err := renderSingleAPIRequest(args[1], query, body, headers, c)
|
||||
addRepoContextVars(vars)
|
||||
path, err = renderSinglePath(path, vars)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -103,7 +93,33 @@ func runAPI(c *cobra.Command, args []string) error {
|
|||
}
|
||||
cli.Debug = cmdutil.Debug
|
||||
|
||||
env, err := cli.DoWithHeaders(method, request.Path, request.Body, request.Query, request.Headers)
|
||||
body, err := readJSONBody(c, vars)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var query url.Values
|
||||
queryStr, _ := c.Flags().GetString("query")
|
||||
if queryStr != "" {
|
||||
query, err = renderSingleQuery(queryStr, vars)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
dryRun, _ := c.Flags().GetBool("dry-run")
|
||||
if dryRun {
|
||||
return output.Print(output.SuccessEnvelope(map[string]interface{}{
|
||||
"dry_run": true,
|
||||
"method": method,
|
||||
"path": path,
|
||||
"query": query,
|
||||
"body": body,
|
||||
"variables": sortedVars(vars),
|
||||
}, nil), resolveFormat())
|
||||
}
|
||||
|
||||
env, err := cli.Do(method, path, body, query)
|
||||
if err != nil {
|
||||
var apiErr *client.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
|
|
@ -116,7 +132,7 @@ func runAPI(c *cobra.Command, args []string) error {
|
|||
return output.Print(env, resolveFormat())
|
||||
}
|
||||
|
||||
func readJSONBody(c *cobra.Command) (interface{}, error) {
|
||||
func readJSONBody(c *cobra.Command, vars map[string]string) (interface{}, error) {
|
||||
bodyStr, _ := c.Flags().GetString("body")
|
||||
bodyFile, _ := c.Flags().GetString("body-file")
|
||||
bodyStdin, _ := c.Flags().GetBool("body-stdin")
|
||||
|
|
@ -156,7 +172,64 @@ func readJSONBody(c *cobra.Command) (interface{}, error) {
|
|||
if err := json.Unmarshal(data, &body); err != nil {
|
||||
return nil, fmt.Errorf("invalid JSON body: %w", err)
|
||||
}
|
||||
return body, nil
|
||||
rendered, err := renderBatchValue(body, vars)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render JSON body: %w", err)
|
||||
}
|
||||
return rendered, nil
|
||||
}
|
||||
|
||||
func renderSinglePath(path string, vars map[string]string) (string, error) {
|
||||
rendered, err := renderTemplate(rewriteColonPlaceholders(path), vars)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("render path: %w", err)
|
||||
}
|
||||
return rendered, nil
|
||||
}
|
||||
|
||||
func renderSingleQuery(raw string, vars map[string]string) (url.Values, error) {
|
||||
rendered, err := renderTemplate(raw, vars)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render query: %w", err)
|
||||
}
|
||||
query, err := url.ParseQuery(rendered)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid query string: %w", err)
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
||||
func addRepoContextVars(vars map[string]string) {
|
||||
if vars == nil {
|
||||
return
|
||||
}
|
||||
if vars["owner"] != "" && vars["repo"] != "" {
|
||||
return
|
||||
}
|
||||
owner, repo, err := repoContext.ResolveOwnerRepo(cmdutil.Owner, cmdutil.Repo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if vars["owner"] == "" {
|
||||
vars["owner"] = owner
|
||||
}
|
||||
if vars["repo"] == "" {
|
||||
vars["repo"] = repo
|
||||
}
|
||||
}
|
||||
|
||||
func rewriteColonPlaceholders(path string) string {
|
||||
return colonPathVarPattern.ReplaceAllString(path, `$1{{$2}}`)
|
||||
}
|
||||
|
||||
var colonPathVarPattern = templatePattern
|
||||
|
||||
func init() {
|
||||
colonPathVarPattern = mustCompileColonPattern()
|
||||
}
|
||||
|
||||
func mustCompileColonPattern() *regexp.Regexp {
|
||||
return regexp.MustCompile(`(^|/):([A-Za-z0-9_.-]+)`)
|
||||
}
|
||||
|
||||
func resolveFormat() string {
|
||||
|
|
@ -166,207 +239,3 @@ func resolveFormat() string {
|
|||
}
|
||||
return f
|
||||
}
|
||||
|
||||
type singleAPIRequest struct {
|
||||
Path string
|
||||
Query url.Values
|
||||
Body interface{}
|
||||
Headers http.Header
|
||||
}
|
||||
|
||||
func renderSingleAPIRequest(path string, query url.Values, body interface{}, headers http.Header, c *cobra.Command) (*singleAPIRequest, error) {
|
||||
normalizedPath := normalizeSingleAPIPath(path)
|
||||
if !strings.HasPrefix(normalizedPath, "/") {
|
||||
normalizedPath = "/" + normalizedPath
|
||||
}
|
||||
|
||||
vars, err := resolveSingleRequestVars(c, normalizedPath, query, body, headers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
renderedPath, err := renderTemplate(normalizedPath, vars)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render path: %w", err)
|
||||
}
|
||||
renderedQuery, err := renderURLValues(query, vars)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render query: %w", err)
|
||||
}
|
||||
renderedBody, err := renderBatchValue(body, vars)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render body: %w", err)
|
||||
}
|
||||
renderedHeaders, err := renderAPIHeaders(headers, vars)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render headers: %w", err)
|
||||
}
|
||||
|
||||
return &singleAPIRequest{
|
||||
Path: renderedPath,
|
||||
Query: renderedQuery,
|
||||
Body: renderedBody,
|
||||
Headers: renderedHeaders,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func normalizeSingleAPIPath(path string) string {
|
||||
return strings.NewReplacer(":owner", "{{owner}}", ":repo", "{{repo}}").Replace(strings.TrimSpace(path))
|
||||
}
|
||||
|
||||
func resolveSingleRequestVars(c *cobra.Command, path string, query url.Values, body interface{}, headers http.Header) (map[string]string, error) {
|
||||
vars, err := parseBatchVars(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !needsOwnerRepoResolution(path, query, body, headers, vars) {
|
||||
return vars, nil
|
||||
}
|
||||
owner, repo, err := gitcontext.ResolveOwnerRepo(cmdutil.Owner, cmdutil.Repo)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve owner/repo for api templates: %w", err)
|
||||
}
|
||||
if _, ok := vars["owner"]; !ok {
|
||||
vars["owner"] = owner
|
||||
}
|
||||
if _, ok := vars["repo"]; !ok {
|
||||
vars["repo"] = repo
|
||||
}
|
||||
return vars, nil
|
||||
}
|
||||
|
||||
func needsOwnerRepoResolution(path string, query url.Values, body interface{}, headers http.Header, vars map[string]string) bool {
|
||||
if vars["owner"] != "" && vars["repo"] != "" {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(path, "{{owner}}") || strings.Contains(path, "{{repo}}") {
|
||||
return true
|
||||
}
|
||||
for key, values := range query {
|
||||
if strings.Contains(key, "{{owner}}") || strings.Contains(key, "{{repo}}") {
|
||||
return true
|
||||
}
|
||||
for _, value := range values {
|
||||
if strings.Contains(value, "{{owner}}") || strings.Contains(value, "{{repo}}") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
if containsTemplateVar(body, "owner", "repo") {
|
||||
return true
|
||||
}
|
||||
for key, values := range headers {
|
||||
if strings.Contains(key, "{{owner}}") || strings.Contains(key, "{{repo}}") {
|
||||
return true
|
||||
}
|
||||
for _, value := range values {
|
||||
if strings.Contains(value, "{{owner}}") || strings.Contains(value, "{{repo}}") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func containsTemplateVar(value interface{}, names ...string) bool {
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return false
|
||||
case string:
|
||||
for _, name := range names {
|
||||
if strings.Contains(typed, "{{"+name+"}}") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
case []interface{}:
|
||||
for _, item := range typed {
|
||||
if containsTemplateVar(item, names...) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
case map[string]interface{}:
|
||||
for key, item := range typed {
|
||||
if containsTemplateVar(key, names...) || containsTemplateVar(item, names...) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func parseAPIHeaders(c *cobra.Command) (http.Header, error) {
|
||||
rawHeaders, _ := c.Flags().GetStringSlice("header")
|
||||
if len(rawHeaders) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
headers := http.Header{}
|
||||
for _, item := range rawHeaders {
|
||||
name, value, ok := strings.Cut(item, ":")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid --header %q, want key:value", item)
|
||||
}
|
||||
name = strings.TrimSpace(name)
|
||||
value = strings.TrimSpace(value)
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("invalid --header %q, header name cannot be empty", item)
|
||||
}
|
||||
headers.Add(name, value)
|
||||
}
|
||||
return headers, nil
|
||||
}
|
||||
|
||||
func renderAPIHeaders(headers http.Header, vars map[string]string) (http.Header, error) {
|
||||
if len(headers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rendered := http.Header{}
|
||||
keys := make([]string, 0, len(headers))
|
||||
for key := range headers {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
renderedKey, err := renderTemplate(key, vars)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, value := range headers.Values(key) {
|
||||
renderedValue, err := renderTemplate(value, vars)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rendered.Add(renderedKey, renderedValue)
|
||||
}
|
||||
}
|
||||
return rendered, nil
|
||||
}
|
||||
|
||||
func renderURLValues(query url.Values, vars map[string]string) (url.Values, error) {
|
||||
if len(query) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rendered := url.Values{}
|
||||
keys := make([]string, 0, len(query))
|
||||
for key := range query {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
renderedKey, err := renderTemplate(key, vars)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, value := range query[key] {
|
||||
renderedValue, err := renderTemplate(value, vars)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rendered.Add(renderedKey, renderedValue)
|
||||
}
|
||||
}
|
||||
return rendered, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,10 +4,8 @@ import (
|
|||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/gitlink-org/gitlink-cli/cmd/cmdutil"
|
||||
|
|
@ -204,104 +202,102 @@ func TestRunAPINoPrefix(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestRunAPISingleRequestTemplatesAndHeaders(t *testing.T) {
|
||||
oldOwner, oldRepo, oldFormat := cmdutil.Owner, cmdutil.Repo, cmdutil.Format
|
||||
cmdutil.Owner = "Gitlink"
|
||||
cmdutil.Repo = "gitlink-cli"
|
||||
cmdutil.Format = "json"
|
||||
t.Cleanup(func() {
|
||||
cmdutil.Owner = oldOwner
|
||||
cmdutil.Repo = oldRepo
|
||||
cmdutil.Format = oldFormat
|
||||
})
|
||||
func TestRunAPIRendersOwnerRepoColonPlaceholders(t *testing.T) {
|
||||
oldOwner, oldRepo := cmdutil.Owner, cmdutil.Repo
|
||||
cmdutil.Owner, cmdutil.Repo = "Gitlink", "gitlink-cli"
|
||||
defer func() {
|
||||
cmdutil.Owner, cmdutil.Repo = oldOwner, oldRepo
|
||||
}()
|
||||
|
||||
var gotBody map[string]interface{}
|
||||
setupAPITest(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/Gitlink/gitlink-cli/issues.json" {
|
||||
t.Fatalf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
if r.URL.Query().Get("state") != "open" {
|
||||
t.Fatalf("state query = %q, want open", r.URL.Query().Get("state"))
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{"ok": true})
|
||||
})
|
||||
cmdutil.Format = "json"
|
||||
|
||||
cmd := NewAPICmd()
|
||||
cmd.SetArgs([]string{"GET", "/:owner/:repo/issues"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("runAPI placeholder error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAPIRendersVarsInQueryAndBody(t *testing.T) {
|
||||
var gotBody map[string]interface{}
|
||||
setupAPITest(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/Gitlink/gitlink-cli/issues/42/journals.json" {
|
||||
t.Fatalf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
if r.URL.Query().Get("repo") != "gitlink-cli" {
|
||||
t.Fatalf("repo query = %q, want gitlink-cli", r.URL.Query().Get("repo"))
|
||||
}
|
||||
if r.Header.Get("X-Repo") != "gitlink-cli" {
|
||||
t.Fatalf("X-Repo = %q, want gitlink-cli", r.Header.Get("X-Repo"))
|
||||
if r.URL.Query().Get("notify") != "true" {
|
||||
t.Fatalf("notify query = %q", r.URL.Query().Get("notify"))
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {
|
||||
t.Fatalf("decode body: %v", err)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{"id": 7})
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{"id": 99})
|
||||
})
|
||||
cmdutil.Format = "json"
|
||||
|
||||
bodyPath := filepath.Join(t.TempDir(), "body.json")
|
||||
if err := os.WriteFile(bodyPath, []byte(`{"notes":"hello {{actor}}","meta":{"repo":"{{repo}}"}}`), 0600); err != nil {
|
||||
t.Fatalf("write body: %v", err)
|
||||
}
|
||||
|
||||
cmd := NewAPICmd()
|
||||
cmd.SetArgs([]string{"POST", "/:owner/:repo/issues"})
|
||||
cmd.Flags().Set("query", "state={{state}}&repo={{repo}}")
|
||||
cmd.Flags().Set("body", `{"subject":"{{title}}","meta":{"owner":"{{owner}}","repo":"{{repo}}"}}`)
|
||||
cmd.Flags().Set("header", "X-Repo: {{repo}}")
|
||||
cmd.Flags().Set("var", "state=open")
|
||||
cmd.Flags().Set("var", "title=Bug report")
|
||||
cmd.SetArgs([]string{
|
||||
"POST", "/v1/{{owner}}/{{repo}}/issues/{{number}}/journals",
|
||||
"--query", "notify={{notify}}",
|
||||
"--body-file", bodyPath,
|
||||
"--var", "owner=Gitlink",
|
||||
"--var", "repo=gitlink-cli",
|
||||
"--var", "number=42",
|
||||
"--var", "notify=true",
|
||||
"--var", "actor=bot",
|
||||
})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("runAPI template error: %v", err)
|
||||
t.Fatalf("runAPI rendered vars error: %v", err)
|
||||
}
|
||||
|
||||
if gotBody["subject"] != "Bug report" {
|
||||
t.Fatalf("subject = %#v, want Bug report", gotBody["subject"])
|
||||
if gotBody["notes"] != "hello bot" {
|
||||
t.Fatalf("notes = %#v", gotBody["notes"])
|
||||
}
|
||||
meta, _ := gotBody["meta"].(map[string]interface{})
|
||||
if meta["owner"] != "Gitlink" || meta["repo"] != "gitlink-cli" {
|
||||
t.Fatalf("meta = %#v", meta)
|
||||
meta := gotBody["meta"].(map[string]interface{})
|
||||
if meta["repo"] != "gitlink-cli" {
|
||||
t.Fatalf("meta.repo = %#v", meta["repo"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderSingleAPIRequestUsesVarsAndOwnerRepo(t *testing.T) {
|
||||
oldOwner, oldRepo := cmdutil.Owner, cmdutil.Repo
|
||||
cmdutil.Owner = "Gitlink"
|
||||
cmdutil.Repo = "gitlink-cli"
|
||||
t.Cleanup(func() {
|
||||
cmdutil.Owner = oldOwner
|
||||
cmdutil.Repo = oldRepo
|
||||
func TestRunAPIDryRunDoesNotReachServer(t *testing.T) {
|
||||
setupAPITest(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("dry-run should not reach server")
|
||||
})
|
||||
cmdutil.Format = "json"
|
||||
|
||||
cmd := NewAPICmd()
|
||||
if err := cmd.Flags().Set("var", "issue=42"); err != nil {
|
||||
t.Fatalf("set var: %v", err)
|
||||
}
|
||||
headers := http.Header{"X-Issue": []string{"{{issue}}"}}
|
||||
query := url.Values{
|
||||
"repo": {"{{repo}}"},
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"notes": "owner={{owner}} issue={{issue}}",
|
||||
}
|
||||
|
||||
req, err := renderSingleAPIRequest("/:owner/:repo/issues/{{issue}}", query, body, headers, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("renderSingleAPIRequest error: %v", err)
|
||||
}
|
||||
if req.Path != "/Gitlink/gitlink-cli/issues/42" {
|
||||
t.Fatalf("Path = %q", req.Path)
|
||||
}
|
||||
if req.Query.Get("repo") != "gitlink-cli" {
|
||||
t.Fatalf("query repo = %q", req.Query.Get("repo"))
|
||||
}
|
||||
if req.Headers.Get("X-Issue") != "42" {
|
||||
t.Fatalf("X-Issue = %q", req.Headers.Get("X-Issue"))
|
||||
}
|
||||
if !reflect.DeepEqual(req.Body, map[string]interface{}{"notes": "owner=Gitlink issue=42"}) {
|
||||
t.Fatalf("Body = %#v", req.Body)
|
||||
cmd.SetArgs([]string{
|
||||
"POST", "/v1/{{owner}}/{{repo}}/issues",
|
||||
"--body", `{"subject":"{{title}}"}`,
|
||||
"--dry-run",
|
||||
"--var", "owner=Gitlink",
|
||||
"--var", "repo=gitlink-cli",
|
||||
"--var", "title=Bug report",
|
||||
})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("runAPI dry-run error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAPIHeadersRejectsInvalidInput(t *testing.T) {
|
||||
func TestRunAPIMissingSingleRequestVar(t *testing.T) {
|
||||
setupAPITest(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("should not reach server")
|
||||
})
|
||||
cmdutil.Format = "json"
|
||||
|
||||
cmd := NewAPICmd()
|
||||
if err := cmd.Flags().Set("header", "broken"); err != nil {
|
||||
t.Fatalf("set header: %v", err)
|
||||
}
|
||||
if _, err := parseAPIHeaders(cmd); err == nil {
|
||||
t.Fatal("expected invalid header error")
|
||||
cmd.SetArgs([]string{"GET", "/v1/{{owner}}/{{repo}}/issues/{{number}}"})
|
||||
if err := cmd.Execute(); err == nil {
|
||||
t.Fatal("expected missing variable error")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,19 @@
|
|||
# Raw API 单次调用模板变量与请求头支持
|
||||
# api 单次调用模板变量与预演能力
|
||||
|
||||
`gitlink-cli api` 的单次调用模式现在和批处理模式对齐了模板渲染能力,不再只能手写完整路径。现在可以直接在路径里使用 `/:owner/:repo`,也可以在 path、query、JSON body、header 中使用 `{{owner}}`、`{{repo}}` 和自定义 `{{var}}` 变量;其中 `owner` / `repo` 会优先读取 `--var`,否则自动复用全局 `--owner`、`--repo` 或当前仓库上下文。
|
||||
这次改动把 `gitlink-cli api` 的单次调用模式和 batch 模式拉齐了。
|
||||
|
||||
这次改动同时把原来声明但未实际生效的 `--header` 接上了。单次请求现在支持通过 `--header key:value` 传递一个或多个自定义请求头,header 名和值都可以参与模板渲染,适合调试网关、透传审计字段、补充实验性接口所需头信息。
|
||||
- 单次调用现在支持 `--var key=value`,可以在路径、查询参数和 JSON 请求体里复用 `{{var}}` 模板变量。
|
||||
- 路径里的 `:owner` 和 `:repo` 会自动使用当前 `--owner` / `--repo` 或 git remote 上下文渲染,修复了单次调用不替换占位符的问题。
|
||||
- `--dry-run` 不再只属于 batch 模式,单次调用也可以先预览渲染后的 method、path、query、body 和 variables,再决定是否真正发请求。
|
||||
|
||||
本次提交补充了路径占位符回归测试、query/body/header 联动渲染测试、非法 header 校验测试,以及自定义 header 真正发到服务端的行为验证。README 和 README.zh-CN 也同步加入了单次请求模板变量示例,方便维护者、脚本和 Agent 直接复用。
|
||||
这样做的目的不是单纯补一个 bug,而是让 Raw API 更适合脚本和 Agent 复用:同一份模板写法既能用在 `api --batch-file`,也能平滑退化成一次性的单条请求。
|
||||
|
||||
本地验证:
|
||||
|
||||
```bash
|
||||
go test ./cmd/api
|
||||
go test ./...
|
||||
go build ./...
|
||||
git diff --check
|
||||
go run . api --help
|
||||
```
|
||||
|
|
|
|||
|
|
@ -127,9 +127,9 @@
|
|||
"error.profile.user_required": "could not determine target user; pass --user or run gitlink-cli auth login",
|
||||
"error.unsupported_language": "unsupported language: {lang}",
|
||||
"flag.api.batch_continue_on_error": "Continue running remaining batch requests after a failure",
|
||||
"flag.api.batch_dry_run": "Preview batch requests without sending remote requests",
|
||||
"flag.api.batch_dry_run": "Preview rendered request(s) without sending remote requests",
|
||||
"flag.api.batch_file": "Read an API batch plan from a JSON file",
|
||||
"flag.api.batch_var": "Override a batch template variable (key=value, repeatable)",
|
||||
"flag.api.batch_var": "Provide a template variable override (key=value, repeatable)",
|
||||
"flag.api.body": "Request body (JSON string)",
|
||||
"flag.api.body_file": "Read request body JSON from a file",
|
||||
"flag.api.body_stdin": "Read request body JSON from stdin",
|
||||
|
|
|
|||
|
|
@ -127,9 +127,9 @@
|
|||
"error.profile.user_required": "无法确定目标用户;请通过 --user 指定,或先运行 gitlink-cli auth login 登录",
|
||||
"error.unsupported_language": "不支持的语言:{lang}",
|
||||
"flag.api.batch_continue_on_error": "批处理请求失败后继续执行后续请求",
|
||||
"flag.api.batch_dry_run": "预览批处理请求,不发送远端请求",
|
||||
"flag.api.batch_dry_run": "预览渲染后的请求,不发送远端请求",
|
||||
"flag.api.batch_file": "从 JSON 文件读取 API 批处理计划",
|
||||
"flag.api.batch_var": "覆盖批处理模板变量(key=value,可重复)",
|
||||
"flag.api.batch_var": "提供模板变量覆盖值(key=value,可重复)",
|
||||
"flag.api.body": "请求体(JSON 字符串)",
|
||||
"flag.api.body_file": "从文件读取 JSON 请求体",
|
||||
"flag.api.body_stdin": "从标准输入读取 JSON 请求体",
|
||||
|
|
|
|||
Loading…
Reference in New Issue