# Argument parsers

readerly is not a CLI framework. It reads the shared reader flags, such as `--format` and `--no-input`, and leaves your commands, options and help text to the parser you already use.

## Two calls on the same argv

Each command takes its own arguments, the ones after its name, and uses them twice:

1. `createOut({ tool, command, argv })` scans `argv` for the [shared flags](https://readerly.loadsheet.dev/guide/flags) and builds the profile from them.
2. `readerFlags(argv).rest` returns the same `argv` without those flags. Your parser reads that.

`readerFlags` never throws. It stops at `--` and leaves `--` and everything after it in `rest`. It knows the long flags only, plus `-y`. `-v` stays in `rest`, so it can keep meaning `--version`.

Your parser never sees `--format`, `--json`, `--full`, `--max-chars`, `--color`, `--no-color`, `--no-input`, `--non-interactive`, `--yes`, `-y`, `--verbose`, `--quiet` or `--input`. Don't declare options with those names.

A bad value, such as `--format nope`, is not your parser's problem either. `createOut` keeps it and `out.end()` prints the failure and returns `2`:

```text
✖ --format nope is not a format. Use one of: text, agent, json, jsonl.
╰▶ fix: Pass --format with one of: text, agent, json, jsonl.
```

## node:util parseArgs

`parseArgs` ships with Node, so this example needs nothing beyond `readerly`:

```ts [acme.ts]
import { parseArgs } from "node:util";
import { createOut, failure, FailureError, readerFlags } from "readerly";

export async function check(argv: string[]): Promise<number> {
  const out = createOut<{ files: number }>({ tool: "acme", command: "check", argv });
  let parsed;
  try {
    parsed = parseArgs({
      args: readerFlags(argv).rest,
      options: { fix: { type: "boolean", default: false } },
      allowPositionals: true,
    });
  } catch (error) {
    return out.fail(new FailureError(failure("usage", (error as Error).message)));
  }
  const paths = parsed.positionals.length > 0 ? parsed.positionals : ["."];
  out.warn({ code: "ACME010", message: "Alias shadows a workspace package", file: "vite.config.ts" });
  out.set({ files: paths.length });
  if (!parsed.values.fix) out.next("acme check --fix", "applies 1 safe fix");
  return out.end();
}

const [command, ...args] = process.argv.slice(2);
if (command === "check") process.exitCode = await check(args);
```

`process.exitCode = await check(args)` sets the exit code and lets Node finish writing stdout. `out.end()` returns `0` for `ok`, `1` for `failed` and `2` for `action_required`.

In a pipe, `acme check src` prints:

```text
⚠ 1 warning

warn  ACME010  vite.config.ts  Alias shadows a workspace package

next: acme check --fix   (applies 1 safe fix)
```

`parseArgs` is strict by default and throws on an unknown option. Wrapped in `failure("usage", …)`, the error leaves through `out.fail` in the reader's format and exits `2`. `acme check src --frobnicate` prints on stderr:

```text
✖ Unknown option '--frobnicate'. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- "--frobnicate"
```

With `--json`, the same failure is a document on stdout:

```json
{
  "schema": "acme.check/v1",
  "status": "failed",
  "error": {
    "message": "Unknown option '--frobnicate'. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- \"--frobnicate\""
  }
}
```

> [!WARNING]
> `out.fail(error)` takes something thrown. Pass `new FailureError(failure(…))`, not the `Failure` object itself: a plain object becomes a `runtime` failure with the message `[object Object]` and exit `1`.

## cac

cac matches the command for you, so the command's own arguments come from `argv` without the command's name. This example ran with cac 7.1.1:

```ts [acme.ts]
import { cac } from "cac";
import { createOut, failure, FailureError, readerFlags } from "readerly";

async function check(argv: string[], paths: string[], options: { fix: boolean }) {
  const out = createOut({ tool: "acme", command: "check", argv });
  out.info(`checked ${paths.join(", ") || "."}${options.fix ? " with fixes" : ""}`);
  return out.end();
}

const argv = process.argv.slice(2);
const cli = cac("acme");
cli
  .command("check [...paths]", "Check files")
  .option("--fix", "Apply the safe fixes")
  // createOut gets the command's own arguments: argv without the word `check`.
  .action((paths: string[], options: { fix: boolean }) =>
    check(argv.toSpliced(argv.indexOf("check"), 1), paths, options),
  );
cli.parse(["node", "acme", ...readerFlags(argv).rest], { run: false });
try {
  process.exitCode = await cli.runMatchedCommand();
} catch (error) {
  const out = createOut({ tool: "acme", command: cli.matchedCommandName, argv });
  process.exitCode = out.fail(new FailureError(failure("usage", (error as Error).message)));
}
```

`cli.parse` drops the first two items of the array it gets, as it does with `process.argv`, hence `"node", "acme"`. `{ run: false }` keeps the action from running inside `parse`, so `runMatchedCommand()` can return its exit code.

Reader flags work before or after the command name. `acme --format jsonl check src` prints:

```text
{"type":"version","schema":"acme.check/v1","tool":"acme"}
{"type":"diagnostic","severity":"info","message":"checked src"}
{"type":"result","status":"ok","message":"1 info","data":{}}
```

cac throws on an unknown option from `runMatchedCommand()`, before the action runs. The `catch` turns it into a usage failure. `acme check --frobnicate` prints on stderr and exits `2`:

```text
✖ Unknown option `--frobnicate`
```

## The rerun command

readerly builds the commands in `hidden:` footers, in the `next:` line of a skipped prompt and in the `rerun` of an `action_required` failure from `tool`, `command` and `rest`, without the reader flags. Pass the command's own arguments, not the whole `process.argv`. For `acme check src` with `argv: ["src"]`, a skipped `--fix` prompt prints `next: acme check src --fix`. With `argv: ["check", "src"]`, it prints `next: acme check check src --fix`.

Next: [testing your CLI](https://readerly.loadsheet.dev/integrations/testing) for every reader.

<!-- vitehub-docs:section-links -->
## In this section

- [Overview](https://readerly.loadsheet.dev/raw/integrations.md)
- [GitHub Actions](https://readerly.loadsheet.dev/raw/integrations/github-actions.md)
- [Argument parsers](https://readerly.loadsheet.dev/raw/integrations/argument-parsers.md) (this page)
- [Testing your CLI](https://readerly.loadsheet.dev/raw/integrations/testing.md)
- [Progress](https://readerly.loadsheet.dev/raw/integrations/progress.md)
- [Markdown answers](https://readerly.loadsheet.dev/raw/integrations/markdown-answers.md)
- [nostics](https://readerly.loadsheet.dev/raw/integrations/nostics.md)

Next: [Testing your CLI](https://readerly.loadsheet.dev/raw/integrations/testing.md)

All pages: [llms.txt](https://readerly.loadsheet.dev/llms.txt)
