diff --git a/README.md b/README.md index bc6ec43..f532732 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,8 @@ part 1 of 13 (tokens 0–6,000 of ~75,000). next: string fetch https://en.wikipe The parts after the first come from a local copy that the first part saves for 15 minutes, under `$XDG_CACHE_HOME/string/fetch` or `~/.cache/string/fetch`. They send no request and cost nothing, keyless allowance included. +A field that only comes back in JSON, such as `--jsonSchema` or `--screenshot`, needs JSON output. With `--format markdown` or `--format raw` it exits 2 and says so, where the field used to be dropped without a word. For `request`, `--body-file -` reads the body from stdin. `--body` sends its text as written, so `--body @order.json` warns when `order.json` is a file, since `--body-file order.json` was likely meant. + A bare domain works too: `string example.com` fetches `https://example.com`. When `fetch`, `request` or `sitemap submit` gets a URL with no scheme, it uses `https://` and says so on stderr. **Every API field is a flag of the same name.** A field from the [API reference](https://docs.usestring.ai/api-reference/fetch) works on the command line as written: `executeJS` is `--executeJS`, and `countryCode` is `--countryCode DE`. A boolean flag alone is true, and `=false` turns it off (`--solveCaptcha=false`). An object or array field takes JSON, or `@` and a file path (`--jsonSchema @./schema.json`). `string fetch --help`, `string search --help` and `string sitemap --help` list each command's fields. Every flag of more than one word also takes its kebab-case and snake_case spellings, so `--main-content-only` and `--main_content_only` are `--mainContentOnly`, and `--envFile` is `--env-file`. A near miss of a flag, such as `--mainContentOnyl`, gets the right name back, and so does a near miss of a command, or a word other tools use for one: `string scrape URL` answers `Did you mean fetch?` with `string fetch URL` as the next step, and exits 2 without running it. diff --git a/cmd/string/help.go b/cmd/string/help.go index 285c301..8a68de8 100644 --- a/cmd/string/help.go +++ b/cmd/string/help.go @@ -195,8 +195,8 @@ var commandDocs = map[string]commandDoc{ }, returns: append([]string{"stdout the response as JSON"}, exitsOfARequest...), cost: "Needs a key. Prices: https://docs.usestring.ai/get-started/pricing", - flags: ` --body TEXT the request body, as written - --body-file FILE the request body, read from FILE + flags: ` --body TEXT the request body, as written, @ included + --body-file FILE the request body, read from FILE, or - for stdin ` + outputFlags, fields: " The same as string fetch: string fetch --help.\n", more: "https://docs.usestring.ai/api-reference/fetch", diff --git a/cmd/string/input_fixes_test.go b/cmd/string/input_fixes_test.go new file mode 100644 index 0000000..e21f63d --- /dev/null +++ b/cmd/string/input_fixes_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +// A field only JSON carries, asked for with another format, exits 2 with the +// fix, where it used to be dropped without a word. +func TestAJSONOnlyFieldNeedsJSON(t *testing.T) { + for list, want := range map[string]string{ + `fetch https://example.com --jsonSchema {} --format markdown`: "error: --jsonSchema comes back only in JSON, so --format markdown would lose it; drop --format, or use --format json\n", + `fetch https://example.com --screenshot --format raw`: "error: --screenshot comes back only in JSON, so --format raw would lose it; drop --format, or use --format json\n", + `request POST https://example.com --captureCookies --format markdown`: "error: --captureCookies comes back only in JSON, so --format markdown would lose it; drop --format, or use --format json\n", + } { + if got := runOffline(t, strings.Fields(list)...); got.status != exitUsage || got.errors != want { + t.Errorf("string %s: %+v, want %q", list, got, want) + } + } + base, _ := fetchAPI(t, `{"statusCode":200}`) + if got := runAs(base, execCtx{}, "fetch", "https://example.com", "--jsonSchema", "{}", "--format", "json"); got.status != 0 { + t.Errorf("--jsonSchema --format json: %+v", got) + } +} + +// --body-file - reads the body from stdin, and --body @FILE warns when FILE +// exists, since --body sends its text as written. +func TestRequestBodiesFromStdinAndTheAtWarning(t *testing.T) { + var mu sync.Mutex + var sent []string + base := api(t, func(w http.ResponseWriter, r *http.Request) { + var body struct { + Body string `json:"body"` + } + json.NewDecoder(r.Body).Decode(&body) + mu.Lock() + sent = append(sent, body.Body) + mu.Unlock() + io.WriteString(w, `{"statusCode":200}`) + }) + request := func(stdin string, list ...string) result { + var stdout, stderr bytes.Buffer + status := run(append([]string{"request", "POST", "https://example.com/orders"}, list...), runtime{env: envOf(map[string]string{"STRING_API_KEY": "test-key", "STRING_API_BASE_URL": base}), client: http.DefaultClient, stdin: strings.NewReader(stdin), stdout: &stdout, stderr: &stderr}) + return result{status, stdout.String(), stderr.String()} + } + if got := request(`{"sku":"A1"}`, "--body-file", "-"); got.status != 0 || got.errors != "" || len(sent) != 1 || sent[0] != `{"sku":"A1"}` { + t.Errorf("--body-file -: %+v, sent %q", got, sent) + } + if got := request("{}", "--input", "-", "--body-file", "-"); got.status != exitUsage || got.errors != "error: Only one of --input - and --body-file - can read stdin\n" { + t.Errorf("--input - --body-file -: %+v", got) + } + + dir := t.TempDir() + order := filepath.Join(dir, "order.json") + if err := os.WriteFile(order, []byte(`{"sku":"A1"}`), 0o600); err != nil { + t.Fatal(err) + } + sent = nil + if got := request("", "--body", "@"+order); got.status != 0 || got.errors != "warning: --body @"+order+" sends the text @"+order+"; did you mean --body-file "+order+"?\n" || sent[0] != "@"+order { + t.Errorf("--body @FILE: %+v, sent %q", got, sent) + } + if got := request("", "--body", "@"+filepath.Join(dir, "missing.json")); got.status != 0 || got.errors != "" { + t.Errorf("--body @MISSING: %+v", got) + } +} diff --git a/cmd/string/run.go b/cmd/string/run.go index 920e62f..fa375f1 100644 --- a/cmd/string/run.go +++ b/cmd/string/run.go @@ -650,10 +650,21 @@ func fetchFormat(value string) (string, error) { } func formatFor(body map[string]any, fallback string) (string, error) { - if format := field(body, "format"); format != nil { - return fetchFormat(jsString(format)) + format := field(body, "format") + if format == nil { + return fallback, nil } - return fallback, nil + chosen, err := fetchFormat(jsString(format)) + if err != nil || chosen == "json" { + return chosen, err + } + // A field that only JSON carries would be dropped from any other format. + for _, name := range jsonOnlyFields { + if jsTruthy(field(body, name)) { + return "", fmt.Errorf("--%s comes back only in JSON, so --format %s would lose it; drop --format, or use --format json", name, chosen) + } + } + return chosen, nil } // jsonOnlyFields come back only in a JSON response. @@ -881,12 +892,28 @@ func requestCommand(list []string, stdin io.Reader) (*operation, error) { if hasText && hasFile { return nil, errors.New("Use only one of --body and --body-file") } + if input, _ := parsed.value("input"); input == "-" && file == "-" { + return nil, errors.New("Only one of --input - and --body-file - can read stdin") + } + // --body is sent as written, even when it starts with @, but @ and a + // file that exists most likely meant --body-file. + var warning string + if name, ok := strings.CutPrefix(text, "@"); hasText && ok && name != "" { + if info, err := os.Stat(name); err == nil && !info.IsDir() { + warning = fmt.Sprintf("warning: --body %s sends the text %s; did you mean --body-file %s?", text, text, name) + } + } body, err := requestFields(parsed, stdin) if err != nil { return nil, err } if hasFile { - contents, err := os.ReadFile(file) + var contents []byte + if file == "-" { + contents, err = io.ReadAll(stdin) + } else { + contents, err = os.ReadFile(file) + } if err != nil { return nil, err } @@ -900,6 +927,8 @@ func requestCommand(list []string, stdin io.Reader) (*operation, error) { if err != nil { return nil, err } + note = strings.TrimPrefix(note+"\n"+warning, "\n") + note = strings.TrimSuffix(note, "\n") body["url"], body["method"], body["format"] = target, method, format if hasText { body["body"] = text