diff --git a/README.md b/README.md index f37b5bd..7cc75b9 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ error: Keyless requests can't use mainContentOnly (HTTP 400) next: run `string login` or set STRING_API_KEY ``` -Add `--json` to any command to get the error as one JSON object on stderr instead: +Add `--json` to any command to get the error as one JSON object on stderr instead. `--errors json` does the same and leaves stdout as it is, so `string fetch URL --errors json` still prints Markdown. From 0.4, `--json` on fetch prints a JSON object. 0.3 says so with a notice when it runs, and warns when a fetched site answers 404, 410 or another error, whose exit codes change in 0.4. `string help formatting` lists each change. `STRING_NO_DEPRECATION_WARNINGS=1` silences the notices, and `STRING_COMPAT=0.2` will keep 0.2's behavior: ```json {"error":{"status":429,"code":"keyless_refused","exit_code":3,"message":"…","retryable":false,"retry_after_seconds":3600,"user_action_required":true,"request_id":"…","next_step":"run `string login` or set STRING_API_KEY","next_commands":[{"type":"login","command":"string login","argv":["string","login"]},{"type":"env","why":"set STRING_API_KEY to an API key from https://portal.usestring.ai/api-keys"}],"help_url":"https://usestring.ai/auth.md"}} diff --git a/cmd/string/help.go b/cmd/string/help.go index 0ba6435..6c9ee1c 100644 --- a/cmd/string/help.go +++ b/cmd/string/help.go @@ -503,6 +503,11 @@ Learn more: https://github.com/usestring/cli#errors-and-exit-codes STRING_AUTO_UPDATE 0 turns off the daily update check, and the rewrite of the skill after an update STRING_DOWNLOAD_URL where string update takes releases from, for tests + STRING_NO_DEPRECATION_WARNINGS + 1 silences what string says ahead of a change, such as + the notice for fetch --json + STRING_COMPAT 0.2 will keep 0.2's output and exit codes once 0.4 + changes them, and silences those notices now DO_NOT_TRACK 1 sends String only string's version CI set to anything but false or 0: a CI job, where nobody approves a sign-in and nothing updates itself @@ -541,8 +546,19 @@ keyless allowance, and errors. -o, --output FILE the response goes to FILE instead of stdout --input FILE more request fields, from a JSON object in FILE or - for stdin; flags win over it + --errors json errors as JSON, as --json gives them, with stdout as it + is: Markdown from fetch stays Markdown --format fetch's format: markdown, json or raw +What changes in 0.4, each with its notice or warning in 0.3: + - fetch --json prints a JSON object: markdown, statusCode, finalUrl, + tokens. --errors json keeps Markdown on stdout with JSON errors; + - a fetch whose site answers 404 or 410 exits 8, and another error 6, + with the page still printed; --no-fail keeps exit 0; + - an API 404, such as an unknown job, exits 8, and a request that gets no + answer exits 6. +STRING_COMPAT=0.2 will keep 0.2's behavior for all of them. + Exit codes: string help exit-codes. Learn more: https://github.com/usestring/cli#commands diff --git a/cmd/string/help_topics_test.go b/cmd/string/help_topics_test.go index e70297b..a11f3d1 100644 --- a/cmd/string/help_topics_test.go +++ b/cmd/string/help_topics_test.go @@ -47,7 +47,7 @@ func TestHelpTopics(t *testing.T) { t.Fatal(err) } for _, match := range named.FindAllStringSubmatch(string(data), -1) { - if !strings.Contains(helpTopics["environment"], "\n "+match[1]+" ") { + if !regexp.MustCompile(`\n ` + match[1] + `[ \n]`).MatchString(helpTopics["environment"]) { t.Errorf("%s reads %s, which string help environment doesn't list", file, match[1]) } } diff --git a/cmd/string/migration.go b/cmd/string/migration.go new file mode 100644 index 0000000..8bc135a --- /dev/null +++ b/cmd/string/migration.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + "strconv" +) + +// What 0.3 says ahead of the changes 0.4 makes to fetch, on stderr only. +// STRING_NO_DEPRECATION_WARNINGS=1 silences it, and so does STRING_COMPAT=0.2, +// which keeps 0.2's behavior once 0.4 is out. + +// announcing reports whether string says what changes in 0.4. +func announcing(env func(string) (string, bool)) bool { + compat, _ := env("STRING_COMPAT") + return !switchedOn(env, "STRING_NO_DEPRECATION_WARNINGS") && compat != "0.2" +} + +// fetchJSONNotice is said when fetch runs with --json, whose stdout becomes a +// JSON object in 0.4. +const fetchJSONNotice = `notice: from 0.4, --json on fetch prints a JSON object (markdown, statusCode, finalUrl, tokens). To keep +Markdown on stdout with JSON errors, use --errors json (works now). STRING_COMPAT=0.2 keeps the old behavior. +` + +// siteStatusWarning is said when the site that fetch read answered status, +// as X-Status-Code gives it, and the exit code for that changes in 0.4: a +// missing page exits 8, another error 6. It is empty for any other status. +func siteStatusWarning(status, url string) string { + code, err := strconv.Atoi(status) + switch { + case err != nil || code < 400: + return "" + case code == 404 || code == 410: + return fmt.Sprintf("warning: %s answered %d. From 0.4, string fetch exits 8 for that (target_not_found); --no-fail will keep exit 0.\n", url, code) + } + return fmt.Sprintf("warning: %s answered %d. From 0.4, string fetch exits 6 for that (target_http_error), with the page still printed; --no-fail will keep exit 0.\n", url, code) +} diff --git a/cmd/string/migration_test.go b/cmd/string/migration_test.go new file mode 100644 index 0000000..8fd119f --- /dev/null +++ b/cmd/string/migration_test.go @@ -0,0 +1,82 @@ +package main + +import ( + "bytes" + "io" + "net/http" + "strings" + "testing" +) + +// runFetching runs string against base with the variables in vars and a key. +func runFetching(base string, vars map[string]string, list ...string) result { + vars["STRING_API_KEY"], vars["STRING_API_BASE_URL"] = "test-key", base + var stdout, stderr bytes.Buffer + status := run(list, runtime{env: envOf(vars), client: http.DefaultClient, stdin: strings.NewReader(""), stdout: &stdout, stderr: &stderr}) + return result{status, stdout.String(), stderr.String()} +} + +// --errors json gives JSON errors as --json does, and leaves stdout alone: +// fetch's Markdown stays Markdown. +func TestErrorsJSONLeavesStdoutAlone(t *testing.T) { + failing := false + base := api(t, func(w http.ResponseWriter, r *http.Request) { + if failing { + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, `{"error":"bad url"}`) + return + } + io.WriteString(w, "# Example Domain\n") + }) + for _, list := range [][]string{{"fetch", "https://example.com", "--errors", "json"}, {"--errors=json", "https://example.com"}} { + failing = false + if got := runFetching(base, map[string]string{}, list...); got.status != 0 || got.output != "# Example Domain\n" || got.errors != "" { + t.Errorf("%v: %+v", list, got) + } + failing = true + got := runFetching(base, map[string]string{}, list...) + if envelope := decode(t, got.errors).(map[string]any)["error"].(map[string]any); got.status != exitUsage || envelope["message"] != "bad url" || envelope["exit_code"] != float64(exitUsage) { + t.Errorf("%v failing: %+v", list, got) + } + } + if got := runFetching(base, map[string]string{}, "fetch", "https://example.com", "--errors", "text"); got.status != exitUsage || !strings.HasPrefix(got.errors, "error: bad url (HTTP 400)") { + t.Errorf("--errors text: %+v", got) + } + if got := runOffline(t, "fetch", "https://example.com", "--errors", "xml"); got.status != exitUsage || got.errors != "error: --errors takes json or text, not \"xml\"\n" { + t.Errorf("--errors xml: %+v", got) + } +} + +// fetch --json says once that its stdout changes in 0.4, and a fetch whose +// site answered an error says how its exit code changes. Either can be +// silenced. +func TestFetchSaysWhatChangesIn04(t *testing.T) { + status := "200" + base := api(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Status-Code", status) + io.WriteString(w, "# Example Domain\n") + }) + for _, c := range []struct { + about string + status string + vars map[string]string + list []string + said string + }{ + {"fetch --json", "200", map[string]string{}, []string{"fetch", "https://example.com", "--json"}, fetchJSONNotice}, + {"a URL with --json", "200", map[string]string{}, []string{"--json", "https://example.com"}, fetchJSONNotice}, + {"fetch --errors json", "200", map[string]string{}, []string{"fetch", "https://example.com", "--errors", "json"}, ""}, + {"search --json", "200", map[string]string{}, []string{"search", "coffee", "--json"}, ""}, + {"a missing page", "404", map[string]string{}, []string{"fetch", "https://example.com/gone"}, "warning: https://example.com/gone answered 404. From 0.4, string fetch exits 8 for that (target_not_found); --no-fail will keep exit 0.\n"}, + {"a page that's gone", "410", map[string]string{}, []string{"fetch", "https://example.com/gone"}, "warning: https://example.com/gone answered 410. From 0.4, string fetch exits 8 for that (target_not_found); --no-fail will keep exit 0.\n"}, + {"a site that fails", "503", map[string]string{}, []string{"fetch", "https://example.com"}, "warning: https://example.com/ answered 503. From 0.4, string fetch exits 6 for that (target_http_error), with the page still printed; --no-fail will keep exit 0.\n"}, + {"a search of a site that fails", "503", map[string]string{}, []string{"search", "coffee"}, ""}, + {"warnings silenced", "404", map[string]string{"STRING_NO_DEPRECATION_WARNINGS": "1"}, []string{"fetch", "https://example.com/gone", "--json"}, ""}, + {"0.2 kept", "404", map[string]string{"STRING_COMPAT": "0.2"}, []string{"fetch", "https://example.com/gone", "--json"}, ""}, + } { + status = c.status + if got := runFetching(base, c.vars, c.list...); got.status != 0 || got.errors != c.said { + t.Errorf("%s: exit %d, stderr %q, want %q", c.about, got.status, got.errors, c.said) + } + } +} diff --git a/cmd/string/run.go b/cmd/string/run.go index 02ac8f0..dc64430 100644 --- a/cmd/string/run.go +++ b/cmd/string/run.go @@ -238,7 +238,9 @@ that runs it stops too. Errors go to stderr as error: and one sentence, the API's own message when it sends one, then the details under it, such as Retry-After, the keyless allowance and x-request-id, then next: and the step out. They never carry an -HTML page or a raw answer. --json prints them as {"error":{...}} instead. +HTML page or a raw answer. --json prints them as {"error":{...}} instead, and +--errors json does the same with stdout left as it is. From 0.4, fetch --json +prints a JSON object: string help formatting lists what changes. Exit codes: 0 ok, 1 other failure, 2 bad input, 3 needs a key or the key was refused, 4 out of credit, 5 rate limited, 6 upstream failure, 7 timeout, @@ -1027,6 +1029,7 @@ type globalSwitches struct { noInput bool // --no-input hasTimeout bool // --timeout timeout string // --timeout's value + errors string // --errors's value: json or text } // takeGlobalSwitches removes the global switches from the arguments before @@ -1036,7 +1039,7 @@ func takeGlobalSwitches(list []string) ([]string, globalSwitches) { kept := make([]string, 0, len(list)) for i := 0; i < len(list); i++ { arg := list[i] - if global, ok := flagNamed(arg, []string{"--json", "--no-open", "--no-input", "--yes", "--timeout"}); ok { + if global, ok := flagNamed(arg, []string{"--json", "--no-open", "--no-input", "--yes", "--timeout", "--errors"}); ok { arg = global } switch { @@ -1061,6 +1064,15 @@ func takeGlobalSwitches(list []string) ([]string, globalSwitches) { } case strings.HasPrefix(arg, "--timeout="): found.hasTimeout, found.timeout = true, strings.TrimPrefix(arg, "--timeout=") + case arg == "--errors": + // Its value always follows, as --timeout's does. + found.errors = "--errors" + if i+1 < len(list) { + i++ + found.errors = list[i] + } + case strings.HasPrefix(arg, "--errors="): + found.errors = strings.TrimPrefix(arg, "--errors=") default: kept = append(kept, arg) } @@ -1072,16 +1084,22 @@ func run(list []string, rt runtime) int { list, global := takeGlobalSwitches(list) rt.json, rt.exec.noOpen = global.json, global.noOpen rt.exec.noInput = rt.exec.noInput || global.noInput - rt.interrupt.answer(rt.json, rt.exec.redraws()) + // --errors json gives JSON errors, as --json does, and leaves stdout as + // it is. + jsonErrors := rt.json || global.errors == "json" + rt.interrupt.answer(jsonErrors, rt.exec.redraws()) + if global.errors != "" && global.errors != "json" && global.errors != "text" { + return report(rt.stderr, usage(fmt.Errorf("--errors takes json or text, not %q", global.errors)), jsonErrors) + } if global.hasTimeout { limit, err := parseTimeout(global.timeout) if err != nil { - return report(rt.stderr, usage(err), rt.json) + return report(rt.stderr, usage(err), jsonErrors) } rt.timeout = &limit } if err := execute(list, rt); err != nil { - return report(rt.stderr, err, rt.json) + return report(rt.stderr, err, jsonErrors) } return 0 } @@ -1148,6 +1166,9 @@ func execute(list []string, rt runtime) error { if op.note != "" { fmt.Fprintln(rt.stderr, op.note) } + if op.command == "fetch" && rt.json && announcing(rt.env) { + fmt.Fprint(rt.stderr, fetchJSONNotice) + } key, err := apiKey(rt.env) if err != nil { return &failure{exit: exitAuth, code: "invalid_key", message: err.Error()} @@ -1227,6 +1248,11 @@ func (c apiClient) call(op *operation) ([]byte, error) { if err != nil { return nil, err } + if op.command == "fetch" && announcing(c.rt.env) { + if warning := siteStatusWarning(response.Header.Get("X-Status-Code"), jsString(op.body["url"])); warning != "" { + fmt.Fprint(c.rt.stderr, warning) + } + } if notes := keylessNotes(response.Header); len(notes) > 0 { fmt.Fprintf(c.rt.stderr, "%s\nRan without a key. For more, %s.\n", strings.Join(notes, "\n"), needsKey) } diff --git a/cmd/string/timeout_test.go b/cmd/string/timeout_test.go index 1dca81e..c3e0bdf 100644 --- a/cmd/string/timeout_test.go +++ b/cmd/string/timeout_test.go @@ -143,7 +143,7 @@ func TestARequestThatRunsOutOfTimeExits7(t *testing.T) { t.Errorf("fetch: %+v, want exit 7 and %q", got, want) } got = invoke(t, []string{"--json", "--timeout=50ms", "fetch", "https://example.com"}, base, "test-key") - expectJSON(t, got.errors, `{"error":{"code":"timeout","message":"`+host+` took longer than 50ms to answer, so string stopped waiting.","next_step":"run it again with --timeout 100ms","retry_after_seconds":null,"exit_code":7,"retryable":true,"user_action_required":false,"next_commands":[{"type":"retry","why":"run it again with --timeout 100ms"}]}}`) + expectJSON(t, lastLine(got.errors), `{"error":{"code":"timeout","message":"`+host+` took longer than 50ms to answer, so string stopped waiting.","next_step":"run it again with --timeout 100ms","retry_after_seconds":null,"exit_code":7,"retryable":true,"user_action_required":false,"next_commands":[{"type":"retry","why":"run it again with --timeout 100ms"}]}}`) if got.status != exitTimeout { t.Errorf("fetch --json: %+v", got) }