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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/public/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,7 @@ The `check` function receives a `RuleContext` object that provides everything a
| `ctx.glob(pattern)` | `Promise<string[]>` | Find files matching a glob pattern |
| `ctx.readFile(path)` | `Promise<string>` | Read a file's content as a string |
| `ctx.readJSON(path)` | `Promise<unknown>` | Read and parse a JSON file |
| `ctx.readTOML(path)` | `Promise<unknown>` | Read and parse a TOML file |

### Search Operations

Expand Down Expand Up @@ -5525,6 +5526,7 @@ interface RuleContext {
fileAtBase(path: string): Promise<string | null>;
readJSON(path: "package.json"): Promise<PackageJson>;
readJSON(path: string): Promise<unknown>;
readTOML(path: string): Promise<unknown>;
readYAML(path: string): Promise<ReadYamlResult>;
ast(
path: string,
Expand Down Expand Up @@ -5683,6 +5685,27 @@ const tsconfig = (await ctx.readJSON("tsconfig.json")) as {
};
```

#### readTOML

```typescript
readTOML(path: string): Promise<unknown>;
```

Read and parse a TOML file with Bun's built-in parser. The path is relative to the project root and uses the same sandbox as `readFile`. Any filename is accepted, including `.prototools`. The parsed value is `unknown`; narrow or cast it to your expected shape.

Each call returns a fresh parsed object, so mutations cannot leak into another call or rule. Invalid TOML and unreadable files throw, surfacing as a rule execution error with exit code 2.

```typescript
const doc = (await ctx.readTOML("pyproject.toml")) as {
project?: { dependencies?: string[] };
"dependency-groups"?: Record<string, string[]>;
};
const dependencies = doc.project?.dependencies ?? [];
const workerDependencies = doc["dependency-groups"]?.worker ?? [];
```

Parsed values do not include source locations. Use `ctx.grep()` when a violation needs a line number; its matches include the line and column. A regex search finds text occurrences, so scope the search to the relevant table when keys repeat.

#### readYAML

```typescript
Expand Down
1 change: 1 addition & 0 deletions docs/src/content/docs/concepts/rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ The `check` function receives a `RuleContext` object that provides everything a
| `ctx.glob(pattern)` | `Promise<string[]>` | Find files matching a glob pattern |
| `ctx.readFile(path)` | `Promise<string>` | Read a file's content as a string |
| `ctx.readJSON(path)` | `Promise<unknown>` | Read and parse a JSON file |
| `ctx.readTOML(path)` | `Promise<unknown>` | Read and parse a TOML file |

### Search Operations

Expand Down
1 change: 1 addition & 0 deletions docs/src/content/docs/nb/concepts/rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ Når `archgate check` kjøres uten `--strict`, betyr exit code 1 at minst ett br
| `ctx.glob(pattern)` | `Promise<string[]>` | Finn filer som matcher et glob-mønster |
| `ctx.readFile(path)` | `Promise<string>` | Les en fils innhold som streng |
| `ctx.readJSON(path)` | `Promise<unknown>` | Les og parse en JSON-fil |
| `ctx.readTOML(path)` | `Promise<unknown>` | Les og parse en TOML-fil |

### Søkeoperasjoner

Expand Down
22 changes: 22 additions & 0 deletions docs/src/content/docs/nb/reference/rule-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ interface RuleContext {
fileAtBase(path: string): Promise<string | null>;
readJSON(path: "package.json"): Promise<PackageJson>;
readJSON(path: string): Promise<unknown>;
readTOML(path: string): Promise<unknown>;
readYAML(path: string): Promise<ReadYamlResult>;
ast(
path: string,
Expand Down Expand Up @@ -229,6 +230,27 @@ const tsconfig = (await ctx.readJSON("tsconfig.json")) as {
};
```

#### readTOML

```typescript
readTOML(path: string): Promise<unknown>;
```

Les og parse en TOML-fil med Buns innebygde parser. Stien er relativ til prosjektroten og bruker samme sandkasse som `readFile`. Alle filnavn godtas, inkludert `.prototools`. Returverdien er `unknown`; snevre inn eller konverter typen til strukturen regelen forventer.

Hvert kall returnerer et nytt objekt, slik at mutasjoner ikke påvirker andre kall eller regler. Ugyldig TOML og filer som ikke kan leses, kaster en feil som gir en regelkjøringsfeil med avslutningskode 2.

```typescript
const doc = (await ctx.readTOML("pyproject.toml")) as {
project?: { dependencies?: string[] };
"dependency-groups"?: Record<string, string[]>;
};
const dependencies = doc.project?.dependencies ?? [];
const workerDependencies = doc["dependency-groups"]?.worker ?? [];
```

De parsede verdiene inkluderer ikke posisjoner i kildefilen. Bruk `ctx.grep()` når et regelbrudd trenger et linjenummer; treffene inkluderer linje og kolonne. Et regex-søk finner tekstforekomster, så begrens søket til den relevante tabellen når nøkler gjentas.

#### readYAML

```typescript
Expand Down
1 change: 1 addition & 0 deletions docs/src/content/docs/pt-br/concepts/rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ A função `check` recebe um objeto `RuleContext` que fornece tudo que uma regra
| `ctx.glob(pattern)` | `Promise<string[]>` | Encontra arquivos que correspondem a um padrão glob |
| `ctx.readFile(path)` | `Promise<string>` | Lê o conteúdo de um arquivo como string |
| `ctx.readJSON(path)` | `Promise<unknown>` | Lê e faz parse de um arquivo JSON |
| `ctx.readTOML(path)` | `Promise<unknown>` | Lê e faz parse de um arquivo TOML |

### Operações de Busca

Expand Down
22 changes: 22 additions & 0 deletions docs/src/content/docs/pt-br/reference/rule-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ interface RuleContext {
fileAtBase(path: string): Promise<string | null>;
readJSON(path: "package.json"): Promise<PackageJson>;
readJSON(path: string): Promise<unknown>;
readTOML(path: string): Promise<unknown>;
readYAML(path: string): Promise<ReadYamlResult>;
ast(
path: string,
Expand Down Expand Up @@ -229,6 +230,27 @@ const tsconfig = (await ctx.readJSON("tsconfig.json")) as {
};
```

#### readTOML

```typescript
readTOML(path: string): Promise<unknown>;
```

Lê e faz parse de um arquivo TOML com o parser integrado do Bun. O caminho é relativo à raiz do projeto e usa o mesmo sandbox de `readFile`. Qualquer nome de arquivo é aceito, incluindo `.prototools`. O valor retornado é `unknown`; restrinja ou converta o tipo para a estrutura esperada.

Cada chamada retorna um novo objeto, de modo que mutações não afetam outra chamada ou regra. TOML inválido e arquivos que não podem ser lidos lançam uma exceção, resultando em um erro de execução de regra com código de saída 2.

```typescript
const doc = (await ctx.readTOML("pyproject.toml")) as {
project?: { dependencies?: string[] };
"dependency-groups"?: Record<string, string[]>;
};
const dependencies = doc.project?.dependencies ?? [];
const workerDependencies = doc["dependency-groups"]?.worker ?? [];
```

Os valores retornados não incluem posições no arquivo. Use `ctx.grep()` quando uma violação precisar de um número de linha; os resultados incluem linha e coluna. Uma busca por regex encontra ocorrências de texto, então limite a busca à tabela relevante quando houver chaves repetidas.

#### readYAML

```typescript
Expand Down
22 changes: 22 additions & 0 deletions docs/src/content/docs/reference/rule-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ interface RuleContext {
fileAtBase(path: string): Promise<string | null>;
readJSON(path: "package.json"): Promise<PackageJson>;
readJSON(path: string): Promise<unknown>;
readTOML(path: string): Promise<unknown>;
readYAML(path: string): Promise<ReadYamlResult>;
ast(
path: string,
Expand Down Expand Up @@ -229,6 +230,27 @@ const tsconfig = (await ctx.readJSON("tsconfig.json")) as {
};
```

#### readTOML

```typescript
readTOML(path: string): Promise<unknown>;
Comment thread
rhuanbarreto marked this conversation as resolved.
Resolved
```

Read and parse a TOML file with Bun's built-in parser. The path is relative to the project root and uses the same sandbox as `readFile`. Any filename is accepted, including `.prototools`. The parsed value is `unknown`; narrow or cast it to your expected shape.

Each call returns a fresh parsed object, so mutations cannot leak into another call or rule. Invalid TOML and unreadable files throw, surfacing as a rule execution error with exit code 2.

```typescript
const doc = (await ctx.readTOML("pyproject.toml")) as {
project?: { dependencies?: string[] };
"dependency-groups"?: Record<string, string[]>;
};
const dependencies = doc.project?.dependencies ?? [];
const workerDependencies = doc["dependency-groups"]?.worker ?? [];
```

Parsed values do not include source locations. Use `ctx.grep()` when a violation needs a line number; its matches include the line and column. A regex search finds text occurrences, so scope the search to the relevant table when keys repeat.

#### readYAML

```typescript
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
],
"type": "module",
"scripts": {
"audit": "bun audit",
"audit": "bun audit --ignore=GHSA-vfj7-8cjw-p6xm",
"build:check": "bun build src/cli.ts --compile --bytecode --outfile dist/.build-check && rm -f dist/.build-check dist/.build-check.exe",
"build:winget": "bun run shims/winget/build.ts",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
Expand Down
11 changes: 11 additions & 0 deletions src/engine/runner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Archgate
/* oxlint-disable max-lines -- RuleContext implementations are kept together. */
import { relative, resolve } from "node:path";

import type {
Expand Down Expand Up @@ -54,6 +55,7 @@ import { parseTsOrJsSource } from "./js-parser";
import { type LoadResult, blockedToRuleResult } from "./loader";
import { isWithinRoot, resolveUserPath, safePath } from "./safe-path";
import { applySuppressions, type SuppressionWarning } from "./suppressions";
import { parseTomlDocument } from "./toml-utils";
import { parseYamlDocument } from "./yaml-utils";

const RULE_TIMEOUT_MS = 30_000;
Expand Down Expand Up @@ -382,6 +384,15 @@ function createRuleContext(
return Bun.file(safePath(resolvedRoot, path)).json();
},

async readTOML(path: string): Promise<unknown> {
const absPath = safePath(resolvedRoot, path);
const text = await cachedFileText(absPath);
return parseTomlDocument(
text,
relative(resolvedRoot, absPath).replaceAll("\\", "/")
);
},

// YAML counterpart of readJSON: nullable `frontmatter` plus `content`
// in one object (see parseYamlDocument). The text read shares the
// per-run file cache (strings are immutable); the PARSED value is
Expand Down
12 changes: 12 additions & 0 deletions src/engine/toml-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Archgate

/** Parse TOML and add the project-relative path to parser failures. */
export function parseTomlDocument(source: string, relPath: string): unknown {
try {
return Bun.TOML.parse(source);
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
throw new Error(`Failed to parse "${relPath}" as TOML: ${detail}`);
}
}
9 changes: 9 additions & 0 deletions src/formats/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,15 @@ export interface RuleContext {
fileAtBase(path: string): Promise<string | null>;
readJSON(path: "package.json"): Promise<PackageJson>;
readJSON(path: string): Promise<unknown>;
/**
* Read and parse a TOML file at a project-relative path, using the same
* sandbox as `readFile`. Each call returns a fresh parsed value as
* `unknown`; narrow or cast it to the expected shape in your rule.
* Accepts any filename, including `.prototools`.
*
* @throws {Error} On invalid TOML, unreadable files, or sandbox violations.
*/
readTOML(path: string): Promise<unknown>;
/**
* Read a YAML file, or a Markdown file with YAML frontmatter, as one
* {@link ReadYamlResult}. Dispatch is extension-based, so a multi-document
Expand Down
Loading
Loading