Files
supabase/packages/eslint-config-supabase/__tests__/ratchet-eslint-rules.test.ts
Anthony Lio b13d6c2878 feat(chore): add a lint ratchet for shadcn rules (#51014)
## Problem

shadcn lint rules has been soft landed in #50676 and are now on as
warnings in every app, but nothing stops a PR from adding new violations

linear: FE-4473

## Solution

- moved the ratchet script and its tests from `apps/studio/scripts` to
`packages/eslint-config-supabase` so every app runs one copy
- added a shared rule list,
`packages/eslint-config-supabase/ratchet-rules.json` with the shadcn
rules
- www, docs, design-system, ui-library and learn get `lint-ratchet.yml`
with one job per changed app (triggered by the app, `packages/**` or the
lockfile) + a weekly `lint-ratchet-decrease.yml` (as for studio ratchet)
- package tests run in `eslint-config-supabase-tests.yml`

<!--
## Preview links

If relevant, include links to changed pages for easy review access.

Copy the preview base URL from the Vercel bot comment on this PR. Use
the following table as an example template.

| Site | Live | Preview | Search for |
| -------------- |
-------------------------------------------------------------------------
|
------------------------------------------------------------------------------------------------------------
| ----------------------------- |
| WWW | [/blog/your-post](https://supabase.com/blog/your-post) |
[/blog/your-post](https://zone-www-dot-com-git-branch-name-supabase.vercel.app/blog/your-post)
| unique phrase from the change |
| Docs |
[/docs/guides/your-page](https://supabase.com/docs/guides/your-page) |
[/docs/guides/your-page](https://docs-git-branch-name-supabase.vercel.app/docs/guides/your-page)
| unique phrase from the change |
| Studio | [/dashboard](https://supabase.com/dashboard) |
[/dashboard](https://studio-git-branch-name-supabase.vercel.app/dashboard)
| unique phrase from the change |
| Design system | [/design-system](https://supabase.com/design-system) |
[/design-system](https://design-system-git-branch-name-supabase.vercel.app/design-system)
| unique phrase from the change |
| UI library | [/library](https://supabase.com/library) |
[/library](https://ui-library-git-branch-name-supabase.vercel.app/library)
| unique phrase from the change |
| Knowledge base |
[/kb/guides/your-page](https://supabase.com/kb/guides/your-page) |
[/kb/guides/your-page](https://kb-git-branch-name-supabase.vercel.app/kb/guides/your-page)
| unique phrase from the change |
-->

<!-- ## Additional context

Optionally add any other context or screenshots.

-->

## Review instructions

1. run `pnpm --filter ./apps/www run lint:ratchet`
2. add `p-[13px]` to a `className` in any www component and run it
again. it fails with `shadcn/no-arbitrary-values` and the file name with
`(+1)`
3. revert change
4. run `pnpm --filter eslint-config-supabase test` and see 6 tests pass
5. in ci, check `Ratchet studio lint checks` and the `ratchet (<app>)`
jobs for the apps this pr touches

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Developer Improvements**
* Expanded automated lint checks to cover additional apps and shared
package changes.
* Added checks for arbitrary Tailwind values, unknown classes, and raw
colors across supported apps.
* Added automated baseline updates that can open or update a pull
request when lint counts change.
* Added tests for the lint configuration and support for combining
multiple rule files.
* Updated Studio lint notifications to exclude Shadcn rules with
zero-baseline counts.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-10-02 14:13:59 +03:00

218 lines
6.7 KiB
TypeScript

import { spawnSync } from 'node:child_process'
import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { runRatchet } from '../ratchet-eslint-rules'
const packageRoot = path.resolve(__dirname, '..')
const repoRoot = path.resolve(packageRoot, '..', '..')
const scriptArgvPlaceholder = path.resolve(packageRoot, 'ratchet-eslint-rules.ts')
const tempDirs: string[] = []
afterEach(() => {
vi.restoreAllMocks()
while (tempDirs.length) {
const dir = tempDirs.pop()
if (dir) {
rmSync(dir, { recursive: true, force: true })
}
}
})
describe('ratchet-eslint-rules integration', () => {
it('captures per-file counts when initializing baselines', () => {
const tmp = createTempDir()
const metadataPath = path.join(tmp, 'baseline.json')
const eslintResults = buildEslintResults([
{ filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 1 } },
{ filePath: repoPath('apps/studio/src/b.ts'), rules: { 'no-console': 2 } },
])
const result = invokeRatchet(
['--metadata', metadataPath, '--rule', 'no-console', '--init'],
eslintResults
)
expect(result).toBe(0)
const metadata = JSON.parse(readFileSync(metadataPath, 'utf8'))
expect(metadata.rules['no-console']).toBe(3)
expect(metadata.ruleFiles['no-console']).toEqual({
[relativeToCwd('apps/studio/src/a.ts')]: 1,
[relativeToCwd('apps/studio/src/b.ts')]: 2,
})
})
it('reports offending files when regressions occur and metadata has per-file data', () => {
const tmp = createTempDir()
const metadataPath = path.join(tmp, 'baseline.json')
writeFileSync(
metadataPath,
JSON.stringify(
{
rules: { 'no-console': 2 },
ruleFiles: {
'no-console': {
[relativeToCwd('apps/studio/src/a.ts')]: 2,
},
},
},
null,
2
)
)
const eslintResults = buildEslintResults([
{ filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 3 } },
{ filePath: repoPath('apps/studio/src/b.ts'), rules: { 'no-console': 1 } },
])
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const result = invokeRatchet(
['--metadata', metadataPath, '--rule', 'no-console'],
eslintResults
)
expect(result).toBe(1)
const combinedErrors = errorSpy.mock.calls.map((args) => args.join(' ')).join('\n')
expect(combinedErrors).toContain(`${relativeToCwd('apps/studio/src/a.ts')} (+1)`)
expect(combinedErrors).toContain(`${relativeToCwd('apps/studio/src/b.ts')} (+1)`)
})
it('combines rule ids from repeated --rules-file flags', () => {
const tmp = createTempDir()
const metadataPath = path.join(tmp, 'baseline.json')
const appRulesPath = path.join(tmp, 'app-rules.json')
const sharedRulesPath = path.join(tmp, 'shared-rules.json')
writeFileSync(appRulesPath, JSON.stringify(['no-console']))
writeFileSync(sharedRulesPath, JSON.stringify(['no-debugger']))
const eslintResults = buildEslintResults([
{ filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 1, 'no-debugger': 2 } },
])
const result = invokeRatchet(
[
'--metadata',
metadataPath,
'--rules-file',
appRulesPath,
'--rules-file',
sharedRulesPath,
'--init',
],
eslintResults
)
expect(result).toBe(0)
const baseline = JSON.parse(readFileSync(metadataPath, 'utf8'))
expect(baseline.rules).toEqual({ 'no-console': 1, 'no-debugger': 2 })
})
it('reads rule ids from --rules-file', () => {
const tmp = createTempDir()
const metadataPath = path.join(tmp, 'baseline.json')
const rulesFilePath = path.join(tmp, 'rules.json')
writeFileSync(rulesFilePath, JSON.stringify(['no-console', 'no-debugger']))
const eslintResults = buildEslintResults([
{ filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 1, 'no-debugger': 2 } },
])
const result = invokeRatchet(
['--metadata', metadataPath, '--rules-file', rulesFilePath, '--init'],
eslintResults
)
expect(result).toBe(0)
const metadata = JSON.parse(readFileSync(metadataPath, 'utf8'))
expect(metadata.rules['no-console']).toBe(1)
expect(metadata.rules['no-debugger']).toBe(2)
})
it('falls back gracefully when baseline is missing per-file data', () => {
const tmp = createTempDir()
const metadataPath = path.join(tmp, 'baseline.json')
writeFileSync(
metadataPath,
JSON.stringify(
{
rules: { 'no-console': 1 },
},
null,
2
)
)
const eslintResults = buildEslintResults([
{ filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 2 } },
])
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const result = invokeRatchet(
['--metadata', metadataPath, '--rule', 'no-console'],
eslintResults
)
expect(result).toBe(1)
const combinedErrors = errorSpy.mock.calls.map((args) => args.join(' ')).join('\n')
expect(combinedErrors).toContain('baseline missing file breakdown')
expect(combinedErrors).toContain(`${relativeToCwd('apps/studio/src/a.ts')} (2 current)`)
})
})
describe('ratchet-eslint-rules CLI', () => {
it('runs when invoked through a symlink', () => {
const tmp = createTempDir()
const link = path.join(tmp, 'ratchet-eslint-rules.ts')
symlinkSync(scriptArgvPlaceholder, link)
const tsxCli = createRequire(import.meta.url).resolve('tsx/cli')
const proc = spawnSync(process.execPath, [tsxCli, link], { encoding: 'utf8' })
expect(proc.status).toBe(2)
expect(proc.stderr).toContain('You must provide at least one --rule')
})
})
function buildEslintResults(
files: Array<{ filePath: string; rules: Record<string, number> }>
): unknown[] {
return files.map(({ filePath, rules }) => ({
filePath,
messages: Object.entries(rules).flatMap(([ruleId, count]) =>
Array.from({ length: count }, () => ({ ruleId }))
),
}))
}
function createTempDir(): string {
const dir = mkdtempSync(path.join(os.tmpdir(), 'ratchet-eslint'))
tempDirs.push(dir)
return dir
}
function repoPath(relPath: string): string {
return path.join(repoRoot, relPath)
}
function invokeRatchet(args: string[], eslintResults: unknown[]): number {
const argv = ['node', scriptArgvPlaceholder, ...args]
return runRatchet(argv, () => ({
results: eslintResults as any,
stderr: '',
}))
}
function relativeToCwd(relPath: string): string {
return path.relative(process.cwd(), repoPath(relPath)).split(path.sep).join('/')
}