Skip to content
Merged
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
33 changes: 18 additions & 15 deletions website/src/content/docs/docs/extending-typespec/linters.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ You can find examples in `packages/best-practices`.
### 1. Define rules

```ts
import { createLinterRule } from "@typespec/compiler";
import { reportDiagnostic } from "../lib.js";
import { createRule, getDoc, paramMessage } from "@typespec/compiler";

export const requiredDocRule = createLinterRule({
export const requiredDocRule = createRule({
name: "no-model-doc",
severity: "warning",
// Short description of what this linter rule does. To be used for generated summary of a linter.
Expand All @@ -37,7 +36,7 @@ export const requiredDocRule = createLinterRule({
operation: (op) => {
if (!getDoc(context.program, op)) {
context.reportDiagnostic({
target: model,
target: op,
});
}
},
Expand All @@ -49,12 +48,12 @@ export const requiredDocRule = createLinterRule({
});
}
},
enums: (type) => {
enum: (type) => {
if (!getDoc(context.program, type)) {
context.reportDiagnostic({
messageId: "enums",
format: {enumName: type.name}
target: model,
format: { enumName: type.name },
target: type,
});
}
},
Expand Down Expand Up @@ -155,26 +154,30 @@ To test a linter rule, a rule tester is provided, allowing you to test a specifi
First, you'll want to create an instance of the rule tester using `createLinterRuleTester`, passing it the rule that is being tested. You can then provide different tests to check whether the rule passes or fails.

```ts
import { RuleTester, createLinterRuleTester, createTestRunner } from "@typespec/compiler/testing";
import {
type LinterRuleTester,
createLinterRuleTester,
createTestRunner,
} from "@typespec/compiler/testing";
import { requiredDocRule } from "./rules/required-doc.rule.js";

describe("required-doc rule", () => {
let ruleTester: RuleTester;
let ruleTester: LinterRuleTester;

beforeEach(() => {
const runner = createTestRunner();
beforeEach(async () => {
const runner = await createTestRunner();
ruleTester = createLinterRuleTester(runner, requiredDocRule, "@typespec/my-linter");
});

it("emit diagnostics when using model named foo", async () => {
it("emit diagnostics when doc is missing for model", async () => {
await ruleTester.expect(`model Foo {}`).toEmitDiagnostics({
code: "@typespec/my-linter/no-foo-model",
message: "Cannot name a model with 'Foo'",
message: "Models must be documented.",
});
});

it("should be valid to use other names", async () => {
await ruleTester.expect(`model Bar {}`).toBeValid();
it("should be valid when doc is provided", async () => {
await ruleTester.expect(`@doc("documentation") model Bar {}`).toBeValid();
});
});
```
Expand Down
Loading