Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/openapi/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -417,7 +417,8 @@ func schemaRequested(cmd *cobra.Command, name string) bool {

// requestBodyMediaType returns the media type and definition the CLI will use,
// preferring application/json for backward compatibility and otherwise using
// the first declared media type.
// the first declared media type. Entries with no schema are skipped, so a
// schema-less application/json stub never shadows a real multipart definition.
func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
if rb == nil || rb.Content == nil {
return "", nil
Expand All@@ -426,7 +427,7 @@ func requestBodyMediaType(rb *v3.RequestBody) (string, *v3.MediaType) {
var first *v3.MediaType
for pair := rb.Content.First(); pair != nil; pair = pair.Next() {
mt := pair.Value()
if mt == nil {
if mt == nil || mt.Schema == nil {
continue
}
if pair.Key() == "application/json" {
Expand Down
55 changes: 47 additions & 8 deletions internal/openapi/multipart.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,12 +106,21 @@ func registerMultipartFlags(cmd *cobra.Command, fields []multipartFieldInfo) {
"body": true, "json-body": true, "schema": true, "field": true, "depth": true,
"profile": true, "token": true, "base-url": true, "compact": true, "format": true, "help": true,
}
taken := func(name string) bool {
return reserved[name] || cmd.Flags().Lookup(name) != nil
}
for i := range fields {
field := &fields[i]
flagName := field.FlagName
if reserved[flagName] || cmd.Flags().Lookup(flagName) != nil {
if taken(flagName) {
flagName = "form-" + flagName
}
// Two fields can collide on the same prefixed name. Registering a
// duplicate makes pflag panic, which would take down the whole CLI at
// startup, so keep suffixing until the name is free.
for suffix := 2; taken(flagName); suffix++ {
flagName = fmt.Sprintf("form-%s-%d", field.FlagName, suffix)
}
field.FlagName = flagName

description := field.Description
Expand All@@ -136,6 +145,11 @@ func buildMultipartBody(cmd *cobra.Command, rawBody []byte, bodyProvided bool, f
if err := decoder.Decode(&values); err != nil {
return nil, "", fmt.Errorf("invalid multipart --body JSON: %w", err)
}
// JSON "null" decodes into a nil map, which the flag merge below would
// panic on.
if values == nil {
return nil, "", fmt.Errorf("multipart --body must be a JSON object of field values")
}
}

for _, field := range fields {
Expand DownExpand Up@@ -213,18 +227,41 @@ func parseMultipartFlagValue(field multipartFieldInfo, value string) (interface{
case "number":
return strconv.ParseFloat(value, 64)
case "array", "object":
var parsed interface{}
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, fmt.Errorf("expected JSON %s: %w", field.Type, err)
}
return parsed, nil
return decodeJSONFlagValue(field.Type, value)
default:
return value, nil
}
}

// decodeJSONFlagValue parses a JSON flag value against the field's declared
// type. Decoding into interface{} would accept an object where the schema says
// array and would silently ignore anything after the first value, so the type
// is pinned and the input must end there.
func decodeJSONFlagValue(fieldType, value string) (interface{}, error) {
decoder := json.NewDecoder(strings.NewReader(value))
decoder.UseNumber()

var parsed interface{}
if fieldType == "array" {
var typed []interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON array: %w", err)
}
parsed = typed
} else {
var typed map[string]interface{}
if err := decoder.Decode(&typed); err != nil {
return nil, fmt.Errorf("expected JSON object: %w", err)
}
parsed = typed
}

if err := decoder.Decode(new(json.RawMessage)); err != io.EOF {
return nil, fmt.Errorf("expected a single JSON %s with no trailing data", fieldType)
}
return parsed, nil
}

func writeMultipartValue(writer *multipart.Writer, field multipartFieldInfo, value interface{}) error {
if values, ok := value.([]interface{}); ok && field.Explode {
for _, item := range values {
Expand All@@ -243,6 +280,8 @@ func writeMultipartSingleValue(writer *multipart.Writer, field multipartFieldInf
if !ok {
return fmt.Errorf("multipart file field %q must be a file path", field.Name)
}
// Match --body @path: shells don't expand "~" inside a flag value.
path = expandHome(path)
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening multipart file %q for field %q: %w", path, field.Name, err)
Expand Down
138 changes: 138 additions & 0 deletions internal/openapi/multipart_test.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"github.com/spf13/cobra"
)

const multipartTestSpec = `{
Expand DownExpand Up@@ -289,3 +291,139 @@ func TestGenerateCommands_MultipartBodyPathHint(t *testing.T) {
t.Fatal("executor called for a path-shaped --body")
}
}

// An explicitly empty --body is a body the caller asked for, so it gets the
// "omit the flag" error rather than reaching buildMultipartBody as a bare EOF.
func TestGenerateCommands_MultipartEmptyBodyFlag(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "people.csv")
if err := os.WriteFile(filePath, []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": filePath, "model-id": "model-123", "body": ""} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "--body is empty") {
t.Fatalf("error = %v, want the empty --body message", err)
}
if called {
t.Fatal("executor called for an empty --body")
}
}

// Binary field values expand "~" the same way --body @path does; shells leave
// it alone inside a flag value.
func TestGenerateCommands_MultipartExpandsHomeInFilePath(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if err := os.WriteFile(filepath.Join(home, "people.csv"), []byte("name\nAda\n"), 0o600); err != nil {
t.Fatal(err)
}

var captured APIRequest
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
captured = request
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"file": "~/people.csv", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}
if err := command.RunE(command, nil); err != nil {
t.Fatalf("RunE: %v", err)
}

parts := parseCapturedMultipart(t, captured)
if got := parts["file"]; got.fileName != "people.csv" || len(got.values) != 1 || got.values[0] != "name\nAda\n" {
t.Errorf("file part = %#v", got)
}
}

// JSON "null" decodes into a nil map, which the flag merge would panic on.
func TestGenerateCommands_MultipartRejectsNullBody(t *testing.T) {
called := false
commands, err := GenerateCommands([]byte(multipartTestSpec), func(request APIRequest) error {
called = true
return nil
})
if err != nil {
t.Fatal(err)
}
command := commands[0].Commands()[0]
for flag, value := range map[string]string{"body": "null", "model-id": "model-123"} {
if err := command.Flags().Set(flag, value); err != nil {
t.Fatalf("set --%s: %v", flag, err)
}
}

err = command.RunE(command, nil)
if err == nil || !strings.Contains(err.Error(), "JSON object of field values") {
t.Fatalf("error = %v, want a non-object --body error", err)
}
if called {
t.Fatal("executor called for a null --body")
}
}

func TestParseMultipartFlagValue_ChecksTypeAndTrailingData(t *testing.T) {
array := multipartFieldInfo{Name: "labels", Type: "array"}
object := multipartFieldInfo{Name: "meta", Type: "object"}

if _, err := parseMultipartFlagValue(array, `{"x":1}`); err == nil {
t.Error("an object passed for an array field was accepted")
}
if _, err := parseMultipartFlagValue(object, `["a"]`); err == nil {
t.Error("an array passed for an object field was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a"] trailing`); err == nil {
t.Error("trailing data after an array was accepted")
}
if _, err := parseMultipartFlagValue(array, `["a","b"]`); err != nil {
t.Errorf("valid array rejected: %v", err)
}
}

// Two fields whose flag names collide must not register the same pflag twice —
// pflag panics on a redefinition, taking down the whole CLI at startup.
func TestRegisterMultipartFlags_ResolvesCollisions(t *testing.T) {
command := &cobra.Command{Use: "upload"}
fields := []multipartFieldInfo{
{Name: "body", FlagName: "body"},
{Name: "Body", FlagName: "body"},
{Name: "body_", FlagName: "body"},
}

registerMultipartFlags(command, fields)

seen := map[string]bool{}
for _, field := range fields {
if field.FlagName == "body" {
t.Errorf("field %q kept the reserved --body name", field.Name)
}
if seen[field.FlagName] {
t.Errorf("duplicate flag name %q", field.FlagName)
}
seen[field.FlagName] = true
if command.Flags().Lookup(field.FlagName) == nil {
t.Errorf("flag --%s was not registered", field.FlagName)
}
}
}