diff --git a/README.md b/README.md index d2f17d6..5f58a3b 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ string integrations run reddit post --post https://www.reddit.com/r/technology/c **Each flag is a field of the action's input, spelled exactly as the field.** Reddit's `post` action takes `post`, `sort` and `maxPages`, so its flags are `--post`, `--sort` and `--maxPages`, the same names the integration docs and the manifest use. A list field takes one item per flag (`--items a --items b`) or a JSON array. `run` prints the JSON response: `data` holds the rows, and `failures` lists any input that produced none. `list` needs no key; `run` needs one. -`string --help` lists the commands and the `STRING_API_BASE_URL` setting for a different API endpoint. Each command has its own page too, from `string COMMAND --help`, `-h` anywhere on the line, or `string help COMMAND`: examples, what it prints, its exit codes, what it costs, and its flags. `string version` gives the version with the commit, its date, the system and the Go version, and `--json` gives them as one object; `string -v` prints the version alone. Help and version send no request. Four topics cover what no one command owns: `string help exit-codes`, `string help environment` (every variable string reads, and what each request tells String), `string help formatting` and `string help agents`. +`string --help` lists the commands and the `STRING_API_BASE_URL` setting for a different API endpoint. Each command has its own page too, from `string COMMAND --help`, `-h` anywhere on the line, or `string help COMMAND`: examples, what it prints, its exit codes, what it costs, and its flags. `string help --all` puts every command on one page, a line each with what it costs, then the flags every command takes, the exit codes and the topics. `string help --json` gives all of it as one JSON document for programs and agents: each command's usage, arguments, flags and the API fields it takes, what it prints, what it costs, whether it reads, spends, writes or stays on this machine, its exit codes and examples. `string help --json COMMAND`, or `--json` on any `--help`, gives one command's part. `string version` gives the version with the commit, its date, the system and the Go version, and `--json` gives them as one object; `string -v` prints the version alone. Help and version send no request. Four topics cover what no one command owns: `string help exit-codes`, `string help environment` (every variable string reads, and what each request tells String), `string help formatting` and `string help agents`. ## Errors and exit codes @@ -250,7 +250,7 @@ A copy that the install script installed checks for a new release once a day and `string` works out whether a coding agent runs it from the variables the agent sets for the commands it runs: `AI_AGENT`, or Claude Code's, Codex's, Gemini CLI's, Cursor's, OpenCode's, Goose's, Amp's, Cline's, GitHub Copilot's or Warp's own. `CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` count only when stdin is not a terminal, since IDE terminals set them for people too, and `AGENT` comes last. `string` never guesses from the terminal type or from the processes around it. `STRING_AGENT=NAME` names the agent instead, and `STRING_AGENT=human` says a person runs `string`. -Under an agent, `string` never waits for a person: `login`, `init` and `trial claim` print the link and code and return, and only `--poll` waits for the approval. It also opens no browser and shows no update notices. What it prints on stdout and its exit codes are the same for an agent, a script and a person. Bare `string`, `string help` and `string --help` start with three lines for an agent, on where to find one command's page and how to keep big pages out of its context. +Under an agent, `string` never waits for a person: `login`, `init` and `trial claim` print the link and code and return, and only `--poll` waits for the approval. It also opens no browser and shows no update notices. What it prints on stdout and its exit codes are the same for an agent, a script and a person. Bare `string`, `string help` and `string --help` start with three lines for an agent: `string help --all` lists every command on one page and `string help --json` adds the flags, output and exit codes, so one call is enough, and `-o FILE` keeps a big page out of its context. `--no-input`, or `STRING_NO_INPUT=1`, does the same for anyone who sets it, such as a script run from a terminal: `string` then waits for no person. `-y` and `--yes` are taken by every command, to confirm what it would ask first; none asks yet. diff --git a/cmd/string/help.go b/cmd/string/help.go index 46210bd..c1b44d1 100644 --- a/cmd/string/help.go +++ b/cmd/string/help.go @@ -77,18 +77,96 @@ func versionCommand(list []string, rt runtime) error { // line and string help COMMAND all print it, and none of them touches the // network. type commandDoc struct { - summary string + summary string + // usage are command lines, each perhaps with a note three spaces after + // it. A line that starts with a space goes on with the line before it. usage []string examples []string // returns are whole lines: what stdout holds, then the exit codes that // matter. returns []string cost string - // flags and fields are aligned lines: the command's own flags, then the - // API's request fields. - flags string - fields string - more string + // flags are the command's own flags, and fields the API's request fields + // it takes, spelled as the API spells them. fieldsAs names the command + // whose fields this one takes, so that its page points there. + flags []flagDoc + fields []flagDoc + fieldsAs string + more string + // leaves are the commands the page covers, in the order string help + // --all lists them: the page's command itself, or each subcommand. + leaves []leaf +} + +// flagDoc is one flag on a command's page. +type flagDoc struct { + // name is the spelling help shows, without the dashes. + name string + // short is a one-letter spelling, such as o for -o. + short string + // value is what follows the flag, such as N, FILE or [JSON]. It is empty + // for a switch, and =false for a switch that is on unless turned off. + value string + // about says what the flag does, in one line or sentence that the page + // wraps. + about string +} + +// spelled is the flag as its page shows it. +func (f flagDoc) spelled() string { + spelled := "--" + f.name + if f.short != "" { + spelled = "-" + f.short + ", " + spelled + } + switch { + case strings.HasPrefix(f.value, "="): + spelled += f.value + case f.value != "": + spelled += " " + f.value + } + return spelled +} + +// helpWidth is how wide a help line may be. +const helpWidth = 80 + +// termDoc is one row of an aligned list on a help page: a term, such as a +// flag or a variable, and what it means. +type termDoc struct{ term, about string } + +// flagLines lays flags out as help pages do. +func flagLines(flags []flagDoc, at int) string { + terms := make([]termDoc, len(flags)) + for i, f := range flags { + terms[i] = termDoc{f.spelled(), f.about} + } + return termLines(terms, at) +} + +// termLines lays terms out as help pages do: each term from the third column, +// and what it means from column at, wrapped to helpWidth. +func termLines(terms []termDoc, at int) string { + var b strings.Builder + for _, t := range terms { + line := " " + t.term + if len(line) >= at-1 { + b.WriteString(line + "\n") + line = "" + } + for _, word := range strings.Fields(t.about) { + switch { + case len(line) <= at: + line += strings.Repeat(" ", at-len(line)) + word + case len(line)+1+len(word) > helpWidth: + b.WriteString(line + "\n") + line = strings.Repeat(" ", at) + word + default: + line += " " + word + } + } + b.WriteString(line + "\n") + } + return b.String() } // page writes the help page of the command named name. @@ -113,8 +191,14 @@ func (d commandDoc) page(name string) string { section("Examples", d.examples) section("Returns", d.returns) section("Cost", strings.Split(d.cost, "\n")) - block("Flags", d.flags) - block("API fields, spelled as in the API", d.fields) + if len(d.flags) > 0 { + block("Flags", flagLines(d.flags, 27)) + } + if d.fieldsAs != "" { + block("API fields, spelled as in the API", " The same as string "+d.fieldsAs+": string "+d.fieldsAs+" --help.\n") + } else if len(d.fields) > 0 { + block("API fields, spelled as in the API", flagLines(d.fields, 35)) + } b.WriteString("\nLearn more: " + d.more + "\n") return b.String() } @@ -128,6 +212,13 @@ func helpFor(command string) string { return help } +// outputFlags are the flags of each command that sends one request and prints +// its response. +var outputFlags = []flagDoc{ + {name: "output", short: "o", value: "FILE", about: "write the response to FILE instead of stdout"}, + {name: "input", value: "FILE", about: "more request fields, from a JSON object in FILE or - for stdin"}, +} + // exitsOfARequest are the exit codes of a command that sends one request. var exitsOfARequest = []string{ "exit 0 ok · 2 bad input · 3 needs a key · 4 out of credit · 5 rate limited", @@ -135,9 +226,6 @@ var exitsOfARequest = []string{ } const ( - outputFlags = ` -o, --output FILE write the response to FILE instead of stdout - --input FILE more request fields, from a JSON object in FILE or - for stdin -` keysDocs = "https://github.com/usestring/cli#keys" ) @@ -160,31 +248,35 @@ var commandDocs = map[string]commandDoc{ " captureIframes or captureCookies", }, exitsOfARequest...), cost: "1 credit, 5 with --executeJS. Without a key: 50 requests and 100 credits a day\nper IP address, with --format and --executeJS only. Parts after the first, with\n--offset, come from a local copy for 15 minutes and cost nothing.", - flags: ` --max-tokens N print about N tokens of the page, cut at a line's end; - stderr says which part it is and the next part's command - --offset N start the part N tokens into the page -` + outputFlags, - fields: ` --format json|markdown|raw the response format - --markdownMode readable|full how much of the page the Markdown keeps - --mainContentOnly drop navigation, headers and footers - --executeJS render the page in a browser - --waitUntil STATE load, domcontentloaded, networkidle0 or networkidle2 - --countryCode CC the proxy country, such as DE - --headers JSON request headers as a JSON object - --jsonSchema JSON|@./FILE extract into this JSON Schema (JSON output) - --screenshot capture a screenshot (JSON output) - --actions JSON|@./FILE browser actions to run (JSON output) - --captureXHR [JSON] return the page's XHR and fetch() calls (JSON output) - --captureIframes [JSON] list the page's iframes (JSON output) - --includeIframes inline each iframe's content - --captureCookies return the page's cookies (JSON output) - --requireWSS require a browser WebSocket fetch path - --solveCaptcha=false fail on a challenge instead of solving it - --ignoreCertificateErrors skip TLS certificate checks - --maxRedirects N follow at most N redirects - --followRedirects=false return the redirect response itself -`, + flags: append([]flagDoc{ + {name: "max-tokens", value: "N", about: "print about N tokens of the page, cut at a line's end; stderr says which part it is and the next part's command"}, + {name: "offset", value: "N", about: "start the part N tokens into the page"}, + }, outputFlags...), + fields: []flagDoc{ + {name: "format", value: "json|markdown|raw", about: "the response format"}, + {name: "markdownMode", value: "readable|full", about: "how much of the page the Markdown keeps"}, + {name: "mainContentOnly", about: "drop navigation, headers and footers"}, + {name: "executeJS", about: "render the page in a browser"}, + {name: "waitUntil", value: "STATE", about: "load, domcontentloaded, networkidle0 or networkidle2"}, + {name: "countryCode", value: "CC", about: "the proxy country, such as DE"}, + {name: "headers", value: "JSON", about: "request headers as a JSON object"}, + {name: "jsonSchema", value: "JSON|@./FILE", about: "extract into this JSON Schema (JSON output)"}, + {name: "screenshot", about: "capture a screenshot (JSON output)"}, + {name: "actions", value: "JSON|@./FILE", about: "browser actions to run (JSON output)"}, + {name: "captureXHR", value: "[JSON]", about: "return the page's XHR and fetch() calls (JSON output)"}, + {name: "captureIframes", value: "[JSON]", about: "list the page's iframes (JSON output)"}, + {name: "includeIframes", about: "inline each iframe's content"}, + {name: "captureCookies", about: "return the page's cookies (JSON output)"}, + {name: "requireWSS", about: "require a browser WebSocket fetch path"}, + {name: "solveCaptcha", value: "=false", about: "fail on a challenge instead of solving it"}, + {name: "ignoreCertificateErrors", about: "skip TLS certificate checks"}, + {name: "maxRedirects", value: "N", about: "follow at most N redirects"}, + {name: "followRedirects", value: "=false", about: "return the redirect response itself"}, + }, more: "https://docs.usestring.ai/api-reference/fetch", + leaves: []leaf{ + {path: "fetch", args: []string{"URL"}, aliases: []string{"URL"}, line: "a page as Markdown; -o FILE; --max-tokens N", costs: "1 credit, keyless ok", keyless: true, effects: "read", exits: requestExits, stdout: "text/markdown"}, + }, }, "request": { summary: "send a POST, PUT or PATCH to a URL through String", @@ -195,11 +287,15 @@ 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, @ 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", + flags: append([]flagDoc{ + {name: "body", value: "TEXT", about: "the request body, as written, @ included"}, + {name: "body-file", value: "FILE", about: "the request body, read from FILE, or - for stdin"}, + }, outputFlags...), + fieldsAs: "fetch", + more: "https://docs.usestring.ai/api-reference/fetch", + leaves: []leaf{ + {path: "request", args: []string{"METHOD", "URL"}, line: "a POST, PUT or PATCH through String", costs: "key", effects: "write", exits: requestExits, stdout: "application/json", json: true}, + }, }, "search": { summary: "search the web", @@ -215,26 +311,30 @@ var commandDocs = map[string]commandDoc{ }, exitsOfARequest...), cost: "Each results page, about ten results, is billed as one search. Without a key a\nsearch costs 5 of the 100 credits a day per IP address, and takes --language,\n--dateRange, --sortBy, --safeSearch, --autocorrect and --verbatim only.", flags: outputFlags, - fields: ` --engine NAME google (the default), duckduckgo, brave or google_ai_mode - --searchType TYPE web, images, videos, shopping, books, places or forums - --searchCount N how many results, 1 to 300 (--count works too) - --page N the results page to start from - --country CC the country to localize results for - --language CODE the result language, such as en or pt-br - --location PLACE where to search from, such as London - --coordinates JSON {"latitude":…,"longitude":…,"radius":…} - --dateRange RANGE hour, day, week, month, year, or {"from":…,"to":…} - --sortBy relevance|date the result order - --safeSearch filter out explicit results - --verbatim match the query's words exactly - --autocorrect=false search the query as typed - --includeOmittedResults include results hidden as similar - --restrictCountry CC only pages from this country - --aiOverview wait for the AI Overview too (costs 2x) - --format structured|raw results as JSON, or the results page as HTML - --solveCaptcha=false never solve a captcha for this search -`, + fields: []flagDoc{ + {name: "engine", value: "NAME", about: "google (the default), duckduckgo, brave or google_ai_mode"}, + {name: "searchType", value: "TYPE", about: "web, images, videos, shopping, books, places or forums"}, + {name: "searchCount", value: "N", about: "how many results, 1 to 300 (--count works too)"}, + {name: "page", value: "N", about: "the results page to start from"}, + {name: "country", value: "CC", about: "the country to localize results for"}, + {name: "language", value: "CODE", about: "the result language, such as en or pt-br"}, + {name: "location", value: "PLACE", about: "where to search from, such as London"}, + {name: "coordinates", value: "JSON", about: "{\"latitude\":…,\"longitude\":…,\"radius\":…}"}, + {name: "dateRange", value: "RANGE", about: "hour, day, week, month, year, or {\"from\":…,\"to\":…}"}, + {name: "sortBy", value: "relevance|date", about: "the result order"}, + {name: "safeSearch", about: "filter out explicit results"}, + {name: "verbatim", about: "match the query's words exactly"}, + {name: "autocorrect", value: "=false", about: "search the query as typed"}, + {name: "includeOmittedResults", about: "include results hidden as similar"}, + {name: "restrictCountry", value: "CC", about: "only pages from this country"}, + {name: "aiOverview", about: "wait for the AI Overview too (costs 2x)"}, + {name: "format", value: "structured|raw", about: "results as JSON, or the results page as HTML"}, + {name: "solveCaptcha", value: "=false", about: "never solve a captcha for this search"}, + }, more: "https://docs.usestring.ai/api-reference/search", + leaves: []leaf{ + {path: "search", args: []string{"QUERY"}, line: "web results as JSON; --searchCount N", costs: "1 search, keyless ok", keyless: true, effects: "read", exits: requestExits, stdout: "application/json", json: true}, + }, }, "sitemap": { summary: "crawl one site: quote it, approve it, read its pages", @@ -258,25 +358,38 @@ var commandDocs = map[string]commandDoc{ " · 4 out of credit · 7 the wait stopped, and the crawl keeps running", }, cost: "submit quotes the crawl for nothing. approve, or submit --approve, starts it at\nthe quoted cost, which --budgetUsd caps.", - flags: ` --approve approve the quote at once (submit only) - --wait wait for the crawl to end: 90s at most under an agent - --limit N, --offset N page through results and list - -o, --output FILE write the response to FILE instead of stdout -`, - fields: ` --maxPages N pages to crawl, 1 to 10,000 (10 by default) - --maxDepth N link depth from URL, 1 to 100 (2 by default) - --pathPrefix PATH only URLs whose path starts with PATH - --budgetUsd USD the spend cap (the quote by default) - --useSitemap also start from the site's /sitemap.xml -`, + flags: []flagDoc{ + {name: "approve", about: "approve the quote at once (submit only)"}, + {name: "wait", about: "wait for the crawl to end: 90s at most under an agent"}, + {name: "limit", value: "N", about: "how many results or jobs to show, for results and list"}, + {name: "offset", value: "N", about: "how many to skip first, for results and list"}, + {name: "output", short: "o", value: "FILE", about: "write the response to FILE instead of stdout"}, + {name: "input", value: "FILE", about: "more request fields, from a JSON object in FILE or - for stdin (submit only)"}, + }, + fields: []flagDoc{ + {name: "maxPages", value: "N", about: "pages to crawl, 1 to 10,000 (10 by default)"}, + {name: "maxDepth", value: "N", about: "link depth from URL, 1 to 100 (2 by default)"}, + {name: "pathPrefix", value: "PATH", about: "only URLs whose path starts with PATH"}, + {name: "budgetUsd", value: "USD", about: "the spend cap (the quote by default)"}, + {name: "useSitemap", about: "also start from the site's /sitemap.xml"}, + }, more: "https://docs.usestring.ai/api-reference/sitemap", + leaves: []leaf{ + {path: "sitemap submit", args: []string{"URL"}, line: "quote a crawl; --approve starts it", costs: "key; spends on --approve", effects: "spend", flags: []string{"approve", "wait", "output", "input", "maxPages", "maxDepth", "pathPrefix", "budgetUsd", "useSitemap"}, exits: requestExits, stdout: "application/json", json: true}, + {path: "sitemap approve", args: []string{"JOB_ID"}, line: "start a quoted crawl; --wait", costs: "key; spends the quote", effects: "spend", flags: jobFlags, exits: requestExits, stdout: "application/json", json: true}, + {path: "sitemap status", args: []string{"JOB_ID"}, line: "a crawl's state; --wait follows it", costs: "key", effects: "read", flags: jobFlags, examples: []string{"string sitemap status JOB_ID --wait"}, exits: askExits, stdout: "application/json", json: true}, + {path: "sitemap results", args: []string{"JOB_ID"}, line: "a crawl's pages; --limit N --offset N", costs: "key", effects: "read", flags: listFlags, exits: askExits, stdout: "application/json", json: true}, + {path: "sitemap list", line: "your crawls; --limit N --offset N", costs: "key", effects: "read", flags: listFlags, examples: []string{"string sitemap list --limit 20"}, exits: askExits, stdout: "application/json", json: true}, + {path: "sitemap cancel", args: []string{"JOB_ID"}, line: "stop a crawl", costs: "key", effects: "write", flags: []string{"output"}, examples: []string{"string sitemap cancel JOB_ID"}, exits: askExits, stdout: "application/json", json: true}, + }, }, "integrations": { summary: "run typed actions over one website, such as reddit post", usage: []string{ - "string integrations [list] every site and its actions", + "string integrations list every site and its actions", "string integrations list SITE SITE's actions, each with its flags", "string integrations run SITE ACTION [--FIELD VALUE ...]", + "string integrations the same as string integrations list", }, examples: []string{ "string integrations list reddit", @@ -289,11 +402,14 @@ var commandDocs = map[string]commandDoc{ " String failed · 7 timed out", }, cost: "list is free and needs no key. run needs one: most actions bill the requests\nthey make, some bill per row. Prices:\nhttps://docs.usestring.ai/get-started/pricing#site-integrations", - flags: ` --FIELD VALUE a field of the action's input, spelled as the field: the - post field is --post. A list field takes one item per - flag, or a JSON array. -` + outputFlags, + flags: append([]flagDoc{ + {name: "FIELD", value: "VALUE", about: "a field of the action's input, spelled as the field: the post field is --post. A list field takes one item per flag, or a JSON array."}, + }, outputFlags...), more: "https://docs.usestring.ai/sites", + leaves: []leaf{ + {path: "integrations list", args: []string{"[SITE]"}, aliases: []string{"integrations"}, line: "sites and their actions; SITE's flags", costs: "free, no key", keyless: true, effects: "read", flags: []string{}, exits: askExits, stdout: "text/plain", json: true}, + {path: "integrations run", args: []string{"SITE", "ACTION"}, line: "one action; --FIELD VALUE per input field", costs: "key; per request or row", effects: "spend", exits: requestExits, stdout: "application/json", json: true}, + }, }, "init": { summary: "install the string-cli skill for the coding agents on this machine", @@ -311,14 +427,17 @@ var commandDocs = map[string]commandDoc{ "exit 0 ok, whether or not the sign-in finishes · 2 bad input", }, cost: "Free.", - flags: ` --agent NAME[,NAME...] only these agents, each in its own skills directory, - such as claude-code, codex, cursor or gemini-cli - --no-mcp don't add String's MCP server to Claude Code and Codex - --no-login skip the sign-in - --browser sign in as string login --browser does - --device-name NAME the machine's name in the new key's name -`, + flags: []flagDoc{ + {name: "agent", value: "NAME[,NAME...]", about: "only these agents, each in its own skills directory, such as claude-code, codex, cursor or gemini-cli"}, + {name: "no-mcp", about: "don't add String's MCP server to Claude Code and Codex"}, + {name: "no-login", about: "skip the sign-in"}, + {name: "browser", about: "sign in as string login --browser does"}, + {name: "device-name", value: "NAME", about: "the machine's name in the new key's name"}, + }, more: "https://github.com/usestring/cli#agent-skills", + leaves: []leaf{ + {path: "init", line: "the skill for your agents, MCP and sign-in", costs: "free", keyless: true, effects: "write", exits: basicExits, stdout: "text/plain"}, + }, }, "skill": { summary: "print the string-cli skill, the guide for coding agents", @@ -333,10 +452,13 @@ var commandDocs = map[string]commandDoc{ "exit 0 ok · 2 bad input", }, cost: "Free, and it sends no request.", - flags: ` --path list the installed copies instead: the SKILL.md in - each agent's skills directory that has the skill -`, + flags: []flagDoc{ + {name: "path", about: "list the installed copies instead: the SKILL.md in each agent's skills directory that has the skill"}, + }, more: "https://github.com/usestring/cli#agent-skills", + leaves: []leaf{ + {path: "skill", line: "the guide for coding agents; --path", costs: "free", keyless: true, effects: "local", exits: basicExits, stdout: "text/markdown"}, + }, }, "login": { summary: "sign in through your browser and save a new API key", @@ -358,19 +480,19 @@ var commandDocs = map[string]commandDoc{ " sign-in service failed · 7 the wait stopped, and the code still works", }, cost: "Free.", - flags: ` --no-wait print the link and code and exit; the default without - a person at a terminal - --poll wait for the sign-in started earlier and save the key: - 90s at most under an agent, --timeout to change it - --with-token read an API key from stdin, check it and save it - --browser sign in on a String page, with no code; it works for a - new account too - --env-file PATH also write the key to PATH as its STRING_API_KEY line - --device-name NAME the machine's name in the new key's name, up to 51 - characters - --no-open never open a browser -`, + flags: []flagDoc{ + {name: "no-wait", about: "print the link and code and exit; the default without a person at a terminal"}, + {name: "poll", about: "wait for the sign-in started earlier and save the key: 90s at most under an agent, --timeout to change it"}, + {name: "with-token", about: "read an API key from stdin, check it and save it"}, + {name: "browser", about: "sign in on a String page, with no code; it works for a new account too"}, + {name: "env-file", value: "PATH", about: "also write the key to PATH as its STRING_API_KEY line"}, + {name: "device-name", value: "NAME", about: "the machine's name in the new key's name, up to 51 characters"}, + {name: "no-open", about: "never open a browser"}, + }, more: keysDocs, + leaves: []leaf{ + {path: "login", line: "sign in, save a key; --json, then --poll", costs: "free", keyless: true, effects: "write", exits: askExits, stdout: "text/plain", json: true}, + }, }, "logout": { summary: "delete the key that string login saved", @@ -383,6 +505,9 @@ var commandDocs = map[string]commandDoc{ }, cost: "Free.", more: keysDocs, + leaves: []leaf{ + {path: "logout", line: "delete the saved key", costs: "free", keyless: true, effects: "write", exits: basicExits, stdout: "text/plain"}, + }, }, "whoami": { summary: "say which key string uses, and check it with String", @@ -395,9 +520,14 @@ var commandDocs = map[string]commandDoc{ "exit 0 String accepts the key · 3 no key, or String refused it · 6 string", " couldn't ask String", }, - cost: "Free: one request that spends no credit, or none with --offline.", - flags: " --offline say where the key comes from, without asking String\n", - more: keysDocs, + cost: "Free: one request that spends no credit, or none with --offline.", + flags: []flagDoc{ + {name: "offline", about: "say where the key comes from, without asking String"}, + }, + more: keysDocs, + leaves: []leaf{ + {path: "whoami", line: "the key in use, checked; --offline", costs: "free", keyless: true, effects: "read", exits: []int{0, 1, 2, 3, 6}, stdout: "text/plain", json: true}, + }, }, "trial": { summary: "get a trial key for an agent, with no account", @@ -419,13 +549,16 @@ var commandDocs = map[string]commandDoc{ " claim's wait stopped, and the code still works", }, cost: "Free: the trial key comes with a small balance.", - flags: ` --email ADDRESS who claims the agent onto their String account - --no-wait print the link and code and exit; the default without - a person at a terminal - --poll wait for the claim started earlier and save the key: - 90s at most under an agent, --timeout to change it -`, + flags: []flagDoc{ + {name: "email", value: "ADDRESS", about: "who claims the agent onto their String account"}, + {name: "no-wait", about: "print the link and code and exit; the default without a person at a terminal"}, + {name: "poll", about: "wait for the claim started earlier and save the key: 90s at most under an agent, --timeout to change it"}, + }, more: keysDocs, + leaves: []leaf{ + {path: "trial", line: "a trial key when nobody can approve one", costs: "free", keyless: true, effects: "write", flags: []string{}, exits: askExits, stdout: "text/plain", json: true}, + {path: "trial claim", line: "move a trial agent to an account", costs: "free", keyless: true, effects: "write", exits: askExits, stdout: "text/plain", json: true}, + }, }, "status": { summary: "show the version, the key in use, and what you can spend", @@ -435,10 +568,13 @@ var commandDocs = map[string]commandDoc{ "stdout the version and the key. With a key, the balance, any amount held by", " running crawls, the plan and its request rate; without one, what is", " left of today's keyless allowance. --json gives one object", - "exit 0 ok, even when the API can't answer", + "exit 0 ok, even when the API can't answer · 3 String refused the key", }, cost: "Free, and it spends none of the keyless allowance.", more: "https://github.com/usestring/cli#commands", + leaves: []leaf{ + {path: "status", line: "the key, balance or keyless allowance", costs: "free", keyless: true, effects: "read", exits: []int{0, 1, 2, 3}, stdout: "text/plain", json: true}, + }, }, "balance": { summary: "print the balance, plan and auto top-up as JSON", @@ -450,6 +586,9 @@ var commandDocs = map[string]commandDoc{ }, cost: "Free. Needs a key.", more: "https://github.com/usestring/cli#commands", + leaves: []leaf{ + {path: "balance", line: "the balance as JSON", costs: "key", effects: "read", exits: askExits, stdout: "application/json", json: true}, + }, }, "update": { summary: "replace this copy of string with the latest release", @@ -464,12 +603,14 @@ var commandDocs = map[string]commandDoc{ "exit 0 ok · 1 the update failed", }, cost: "Free.", - flags: ` --check show the version, the latest release, how this copy was - installed and whether it updates itself - --version X.Y.Z install that release, which then stays until a plain - string update -`, + flags: []flagDoc{ + {name: "check", about: "show the version, the latest release, how this copy was installed and whether it updates itself"}, + {name: "version", value: "X.Y.Z", about: "install that release, which then stays until a plain string update"}, + }, more: "https://github.com/usestring/cli#updating", + leaves: []leaf{ + {path: "update", line: "install the latest release; --check", costs: "free", keyless: true, effects: "write", exits: basicExits, stdout: "text/plain", json: true}, + }, }, "version": { summary: "print this copy's version and build", @@ -477,7 +618,7 @@ var commandDocs = map[string]commandDoc{ "string version [--json]", "string --version, string -v the version alone", }, - examples: []string{"string version", "string -v"}, + examples: []string{"string version", "string version --json"}, returns: []string{ "stdout string VERSION, then the commit, its date, the system and the Go", " version. --json gives one object", @@ -485,9 +626,32 @@ var commandDocs = map[string]commandDoc{ }, cost: "Free, and it sends no request.", more: "https://github.com/usestring/cli#updating", + leaves: []leaf{ + {path: "version", line: "the version and build; --json", costs: "free", keyless: true, effects: "local", exits: basicExits, stdout: "text/plain", json: true}, + }, }, } +// envDocs are the variables string reads, as string help environment and +// string help --json list them. +var envDocs = []termDoc{ + {"STRING_API_KEY", "the API key; it wins over the key string login saved"}, + {"STRING_API_BASE_URL", "another API endpoint"}, + {"STRING_AGENT", "NAME says the coding agent NAME runs string, and human says a person does; it wins over what string finds"}, + {"AI_AGENT, AGENT", "an agent's name, as some agents set it"}, + {"STRING_NO_INPUT", "1 makes string wait for no person, as --no-input does"}, + {"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"}, + {"XDG_CONFIG_HOME", "where the saved key lives: $XDG_CONFIG_HOME/string, or ~/.config/string without it"}, + {"XDG_CACHE_HOME", "where fetch keeps a page read in parts for 15 minutes: $XDG_CACHE_HOME/string/fetch, or ~/.cache/string/fetch"}, + {"CLAUDE_CONFIG_DIR", "where init finds Claude Code's settings"}, + {"CODEX_HOME", "where init finds Codex's settings"}, +} + // helpTopics are the pages of string help TOPIC that no one command owns. var helpTopics = map[string]string{ "exit-codes": `string help exit-codes: what each exit code means, and what to do next @@ -516,32 +680,7 @@ or tell_user, so an agent can take the steps that need no person. Learn more: https://github.com/usestring/cli#errors-and-exit-codes `, - "environment": `string help environment: the variables string reads, and what it sends - - STRING_API_KEY the API key; it wins over the key string login saved - STRING_API_BASE_URL another API endpoint - STRING_AGENT NAME says the coding agent NAME runs string, and human - says a person does; it wins over what string finds - AI_AGENT, AGENT an agent's name, as some agents set it - STRING_NO_INPUT 1 makes string wait for no person, as --no-input does - 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 - XDG_CONFIG_HOME where the saved key lives: $XDG_CONFIG_HOME/string, or - ~/.config/string without it - XDG_CACHE_HOME where fetch keeps a page read in parts for 15 minutes: - $XDG_CACHE_HOME/string/fetch, or ~/.cache/string/fetch - CLAUDE_CONFIG_DIR where init finds Claude Code's settings - CODEX_HOME where init finds Codex's settings - + "environment": "string help environment: the variables string reads, and what it sends\n\n" + termLines(envDocs, 24) + ` string finds Claude Code, Codex, Gemini CLI, Cursor, Copilot CLI, Cline, Amp, Goose and Warp from the variables each sets, and treats them as agents. @@ -622,6 +761,8 @@ Ways that work well: string login --poll which saves the key once they approve string trial a key when nobody can approve one --json errors as one JSON object + string help --all every command on one page, and + string help --json each one's flags, output and exit codes string COMMAND --help one command's examples, output, exit codes, cost and flags string skill the whole guide for agents, the skill @@ -631,10 +772,11 @@ Learn more: https://github.com/usestring/cli#coding-agents `, } -// agentPreamble starts the help for all of string under an agent. -const agentPreamble = `For agents: string COMMAND --help gives one command's examples, output, exit -codes, cost and flags, and string help agents what changes under an agent. -Pages curl or WebFetch can't read: string fetch URL. Big pages: add -o FILE. +// agentPreamble starts the help for all of string under an agent. No command +// in it is split across lines. +const agentPreamble = `For agents: string help --all lists every command on one page, and +string help --json adds the flags, output and exit codes. One call is enough. +Pages that curl or WebFetch can't read: string fetch URL. Big pages: -o FILE. ` diff --git a/cmd/string/help_all.go b/cmd/string/help_all.go new file mode 100644 index 0000000..92ed409 --- /dev/null +++ b/cmd/string/help_all.go @@ -0,0 +1,519 @@ +package main + +import ( + "cmp" + "encoding/json" + "fmt" + "slices" + "strings" +) + +// leaf is one command that string help --all lists on a line and string help +// --json describes. Its page in commandDocs holds its usage, examples, flags +// and fields; a leaf adds what the page says in prose, in a form a program +// can read. +type leaf struct { + // path is the command's words, such as sitemap submit. The first is the + // name of its page. + path string + // args are its arguments as the usage names them. [SITE] is optional. + args []string + // aliases are other words that run it, such as URL for fetch URL. + aliases []string + // line says what it does, with the flags that matter most, for help --all. + line string + // costs says what a call costs and whether it needs a key, for help --all. + costs string + // keyless is true when it works without a key. + keyless bool + // effects is read, spend, write or local: what running it can change. + // A coding agent may run a read or a local command without asking. + effects string + // flags names the page's flags and fields that it takes; nil is all of + // them. + flags []string + // examples add to the page's examples that it owns. + examples []string + // exits are the exit codes it can end with, but for 130, which any + // command ends with when interrupted. + exits []int + // stdout is what it prints: text/markdown, application/json or + // text/plain. json is true when, with --json, stdout is one JSON object. + stdout string + json bool +} + +var ( + // requestExits are the exit codes of a command whose request can spend. + requestExits = []int{0, 1, 2, 3, 4, 5, 6, 7} + // askExits are those of a command that asks String and spends nothing. + askExits = []int{0, 1, 2, 3, 5, 6, 7} + // basicExits are those of a command that can only fail or be misused. + basicExits = []int{0, 1, 2} + jobFlags = []string{"wait", "output"} + listFlags = []string{"limit", "offset", "output"} +) + +// leaves are every command, in the order help --all lists them: the leaves of +// each page, in the order of commands. +var leaves = func() []leaf { + var all []leaf + for _, name := range commands { + all = append(all, commandDocs[name].leaves...) + } + return all +}() + +// words splits a leaf's path into its words. +func (l leaf) words() []string { return strings.Fields(l.path) } + +// page is the help page the leaf is on. +func (l leaf) page() commandDoc { return commandDocs[l.words()[0]] } + +// exitCodeDoc is one exit code, as string help exit-codes explains it. +type exitCodeDoc struct { + code int + meaning string + // retry is true when running the same command again can succeed. + retry bool +} + +var exitCodeDocs = []exitCodeDoc{ + {0, "ok", false}, + {1, "the operation failed, or String couldn't be reached", false}, + {2, "bad input", false}, + {3, "a key is needed or was refused, or the keyless allowance is used up", false}, + {4, "out of credit; nothing was charged", false}, + {5, "rate limited; retry after Retry-After", true}, + {6, "String failed or didn't answer; retry once", true}, + {7, "timed out; a wait that stopped leaves its job going, and next resumes it", true}, + {130, "interrupted", false}, +} + +// globalFlagDocs are the flags every command takes, wherever they are. +var globalFlagDocs = []flagDoc{ + {name: "json", about: "JSON where the command has it, and errors as one JSON object on stderr"}, + {name: "errors", value: "json|text", about: "errors as JSON, as --json gives them, with stdout as it is"}, + {name: "quiet", short: "q", about: "no status lines on stderr; errors and the keyless allowance stay"}, + {name: "timeout", value: "DURATION", about: "how long a wait or a request may take; 0 for no limit"}, + {name: "no-input", about: "wait for no person, as under an agent"}, + {name: "no-open", about: "never open a browser"}, + {name: "yes", short: "y", about: "confirm what a command would ask first"}, + {name: "help", short: "h", about: "the command's page; with --json, its schema"}, +} + +// helpTopicNames are the pages of string help TOPIC, in the order help lists +// them. +var helpTopicNames = []string{"exit-codes", "environment", "formatting", "agents"} + +// helpAll is string help --all: one line for each command, then the global +// flags, the exit codes and the topics. +func helpAll() string { + var b strings.Builder + b.WriteString("string " + version + ": web pages, search and crawls for agents and people\n\n") + names := make([]string, len(leaves)) + nameWidth, lineWidth := 0, 0 + for i, l := range leaves { + names[i] = strings.TrimSpace(l.path + " " + strings.Join(l.args, " ")) + nameWidth, lineWidth = max(nameWidth, len(names[i])), max(lineWidth, len(l.line)) + } + for i, l := range leaves { + fmt.Fprintf(&b, "%-*s %-*s %s\n", nameWidth, names[i], lineWidth, l.line, l.costs) + } + var globals []string + for _, f := range globalFlagDocs { + globals = append(globals, f.spelled()) + } + var codes []string + for _, e := range exitCodeDocs { + meaning, _, _ := strings.Cut(e.meaning, ";") + meaning, _, _ = strings.Cut(meaning, ",") + codes = append(codes, fmt.Sprintf("%d %s", e.code, meaning)) + } + b.WriteString("\n" + wrapItems("Every command takes:", globals)) + b.WriteString(wrapItems("Exit codes:", codes)) + b.WriteString("\nTopics, a page each:\n") + topics := make([]termDoc, len(helpTopicNames)) + for i, name := range helpTopicNames { + title, _, _ := strings.Cut(helpTopics[name], "\n") + _, about, _ := strings.Cut(title, ": ") + topics[i] = termDoc{"string help " + name, about} + } + b.WriteString(termLines(topics, 27)) + b.WriteString("\nOne command: string COMMAND --help. All of it as JSON: string help --json\n") + return b.String() +} + +// wrapItems lists items after lead, separated by dots and wrapped to +// helpWidth between items, with each line after the first indented. +func wrapItems(lead string, items []string) string { + var b strings.Builder + line := lead + for i, item := range items { + switch { + case i == 0: + line += " " + item + case len(line)+3+len(item) > helpWidth: + b.WriteString(line + " ·\n") + line = " " + item + default: + line += " · " + item + } + } + b.WriteString(line + "\n") + return b.String() +} + +// The shapes of string help --json. +type ( + helpSchema struct { + Name string `json:"name"` + Version string `json:"version"` + SchemaVersion int `json:"schemaVersion"` + Spellings string `json:"spellings"` + GlobalFlags []flagSchema `json:"globalFlags"` + Commands []commandSchema `json:"commands"` + APIFields map[string]fieldSetSchema `json:"apiFields"` + ExitCodes []exitCodeSchema `json:"exitCodes"` + Env []envSchema `json:"env"` + Topics []string `json:"topics"` + Schemas map[string]any `json:"schemas"` + } + commandSchema struct { + Path []string `json:"path"` + Aliases [][]string `json:"aliases,omitempty"` + Summary string `json:"summary"` + Usage string `json:"usage"` + Args []argSchema `json:"args"` + // Flags are the command's own; APIFields names the set in apiFields + // whose request fields it takes as flags too. + Flags []flagSchema `json:"flags"` + APIFields string `json:"apiFields,omitempty"` + Returns returnsSchema `json:"returns"` + Cost costSchema `json:"cost"` + Effects string `json:"effects"` + ExitCodes []int `json:"exitCodes"` + Examples []string `json:"examples"` + } + // fieldSetSchema is one API endpoint's request fields, which every + // command that sends to it takes as flags, spelled as the API spells them. + fieldSetSchema struct { + Docs string `json:"docs"` + // Keyless are the fields a keyless call takes; any other needs a key. + Keyless []string `json:"keyless,omitempty"` + Fields []flagSchema `json:"fields"` + } + argSchema struct { + Name string `json:"name"` + Type string `json:"type"` + Required bool `json:"required"` + } + flagSchema struct { + Name string `json:"name"` + Short string `json:"short,omitempty"` + Aliases []string `json:"aliases,omitempty"` + Type string `json:"type"` + Value string `json:"value,omitempty"` + Default *bool `json:"default,omitempty"` + Description string `json:"description"` + } + returnsSchema struct { + Stdout string `json:"stdout"` + JSON bool `json:"json"` + } + costSchema struct { + Summary string `json:"summary"` + Keyless bool `json:"keyless"` + } + exitCodeSchema struct { + Code int `json:"code"` + Meaning string `json:"meaning"` + Retry bool `json:"retry"` + } + envSchema struct { + Name string `json:"name"` + Description string `json:"description"` + } +) + +// spellings says once, for every flag, what string help --json would +// otherwise list as each flag's aliases. +const spellings = "A flag is the same whatever its case, - and _: --mainContentOnly, --main-content-only and --main_content_only are one flag." + +// kindTypes name each field kind in help --json. +var kindTypes = map[kind]string{ + text: "string", boolean: "bool", integer: "int", number: "number", object: "json", + booleanOrObject: "bool|json", textOrObject: "string|json", + textList: "string[]", integerList: "int[]", numberList: "number[]", +} + +// fieldKinds are the request fields of each page that has them, by its name. +var fieldKinds = map[string]map[string]kind{"fetch": fetchFields, "search": searchFields, "sitemap": sitemapFields} + +// fieldAliases are the older names of those fields. +var fieldAliases = map[string]map[string]string{"search": searchAliases} + +// valueTypes name the type of a flag of the CLI's own from its value. +var valueTypes = map[string]string{"": "bool", "=false": "bool", "N": "int", "USD": "number"} + +// flagSchemaOf describes f, a flag of the CLI's own, or an API field of the +// set named set. +func flagSchemaOf(f flagDoc, set string) flagSchema { + described := flagSchema{Name: f.name, Short: f.short, Type: cmp.Or(valueTypes[f.value], "string"), Value: f.value, Description: f.about} + switch { + case f.value == "=false": + // A switch that is on unless turned off. + on := true + described.Value, described.Default = "", &on + case f.name == strings.ToUpper(f.name): + // It stands for every field of an action's input. + described.Type = "any" + } + if k, ok := fieldKinds[set][f.name]; ok { + described.Type = kindTypes[k] + } + for alias, name := range fieldAliases[set] { + if name == f.name { + described.Aliases = append(described.Aliases, alias) + } + } + slices.Sort(described.Aliases) + return described +} + +// fieldSetOf describes the request fields of the page named set. +func fieldSetOf(set string) fieldSetSchema { + page := commandDocs[set] + described := fieldSetSchema{Docs: page.more, Fields: []flagSchema{}} + for _, f := range page.fields { + described.Fields = append(described.Fields, flagSchemaOf(f, set)) + if slices.Contains(keylessFields[set], f.name) { + described.Keyless = append(described.Keyless, f.name) + } + } + return described +} + +// fieldSet names the set of request fields that l takes, or is empty when it +// takes none. +func (l leaf) fieldSet() string { + page := l.page() + set := cmp.Or(page.fieldsAs, l.words()[0]) + fields := commandDocs[set].fields + if len(fields) == 0 || l.flags != nil && !slices.ContainsFunc(fields, func(f flagDoc) bool { return slices.Contains(l.flags, f.name) }) { + return "" + } + return set +} + +// argTypes name the type of each argument in help --json. +var argTypes = map[string]string{"URL": "url"} + +// uncommented is a usage line or an example without the note after it, which +// starts three spaces on. +func uncommented(line string) string { + line, _, _ = strings.Cut(strings.TrimSpace(line), " ") + return line +} + +// usageLines are a page's usage lines, each with the line it wraps onto. +func usageLines(page commandDoc) []string { + var lines []string + for _, line := range page.usage { + if strings.HasPrefix(line, " ") && len(lines) > 0 { + if more := uncommented(line); more != "" { + lines[len(lines)-1] += " " + more + } + continue + } + lines = append(lines, uncommented(line)) + } + return lines +} + +// owner is the leaf of page that line, a command line, runs: the one with the +// longest path that starts it. +func owner(page commandDoc, line string) (leaf, bool) { + var found leaf + for _, l := range page.leaves { + if (line == "string "+l.path || strings.HasPrefix(line, "string "+l.path+" ")) && len(l.path) > len(found.path) { + found = l + } + } + return found, found.path != "" +} + +// schemaOf describes the leaf l from its page. +func schemaOf(l leaf) commandSchema { + words, page := l.words(), l.page() + described := commandSchema{ + Path: words, + Summary: page.summary, + Args: []argSchema{}, + Flags: []flagSchema{}, + Returns: returnsSchema{Stdout: l.stdout, JSON: l.json}, + Cost: costSchema{Summary: l.costs, Keyless: l.keyless}, + Effects: l.effects, + ExitCodes: l.exits, + Examples: []string{}, + APIFields: l.fieldSet(), + } + if len(words) > 1 { + // A group's summary is the group's; the line says what this one does. + described.Summary = l.line + } + for _, alias := range l.aliases { + described.Aliases = append(described.Aliases, strings.Fields(alias)) + } + var usages []string + for _, line := range usageLines(page) { + if mine, ok := owner(page, line); ok && mine.path == l.path { + usages = append(usages, line) + } + } + described.Usage = strings.Join(usages, "\n") + if described.Usage == "" { + described.Usage = strings.TrimSpace("string " + l.path + " " + strings.Join(l.args, " ")) + } + for _, arg := range l.args { + name := strings.Trim(arg, "[]") + described.Args = append(described.Args, argSchema{Name: strings.ToLower(name), Type: cmp.Or(argTypes[name], "string"), Required: !strings.HasPrefix(arg, "[")}) + } + for _, f := range page.flags { + global := slices.ContainsFunc(globalFlagDocs, func(g flagDoc) bool { return g.name == f.name }) + if !global && (l.flags == nil || slices.Contains(l.flags, f.name)) { + described.Flags = append(described.Flags, flagSchemaOf(f, "")) + } + } + for _, example := range page.examples { + example = uncommented(example) + if mine, ok := owner(page, example); ok && mine.path == l.path { + described.Examples = append(described.Examples, example) + } + } + described.Examples = append(described.Examples, l.examples...) + return described +} + +// beforeDashes is list up to its first --, after which every word is an +// argument. +func beforeDashes(list []string) []string { + if end := slices.Index(list, "--"); end >= 0 { + return list[:end] + } + return list +} + +// commandWords are the words at the start of list that can name a command +// and one of its subcommands. +func commandWords(list []string) []string { + var words []string + for _, word := range list { + if strings.HasPrefix(word, "-") || len(words) == 2 { + break + } + words = append(words, word) + } + return words +} + +// leavesNamed are the leaves that words name: a command's, or a single +// subcommand when the second word names one. +func leavesNamed(words []string) []leaf { + var named, narrowed []leaf + for _, l := range leaves { + path := l.words() + if path[0] != words[0] { + continue + } + named = append(named, l) + if len(words) > 1 && len(path) > 1 && path[1] == words[1] { + narrowed = append(narrowed, l) + } + } + if len(narrowed) > 0 { + return narrowed + } + return named +} + +// errorSchema is the JSON Schema of the error object that --json and +// --errors json print on stderr. +var errorSchema = map[string]any{ + "type": "object", + "required": []string{"error"}, + "properties": map[string]any{ + "error": map[string]any{ + "type": "object", + "required": []string{"code", "message", "exit_code", "retryable", "user_action_required", "next_commands"}, + "properties": map[string]any{ + "code": map[string]any{"type": "string"}, + "message": map[string]any{"type": "string"}, + "exit_code": map[string]any{"type": "integer"}, + "retryable": map[string]any{"type": "boolean"}, + "user_action_required": map[string]any{"type": "boolean"}, + "reason": map[string]any{"type": "string"}, + "status": map[string]any{"type": "integer", "description": "the API's HTTP status"}, + "retry_after_seconds": map[string]any{"type": "integer"}, + "request_id": map[string]any{"type": "string"}, + "next_step": map[string]any{"type": "string"}, + "help_url": map[string]any{"type": "string"}, + "next_actions": map[string]any{"type": "array", "description": "the API's next_actions, as it sent them"}, + "next_commands": map[string]any{ + "type": "array", + "items": map[string]any{ + "type": "object", + "required": []string{"type"}, + "properties": map[string]any{ + "type": map[string]any{"enum": []string{stepFix, stepWait, stepRetry, stepLogin, stepTrial, stepEnv, stepPay, stepTell}}, + "command": map[string]any{"type": "string"}, + "argv": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "why": map[string]any{"type": "string"}, + }, + }, + }, + }, + }, + }, +} + +// helpJSON is string help --json, for the commands that words name, or every +// command when words is empty. +func helpJSON(rt runtime, words []string) error { + chosen := leaves + if len(words) > 0 && words[0] != "help" { + if chosen = leavesNamed(words); len(chosen) == 0 { + // Its next step asks for the schema of the command meant. + return unknownCommand(words[0], append(slices.Clone(words[1:]), "--help", "--json")) + } + } + described := helpSchema{ + Name: "string", Version: version, SchemaVersion: 1, Spellings: spellings, + GlobalFlags: []flagSchema{}, Commands: []commandSchema{}, APIFields: map[string]fieldSetSchema{}, ExitCodes: []exitCodeSchema{}, Env: []envSchema{}, + Topics: helpTopicNames, + Schemas: map[string]any{"Error": errorSchema}, + } + for _, f := range globalFlagDocs { + described.GlobalFlags = append(described.GlobalFlags, flagSchemaOf(f, "")) + } + for _, l := range chosen { + command := schemaOf(l) + described.Commands = append(described.Commands, command) + if set := command.APIFields; set != "" { + described.APIFields[set] = fieldSetOf(set) + } + } + for _, e := range exitCodeDocs { + described.ExitCodes = append(described.ExitCodes, exitCodeSchema{e.code, e.meaning, e.retry}) + } + for _, v := range envDocs { + for name := range strings.SplitSeq(v.term, ", ") { + described.Env = append(described.Env, envSchema{name, v.about}) + } + } + encoded, err := json.Marshal(described) + if err != nil { + return err + } + return write(rt.stdout, append(encoded, '\n')) +} diff --git a/cmd/string/help_all_test.go b/cmd/string/help_all_test.go new file mode 100644 index 0000000..04cdb09 --- /dev/null +++ b/cmd/string/help_all_test.go @@ -0,0 +1,464 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "maps" + "net/http" + "regexp" + "slices" + "strconv" + "strings" + "testing" + "unicode" + "unicode/utf8" +) + +// string help --all is one line for each command, then the flags every +// command takes, the exit codes and a line for each topic, on a page an agent +// reads in one call. +func TestHelpAllListsEveryCommandOnOnePage(t *testing.T) { + got := runOffline(t, "help", "--all") + if got.status != 0 || got.errors != "" || got.output != helpAll() { + t.Fatalf("string help --all: exit %d, stderr %q", got.status, got.errors) + } + lines := strings.Split(strings.TrimSuffix(got.output, "\n"), "\n") + for _, l := range leaves { + named := strings.TrimSpace(l.path + " " + strings.Join(l.args, " ")) + if !slices.ContainsFunc(lines, func(line string) bool { + return strings.HasPrefix(line, named+" ") && strings.Contains(line, " "+l.line+" ") && strings.HasSuffix(line, " "+l.costs) + }) { + t.Errorf("string help --all has no line for %s", named) + } + } + for _, f := range globalFlagDocs { + if !strings.Contains(got.output, f.spelled()) { + t.Errorf("string help --all doesn't name %s", f.spelled()) + } + } + for _, e := range exitCodeDocs { + if !regexp.MustCompile(`(: | · |\n )` + strconv.Itoa(e.code) + ` [A-Za-z]`).MatchString(got.output) { + t.Errorf("string help --all doesn't explain exit %d", e.code) + } + } + if !slices.Equal(slices.Sorted(maps.Keys(helpTopics)), slices.Sorted(slices.Values(helpTopicNames))) { + t.Errorf("string help --all lists the topics %v, and string help has %v", helpTopicNames, slices.Sorted(maps.Keys(helpTopics))) + } + // Each topic has a line, which says what its page says it is about. + for _, name := range helpTopicNames { + title, _, _ := strings.Cut(helpTopics[name], "\n") + _, about, _ := strings.Cut(title, ": ") + if !regexp.MustCompile(`\n string help `+name+` +`+regexp.QuoteMeta(about)+`\n`).MatchString(got.output) || about == "" { + t.Errorf("string help --all has no line for string help %s: %q", name, about) + } + } + for _, line := range lines { + if utf8.RuneCountInString(line) > 100 { + t.Errorf("string help --all has a line of %d columns: %q", utf8.RuneCountInString(line), line) + } + } + if n := tokens(len(got.output)); n >= 2000 { + t.Errorf("string help --all is about %d tokens, want under 2,000", n) + } + // Under an agent, the help for all of string names the commands to run + // next, none of them split across lines. + for _, command := range []string{"string help --all", "string help --json", "string fetch URL"} { + if !slices.ContainsFunc(strings.Split(agentPreamble, "\n"), func(line string) bool { return strings.Contains(line, command) }) { + t.Errorf("the lines for agents split or leave out %q:\n%s", command, agentPreamble) + } + } +} + +// describedBy runs string with list and decodes the schema it prints. +func describedBy(t *testing.T, list ...string) helpSchema { + t.Helper() + got := runOffline(t, list...) + var described helpSchema + if got.status != 0 || got.errors != "" || json.Unmarshal([]byte(got.output), &described) != nil { + t.Fatalf("string %s: exit %d, stderr %q", strings.Join(list, " "), got.status, got.errors) + } + return described +} + +// string help --json describes each command: how to run it, its flags and the +// request fields it takes, what it prints, costs and changes, and how it +// exits, in under 8k tokens for the whole CLI. +func TestHelpJSONDescribesEveryCommand(t *testing.T) { + got := runOffline(t, "help", "--json") + // 8k tokens at 3 bytes a token, which JSON like this averages. + if len(got.output) >= 24000 { + t.Errorf("string help --json is %d bytes, want under 24,000 (8k tokens)", len(got.output)) + } + described := describedBy(t, "help", "--json") + exitCodes := map[int]bool{} + for _, e := range exitCodeDocs { + exitCodes[e.code] = true + } + for _, c := range described.Commands { + path := strings.Join(c.Path, " ") + // Each usage line and example runs this command, and not a longer + // one, as string trial claim is longer than string trial. + runs := func(line string) bool { + longer := slices.ContainsFunc(leaves, func(other leaf) bool { + return len(other.path) > len(path) && strings.HasPrefix(other.path, path+" ") && strings.HasPrefix(line+" ", "string "+other.path+" ") + }) + return strings.HasPrefix(line+" ", "string "+path+" ") && !longer && !strings.Contains(line, " ") + } + for line := range strings.SplitSeq(c.Usage, "\n") { + if !runs(line) { + t.Errorf("%s: usage %q", path, line) + } + } + if len(c.Examples) == 0 || slices.ContainsFunc(c.Examples, func(example string) bool { return !runs(example) }) { + t.Errorf("%s: examples %q", path, c.Examples) + } + if c.Summary == "" || !slices.Contains([]string{"read", "spend", "write", "local"}, c.Effects) || !slices.Contains([]string{"text/markdown", "application/json", "text/plain"}, c.Returns.Stdout) { + t.Errorf("%s: summary %q, effects %q, stdout %q", path, c.Summary, c.Effects, c.Returns.Stdout) + } + // Every command can succeed, fail or be misused; 130 is anyone's. + if !slices.IsSorted(c.ExitCodes) || len(slices.Compact(slices.Clone(c.ExitCodes))) != len(c.ExitCodes) || !slices.Contains(c.ExitCodes, 0) || !slices.Contains(c.ExitCodes, exitFailure) || !slices.Contains(c.ExitCodes, exitUsage) || slices.Contains(c.ExitCodes, exitInterrupted) || slices.ContainsFunc(c.ExitCodes, func(code int) bool { return !exitCodes[code] }) { + t.Errorf("%s exits %v", path, c.ExitCodes) + } + for _, f := range c.Flags { + if f.Name == "" || f.Type == "" || f.Description == "" || slices.ContainsFunc(globalFlagDocs, func(g flagDoc) bool { return g.name == f.Name }) { + t.Errorf("%s: flag %+v", path, f) + } + } + if _, ok := described.APIFields[c.APIFields]; c.APIFields != "" && !ok { + t.Errorf("%s takes the fields of %q, which apiFields doesn't have", path, c.APIFields) + } + } + // Each page's usage loses nothing in help --json: every flag its usage + // lines name is in the usage of one of its commands, and another way to + // run one, such as string URL, is that command's alias. + for name, page := range commandDocs { + var usages strings.Builder + var aliases []string + for _, c := range described.Commands { + if c.Path[0] == name { + usages.WriteString(c.Usage + "\n") + for _, alias := range c.Aliases { + aliases = append(aliases, strings.Join(alias, " ")) + } + } + } + for _, line := range page.usage { + line = uncommented(line) + if _, ok := owner(page, line); !ok && strings.HasPrefix(line, "string ") { + if rest := strings.TrimPrefix(line, "string "); !strings.HasPrefix(rest, "-") { + if alias, _, _ := strings.Cut(rest, " ["); !slices.Contains(aliases, alias) { + t.Errorf("the %s page runs a command as %q, which help --json has no alias for", name, line) + } + } + continue + } + for _, flag := range regexp.MustCompile(`--[a-zA-Z-]+`).FindAllString(line, -1) { + if !regexp.MustCompile(regexp.QuoteMeta(flag) + `\b`).MatchString(usages.String()) { + t.Errorf("the %s page's usage names %s, which help --json's usage leaves out", name, flag) + } + } + } + } + // Each set of request fields is the one the command sends, the keyless + // fields are those the keyless tier takes, and a switch that is on unless + // turned off says so. + sets := map[string]map[string]kind{"fetch": fetchFields, "search": searchFields, "sitemap": sitemapFields} + if keys := slices.Sorted(maps.Keys(described.APIFields)); !slices.Equal(keys, slices.Sorted(maps.Keys(sets))) { + t.Errorf("apiFields has %v", keys) + } + for name, set := range described.APIFields { + var fields []string + for _, f := range set.Fields { + fields = append(fields, f.Name) + i := slices.IndexFunc(commandDocs[name].fields, func(doc flagDoc) bool { return doc.name == f.Name }) + onUnlessOff := i >= 0 && commandDocs[name].fields[i].value == "=false" + if f.Type != kindTypes[sets[name][f.Name]] || f.Description == "" || (f.Default != nil) != onUnlessOff || onUnlessOff && !*f.Default || strings.HasPrefix(f.Value, "=") { + t.Errorf("%s field %+v", name, f) + } + } + if slices.Sort(fields); !slices.Equal(fields, slices.Sorted(maps.Keys(sets[name]))) { + t.Errorf("apiFields.%s has %v, and the command sends %v", name, fields, slices.Sorted(maps.Keys(sets[name]))) + } + // An older name the command still takes is listed with its field. + for alias, field := range fieldAliases[name] { + if !slices.ContainsFunc(set.Fields, func(f flagSchema) bool { return f.Name == field && slices.Contains(f.Aliases, alias) }) { + t.Errorf("apiFields.%s doesn't list --%s with %s", name, alias, field) + } + } + var keyless []string + for _, field := range keylessFields[name] { + if _, ok := sets[name][field]; ok { + keyless = append(keyless, field) + } + } + if !slices.Equal(slices.Sorted(slices.Values(set.Keyless)), slices.Sorted(slices.Values(keyless))) || !strings.HasPrefix(set.Docs, "https://") { + t.Errorf("apiFields.%s: keyless %v, want %v; docs %q", name, set.Keyless, keyless, set.Docs) + } + } + // Every variable string help environment lists is in env. + for _, match := range regexp.MustCompile(`\n ([A-Z][A-Z_]+)[ ,\n]`).FindAllStringSubmatch(helpTopics["environment"], -1) { + if !slices.ContainsFunc(described.Env, func(v envSchema) bool { return v.Name == match[1] && v.Description != "" }) { + t.Errorf("env has no %s", match[1]) + } + } + if _, ok := described.Schemas["Error"]; !ok { + t.Errorf("schemas has no Error") + } +} + +// unreachable is a network where every request fails. +type unreachable struct{} + +func (unreachable) RoundTrip(*http.Request) (*http.Response, error) { + return nil, errors.New("no network in this test") +} + +// returns.json says whether --json gives one JSON object on stdout, as each +// command that succeeds here without the network shows. +func TestReturnsSaysWhatJSONGives(t *testing.T) { + described := describedBy(t, "help", "--json") + for _, list := range [][]string{{"version"}, {"skill"}, {"logout"}, {"whoami", "--offline"}, {"init", "--no-login", "--no-mcp"}, {"status"}} { + var stdout, stderr bytes.Buffer + status := run(append(list, "--json"), runtime{ + env: envOf(map[string]string{"HOME": t.TempDir(), "STRING_API_KEY": "test-key"}), + lookPath: func(name string) (string, error) { return "/opt/bin/" + name, nil }, + client: &http.Client{Transport: unreachable{}}, + stdout: &stdout, + stderr: &stderr, + }) + var object map[string]any + gave := json.Unmarshal(stdout.Bytes(), &object) == nil + i := slices.IndexFunc(described.Commands, func(c commandSchema) bool { return c.Path[0] == list[0] }) + if status != 0 || gave != described.Commands[i].Returns.JSON { + t.Errorf("string %s --json: exit %d, one JSON object %v, and help --json says %v; stderr %q", strings.Join(list, " "), status, gave, described.Commands[i].Returns.JSON, stderr.String()) + } + } +} + +// string help --json COMMAND, and COMMAND --help with --json, describe that +// command alone: all of a group's commands, or one of them. +func TestHelpJSONForOneCommand(t *testing.T) { + for _, c := range []struct { + list []string + paths []string + fieldOf []string + }{ + {[]string{"help", "--json", "fetch"}, []string{"fetch"}, []string{"fetch"}}, + {[]string{"help", "fetch", "--json"}, []string{"fetch"}, []string{"fetch"}}, + {[]string{"https://example.com", "-h", "--json"}, []string{"fetch"}, []string{"fetch"}}, + {[]string{"request", "POST", "https://example.com", "--json", "-h"}, []string{"request"}, []string{"fetch"}}, + {[]string{"sitemap", "status", "job-1", "--help", "--json"}, []string{"sitemap status"}, nil}, + {[]string{"help", "--json", "sitemap", "submit"}, []string{"sitemap submit"}, []string{"sitemap"}}, + {[]string{"help", "--json", "sitemap"}, []string{"sitemap submit", "sitemap approve", "sitemap status", "sitemap results", "sitemap list", "sitemap cancel"}, []string{"sitemap"}}, + {[]string{"trial", "--help", "--json"}, []string{"trial", "trial claim"}, nil}, + {[]string{"trial", "claim", "--poll", "--json", "-h"}, []string{"trial claim"}, nil}, + // It needs a key to run, but not to say how. + {[]string{"integrations", "run", "reddit", "post", "--help", "--json"}, []string{"integrations run"}, nil}, + {[]string{"version", "--json", "-h"}, []string{"version"}, nil}, + } { + described := describedBy(t, c.list...) + var paths []string + for _, command := range described.Commands { + paths = append(paths, strings.Join(command.Path, " ")) + } + if sets := slices.Sorted(maps.Keys(described.APIFields)); !slices.Equal(paths, c.paths) || !slices.Equal(sets, c.fieldOf) { + t.Errorf("string %s: commands %q, apiFields %v", strings.Join(c.list, " "), paths, sets) + } + } + if a, b := runOffline(t, "fetch", "--help", "--json"), runOffline(t, "help", "--json", "fetch"); a.output != b.output { + t.Errorf("fetch --help --json and help --json fetch differ") + } + // The whole schema, wherever --json asks for help and names no command. + for _, list := range [][]string{{"--json"}, {"help", "--json"}, {"--help", "--json"}, {"help", "--all", "--json"}, {"help", "exit-codes", "--json"}, {"help", "help", "--json"}} { + if described := describedBy(t, list...); len(described.Commands) != len(leaves) { + t.Errorf("string %s: %d commands, want %d", strings.Join(list, " "), len(described.Commands), len(leaves)) + } + } + // A command string doesn't have is an error, whose next step asks for the + // schema of the command meant. + got := runOffline(t, "help", "--json", "scrape") + lines := strings.Split(strings.TrimSpace(got.errors), "\n") + envelope, _ := decode(t, lines[len(lines)-1]).(map[string]any) + fields, _ := envelope["error"].(map[string]any) + if got.status != exitUsage || got.output != "" || fields["code"] != "unknown_command" || fields["next_step"] != "run `string fetch --help --json`" { + t.Errorf("string help --json scrape: %+v", got) + } + if got := runOffline(t, "bogus", "--help", "--json"); got.status != exitUsage || got.output != "" { + t.Errorf("string bogus --help --json: %+v", got) + } +} + +// spelledEachWay is a flag's name in camelCase, kebab-case and snake_case, +// when it has more than one word. +func spelledEachWay(name string) []string { + var words []string + start := 0 + for i, r := range name { + if r == '-' || unicode.IsUpper(r) && i > 0 && !unicode.IsUpper(rune(name[i-1])) { + words = append(words, strings.ToLower(name[start:i])) + start = i + if r == '-' { + start++ + } + } + } + words = append(words, strings.ToLower(name[start:])) + if len(words) < 2 { + return nil + } + camel := words[0] + for _, word := range words[1:] { + camel += strings.ToUpper(word[:1]) + word[1:] + } + return []string{camel, strings.Join(words, "-"), strings.Join(words, "_")} +} + +// Every flag and request field that help --json gives a command parses on +// that command's line, in each of its spellings and under each alias. +func TestEveryDocumentedFlagParses(t *testing.T) { + samples := map[string]string{"URL": "https://example.com", "QUERY": "coffee", "METHOD": "POST", "JOB_ID": "job-1"} + valueOf := map[string]string{"int": "1", "number": "1", "string": "x", "json": "{}", "string|json": "x", "string[]": "x", "int[]": "1", "number[]": "1"} + described := describedBy(t, "help", "--json") + for _, c := range described.Commands { + // integrations run reads the action's fields from the API first. + if strings.Join(c.Path, " ") == "integrations run" { + continue + } + line := slices.Clone(c.Path) + for _, arg := range c.Args { + if arg.Required { + line = append(line, samples[strings.ToUpper(arg.Name)]) + } + } + flags := slices.Clone(c.Flags) + if c.APIFields != "" { + flags = append(flags, described.APIFields[c.APIFields].Fields...) + } + for _, f := range flags { + for _, spelling := range slices.Concat([]string{f.Name}, spelledEachWay(f.Name), f.Aliases) { + list := append(slices.Clone(line), "--"+spelling) + switch { + case f.Default != nil: + list[len(list)-1] += "=false" + case valueOf[f.Type] != "": + list = append(list, valueOf[f.Type]) + } + if got := runOffline(t, append(list, "--help")...); got.status != 0 || got.output != helpFor(c.Path[0]) { + t.Errorf("string %s --help: exit %d, stderr %q", strings.Join(list, " "), got.status, got.errors) + } + } + } + } + // The flags every command takes parse on any command line. + for _, f := range globalFlagDocs { + if f.name == "json" || f.name == "help" { + continue + } + for _, spelling := range append([]string{f.name}, spelledEachWay(f.name)...) { + list := []string{"search", "coffee", "--" + spelling} + if f.value != "" { + list = append(list, map[string]string{"errors": "json", "timeout": "5s"}[f.name]) + } + if got := runOffline(t, append(list, "--help")...); got.status != 0 || got.output != helpFor("search") { + t.Errorf("string %s --help: exit %d, stderr %q", strings.Join(list, " "), got.status, got.errors) + } + } + } +} + +// Every command has a page, every page its leaves, and what a page says of +// its leaves holds for them, so help --all and help --json say what the +// pages say. +func TestThePagesAndTheirLeavesAgree(t *testing.T) { + var named []string + for _, name := range commands { + if name != "help" { + named = append(named, name) + } + } + if pages := slices.Sorted(maps.Keys(commandDocs)); !slices.Equal(pages, slices.Sorted(slices.Values(named))) { + t.Errorf("the pages are %v, and the commands %v", pages, named) + } + var paths []string + for name, page := range commandDocs { + if len(page.leaves) == 0 { + t.Errorf("the %s page has no leaves", name) + } + every := map[int]bool{} + for _, l := range page.leaves { + paths = append(paths, l.path) + if l.words()[0] != name { + t.Errorf("the %s page has the leaf %q", name, l.path) + } + for _, code := range l.exits { + every[code] = true + } + usages := 0 + for _, line := range usageLines(page) { + if mine, ok := owner(page, line); ok && mine.path == l.path { + usages++ + } + } + if usages == 0 { + t.Errorf("%s has no usage line on its page", l.path) + } + takes := map[string]bool{} + for _, f := range append(slices.Clone(page.flags), page.fields...) { + takes[f.name] = true + } + fields := 0 + for _, flag := range l.flags { + if !takes[flag] { + t.Errorf("%s takes --%s, which its page doesn't have", l.path, flag) + } + if slices.ContainsFunc(page.fields, func(f flagDoc) bool { return f.name == flag }) { + fields++ + } + } + if fields != 0 && fields != len(page.fields) { + t.Errorf("%s takes %d of its page's %d fields, want all or none", l.path, fields, len(page.fields)) + } + } + // Every flag on a page is one of its leaves'. + for _, f := range page.flags { + if !slices.ContainsFunc(page.leaves, func(l leaf) bool { return l.flags == nil || slices.Contains(l.flags, f.name) }) { + t.Errorf("the %s page has --%s, which none of its leaves takes", name, f.name) + } + } + // The exit codes a page names are its leaves' exit codes. + for _, line := range page.returns { + if !strings.HasPrefix(line, "exit") && !strings.HasPrefix(line, " ") { + continue + } + for _, match := range regexp.MustCompile(`(?:^exit|·)\s+(\d+) `).FindAllStringSubmatch(line, -1) { + if code, _ := strconv.Atoi(match[1]); !every[code] { + t.Errorf("the %s page says it exits %d, which none of its leaves does", name, code) + } + } + } + // Every example on a page runs one of its leaves. + for _, example := range page.examples { + if _, ok := owner(page, uncommented(example)); !ok { + t.Errorf("the %s page's example %q runs none of its leaves", name, example) + } + } + } + if len(slices.Compact(slices.Sorted(slices.Values(paths)))) != len(paths) || len(paths) != len(leaves) { + t.Errorf("the leaves %v aren't each listed once", paths) + } + // string help exit-codes explains the exit codes help --all and help + // --json list. + var codes []int + for _, match := range regexp.MustCompile(`\n (\d+) `).FindAllStringSubmatch(helpTopics["exit-codes"], -1) { + code, _ := strconv.Atoi(match[1]) + codes = append(codes, code) + } + var documented []int + for _, e := range exitCodeDocs { + documented = append(documented, e.code) + } + if !slices.Equal(codes, documented) { + t.Errorf("string help exit-codes explains %v, and exitCodeDocs %v", codes, documented) + } +} diff --git a/cmd/string/help_test.go b/cmd/string/help_test.go index 4663ee0..d02aff3 100644 --- a/cmd/string/help_test.go +++ b/cmd/string/help_test.go @@ -44,7 +44,6 @@ func TestEveryCommandHasItsOwnHelp(t *testing.T) { "login": {{"login", "--poll", "-h"}}, "trial": {{"trial", "claim", "--poll", "-h"}, {"help", "trial", "claim"}}, "update": {{"update", "--check", "-h"}}, - "version": {{"version", "--json", "-h"}}, } for command, doc := range commandDocs { want := doc.page(command) diff --git a/cmd/string/run.go b/cmd/string/run.go index 0102b2d..c38f9bf 100644 --- a/cmd/string/run.go +++ b/cmd/string/run.go @@ -137,6 +137,8 @@ Usage: string --version, string -v string help COMMAND the same as string COMMAND --help string help TOPIC exit-codes, environment, formatting or agents + string help --all every command on one page + string help --json [COMMAND] the commands, flags and exit codes as JSON Each API request field is a flag spelled exactly as the field, so the API reference reads straight onto the command line: @@ -952,8 +954,12 @@ func requestCommand(list []string, stdin io.Reader) (*operation, error) { return &operation{method: "POST", path: "/fetch", body: body, binary: format == "raw", output: parsed.values["output"], flagged: flagged(parsed), changes: true, note: note}, nil } +// searchAliases are older names of search's fields, which string help --json +// lists with each field. +var searchAliases = map[string]string{"count": "searchCount"} + func searchCommand(list []string, stdin io.Reader) (*operation, error) { - parsed, err := parse(list, spec{options: []string{"output"}, fields: searchFields, aliases: map[string]string{"count": "searchCount"}}) + parsed, err := parse(list, spec{options: []string{"output"}, fields: searchFields, aliases: searchAliases}) if err != nil || parsed.help { return nil, err } @@ -1211,10 +1217,21 @@ func execute(list []string, rt runtime) error { list = append(slices.Clone(list[1:]), "--help") } if len(list) == 0 || slices.Contains([]string{"", "--help"}, list[0]) { + if rt.json { + return helpJSON(rt, nil) + } return write(rt.stdout, []byte(rootHelp(rt))) } if list[0] == "help" { - if len(list) == 1 || strings.HasPrefix(list[1], "-") { + rest := list[1:] + switch { + case rt.json && len(rest) > 0 && helpTopics[rest[0]] != "": + return helpJSON(rt, nil) + case rt.json: + return helpJSON(rt, commandWords(rest)) + case slices.Contains(rest, "--all"): + return write(rt.stdout, []byte(helpAll())) + case len(rest) == 0 || strings.HasPrefix(rest[0], "-"): return write(rt.stdout, []byte(rootHelp(rt))) } if topic, ok := helpTopics[list[1]]; ok { @@ -1231,6 +1248,10 @@ func execute(list []string, rt runtime) error { if !strings.HasPrefix(list[0], "-") && (strings.Contains(list[0], "://") || strings.Contains(list[0], ".")) { list = append([]string{"fetch"}, list...) } + // With --json, a command's help is its part of string help --json. + if rt.json && slices.Contains(beforeDashes(list), "--help") { + return helpJSON(rt, commandWords(list)) + } switch list[0] { case "--version", "-v": return write(rt.stdout, []byte("string "+version+"\n"))