Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Require listed lint exceptions in Rust and web

Manav Rathi7665ee1ec3e9
diff --git a/.github/checks/change-approval/files.mjs b/.github/checks/change-approval/files.mjs
index 0a3a71d67c..1a7a1f5e72 100644
--- a/.github/checks/change-approval/files.mjs
+++ b/.github/checks/change-approval/files.mjs
@@ -24,6 +24,9 @@ const guardrailFiles = new Set([
"rustfmt.toml",
".rustfmt.toml",
"eslint.config.mjs",
+ "eslint-suppressions.json",
+ "rust/checks/lint-exceptions/suppressions.json",
+ "web/checks/lint-exceptions/suppressions.json",
".prettierrc.json",
"analysis_options.yaml",
]);
diff --git a/.github/checks/change-approval/test.mjs b/.github/checks/change-approval/test.mjs
index 032d9c3f36..574d6d317a 100644
--- a/.github/checks/change-approval/test.mjs
+++ b/.github/checks/change-approval/test.mjs
@@ -656,6 +656,35 @@ test("new lint and formatter configs need approval, including untracked files",
assert.match(scan(t, {}, files, { commit: false }), /^7 guardrail files\n/);
});
+test("suppression lists need approval when added, edited, or deleted", (t) => {
+ const files = {
+ "web/apps/photos/eslint-suppressions.json": "{}\n",
+ "web/packages/new/nested/eslint-suppressions.json": "{}\n",
+ "rust/checks/lint-exceptions/suppressions.json": "{}\n",
+ "web/checks/lint-exceptions/suppressions.json": "{}\n",
+ };
+ for (const [before, after] of [
+ [{}, files],
+ [
+ files,
+ Object.fromEntries(
+ Object.keys(files).map((path) => [path, '{"changed": {}}\n']),
+ ),
+ ],
+ [
+ files,
+ Object.fromEntries(Object.keys(files).map((path) => [path, null])),
+ ],
+ ]) {
+ const { output, summary } = scan(t, before, after, { ci: true });
+ assert.equal(output, 'categories=["guardrail files"]\n');
+ assert.match(summary, /4 guardrail files/);
+ for (const file of Object.keys(files))
+ assert.ok(summary.includes(`\`${file}\``));
+ }
+ assert.match(scan(t, {}, files, { commit: false }), /^4 guardrail files\n/);
+});
+
test("Android lint configurations need approval when added, edited, or deleted", (t) => {
const files = {
"android/build.gradle.kts": "",
diff --git a/rust/checks/lint-exceptions/check.mjs b/rust/checks/lint-exceptions/check.mjs
index 7b6f813f76..1e939b03b3 100644
--- a/rust/checks/lint-exceptions/check.mjs
+++ b/rust/checks/lint-exceptions/check.mjs
@@ -3,11 +3,29 @@ import { existsSync, readFileSync } from "node:fs";
import { relative, resolve, sep } from "node:path";
const root = resolve(process.argv[2]);
+const listPath = "rust/checks/lint-exceptions/suppressions.json";
+const allowed = JSON.parse(readFileSync(resolve(root, listPath), "utf8"));
+const unused = new Map(
+ Object.entries(allowed).map(([path, rules]) => [path, new Set(rules)]),
+);
for (const path of files()) {
const source = readFileSync(resolve(root, path), "utf8");
for (const attribute of attributes(source)) {
- if (!/\bexpect\s*\(/.test(attribute.text)) continue;
+ for (const lint of suppressedLints(attribute.tokens)) {
+ unused.get(path)?.delete(lint);
+ if (!allowed[path]?.includes(lint)) {
+ const line = source
+ .slice(0, attribute.start)
+ .split("\n").length;
+ console.error(
+ `${path}:${line}: ${lint} is not listed in ${listPath}`,
+ );
+ process.exitCode = 1;
+ }
+ }
+ if (!attribute.tokens.some((token) => /^(?:r#)?expect$/.test(token)))
+ continue;
const lints = expectedLints(attribute.text);
if (attribute.inner) {
if (
@@ -27,6 +45,15 @@ for (const path of files()) {
}
}
+for (const [path, rules] of unused) {
+ for (const rule of rules) {
+ console.error(
+ `${path}: ${rule} has no suppression; remove it from ${listPath}`,
+ );
+ process.exitCode = 1;
+ }
+}
+
function expectedLints(attribute) {
const match = attribute.match(/^#!?\[\s*expect\s*\(([\s\S]*)\)\s*\]$/);
if (!match) return undefined;
@@ -66,17 +93,48 @@ function files() {
}
function* attributes(source) {
- const pattern = /^[ \t]*#(!?)\[/gm;
- for (const match of source.matchAll(pattern)) {
- const start = match.index + match[0].indexOf("#");
- const end = attributeEnd(source, start);
- if (end === undefined) continue;
+ const tokens = tokenize(source);
+ for (let i = 0; i < tokens.length; i++) {
+ if (tokens[i].text !== "#") continue;
+ const inner = tokens[i + 1]?.text === "!";
+ const open = i + (inner ? 2 : 1);
+ if (tokens[open]?.text !== "[") continue;
+ let end = open + 1;
+ for (let depth = 1; end < tokens.length; end++) {
+ if (tokens[end].text === "[") depth++;
+ if (tokens[end].text === "]" && --depth === 0) break;
+ }
+ const start = tokens[i].start;
+ const offset = tokens[end].start + 1;
yield {
- end,
- inner: match[1] === "!",
+ inner,
start,
- text: source.slice(start, end),
+ end: offset,
+ text: source.slice(start, offset),
+ tokens: tokens.slice(i, end + 1).map(({ text }) => text),
};
+ i = end;
+ }
+}
+
+function* suppressedLints(tokens) {
+ for (let i = 0; i < tokens.length; i++) {
+ if (
+ !/^(?:r#)?(?:allow|expect)$/.test(tokens[i]) ||
+ tokens[i + 1] !== "("
+ )
+ continue;
+ let lint = "";
+ for (let j = i + 2; j < tokens.length; j++) {
+ const token = tokens[j];
+ if ([",", ")", "reason"].includes(token)) {
+ if (lint) yield lint;
+ lint = "";
+ if (token !== ",") break;
+ } else {
+ lint += token.replace(/^r#/, "");
+ }
+ }
}
}
@@ -132,3 +190,27 @@ function reject(path, source, start) {
console.error(`${path}:${line}: unapproved crate or module lint exception`);
process.exitCode = 1;
}
+
+function tokenize(source) {
+ const lexer =
+ /\/\/[^\n]*|\/\*|[bc]?r(#+)?"[\s\S]*?"\1|[bc]?"(?:\\[\s\S]|[^"\\])*"|b?'(?:\\(?:u\{[\da-fA-F_]+\}|x[\da-fA-F]{2}|[\s\S])|[^'\\\r\n])'|(?:r#)?[a-zA-Z_]\w*|[^\s]/gu;
+ const tokens = [];
+ let match;
+ while ((match = lexer.exec(source))) {
+ const text = match[0];
+ if (text.startsWith("//")) continue;
+ if (text === "/*") {
+ const comments = /\/\*|\*\//g;
+ comments.lastIndex = lexer.lastIndex;
+ for (let depth = 1; depth; ) {
+ const comment = comments.exec(source);
+ if (!comment) throw new Error("Unclosed Rust comment");
+ depth += comment[0] === "/*" ? 1 : -1;
+ }
+ lexer.lastIndex = comments.lastIndex;
+ } else {
+ tokens.push({ text, start: match.index });
+ }
+ }
+ return tokens;
+}
diff --git a/rust/checks/lint-exceptions/suppressions.json b/rust/checks/lint-exceptions/suppressions.json
new file mode 100644
index 0000000000..6209a451e9
--- /dev/null
+++ b/rust/checks/lint-exceptions/suppressions.json
@@ -0,0 +1,73 @@
+{
+ "rust/apps/cli/src/models/export_metadata.rs": [
+ "clippy::trivially_copy_pass_by_ref"
+ ],
+ "rust/apps/cli/src/sync/download.rs": ["clippy::expect_used"],
+ "rust/apps/cli/tests/sync.rs": ["dead_code"],
+ "rust/apps/ensu/src-tauri/src/commands/notes/source.rs": ["unsafe_code"],
+ "rust/apps/ensu/src-tauri/src/commands/system.rs": ["unsafe_code"],
+ "rust/apps/ensu/src-tauri/src/logging.rs": ["clippy::expect_used"],
+ "rust/bindings/frb/locker/src/lib.rs": [
+ "clippy::allow_attributes",
+ "clippy::allow_attributes_without_reason",
+ "clippy::unwrap_used",
+ "unsafe_code"
+ ],
+ "rust/bindings/frb/photos/src/api/usearch_api.rs": ["unsafe_code"],
+ "rust/bindings/frb/photos/src/lib.rs": [
+ "clippy::allow_attributes",
+ "clippy::allow_attributes_without_reason",
+ "clippy::unwrap_used",
+ "unsafe_code"
+ ],
+ "rust/bindings/uniffi/ensu/src/assets.rs": ["clippy::expect_used"],
+ "rust/bindings/wasm/lib/src/logging.rs": ["clippy::expect_used"],
+ "rust/crates/accounts/src/flow.rs": [
+ "clippy::expect_used",
+ "clippy::large_enum_variant"
+ ],
+ "rust/crates/assets/src/download.rs": ["clippy::expect_used"],
+ "rust/crates/assets/src/store.rs": ["clippy::expect_used"],
+ "rust/crates/core/examples/ping.rs": ["clippy::expect_used"],
+ "rust/crates/core/src/crypto/hpke.rs": ["clippy::expect_used"],
+ "rust/crates/core/src/crypto/kdf.rs": ["clippy::expect_used"],
+ "rust/crates/core/src/crypto/secretbox.rs": ["clippy::expect_used"],
+ "rust/crates/core/src/crypto/types.rs": ["clippy::expect_used"],
+ "rust/crates/ensu/src/config.rs": ["clippy::expect_used"],
+ "rust/crates/ensu/src/config/knowledge.rs": ["clippy::expect_used"],
+ "rust/crates/ensu/src/llm/context.rs": ["unsafe_code"],
+ "rust/crates/ensu/src/llm/generate.rs": ["clippy::expect_used"],
+ "rust/crates/ensu/src/model/mod.rs": ["clippy::expect_used"],
+ "rust/crates/ensu/src/retrieval/index.rs": ["unsafe_code"],
+ "rust/crates/ensu/src/transcription/text.rs": ["clippy::expect_used"],
+ "rust/crates/exif/src/isobmff.rs": ["clippy::expect_used"],
+ "rust/crates/image/src/color_management.rs": ["clippy::expect_used"],
+ "rust/crates/location/src/binary.rs": ["clippy::expect_used"],
+ "rust/crates/location/src/city.rs": [
+ "clippy::expect_used",
+ "clippy::trivially_copy_pass_by_ref"
+ ],
+ "rust/crates/location/src/dispute.rs": ["clippy::expect_used"],
+ "rust/crates/location/src/lib.rs": ["clippy::expect_used"],
+ "rust/crates/location/src/urban.rs": ["clippy::expect_used"],
+ "rust/crates/ml/examples/ml_goldens.rs": ["dead_code"],
+ "rust/crates/ml/examples/ocr.rs": ["dead_code"],
+ "rust/crates/ml/src/assets.rs": ["clippy::expect_used"],
+ "rust/crates/ml/src/clip/tokenizer.rs": ["clippy::expect_used"],
+ "rust/crates/ml/src/face/align.rs": ["clippy::expect_used"],
+ "rust/crates/ml/src/ocr/assets.rs": ["clippy::expect_used"],
+ "rust/crates/ml/src/ocr/mod.rs": ["clippy::expect_used"],
+ "rust/crates/ml/src/onnx/providers.rs": ["clippy::expect_used"],
+ "rust/crates/ml/src/onnx/webgpu.rs": ["unsafe_code"],
+ "rust/crates/ml/src/pet/preprocess.rs": ["clippy::expect_used"],
+ "rust/crates/ml/tests/ml_indexing.rs": ["dead_code"],
+ "rust/crates/photos/src/db.rs": ["clippy::expect_used"],
+ "rust/crates/space/src/transport.rs": [
+ "clippy::trivially_copy_pass_by_ref"
+ ],
+ "rust/crates/vecdb/examples/vecdb_bench.rs": ["clippy::expect_used"],
+ "rust/crates/vecdb/src/log.rs": ["clippy::expect_used"],
+ "rust/crates/vecdb/src/store.rs": ["clippy::needless_collect"],
+ "rust/tools/location-dataset/src/city.rs": ["clippy::expect_used"],
+ "rust/tools/location-dataset/src/lib.rs": ["clippy::expect_used"]
+}
diff --git a/rust/checks/lint-exceptions/test.mjs b/rust/checks/lint-exceptions/test.mjs
index 31fac57a00..f64200885a 100644
--- a/rust/checks/lint-exceptions/test.mjs
+++ b/rust/checks/lint-exceptions/test.mjs
@@ -6,12 +6,18 @@ import { dirname, join } from "node:path";
const check = join(import.meta.dirname, "check.mjs");
-for (const source of [
- '#![expect(clippy::unwrap_used, reason = "fixture")]\nfn helper() {}\n',
- '#[expect(dead_code, clippy::unwrap_used, reason = "fixture")]\nmod tests {}\n',
- '#[expect(dead_code, reason = "")]\nmod tests {}\n',
+for (const [source, rules] of [
+ [
+ '#![expect(clippy::unwrap_used, reason = "fixture")]\nfn helper() {}\n',
+ ["clippy::unwrap_used"],
+ ],
+ [
+ '#[expect(dead_code, clippy::unwrap_used, reason = "fixture")]\nmod tests {}\n',
+ ["dead_code", "clippy::unwrap_used"],
+ ],
+ ['#[expect(dead_code, reason = "")]\nmod tests {}\n', ["dead_code"]],
]) {
- const result = run("rust/crates/fixture/src/lib.rs", source);
+ const result = run("rust/crates/fixture/src/lib.rs", source, rules);
assert.equal(result.status, 1, result.stderr);
assert.match(result.stderr, /unapproved crate or module lint exception/);
}
@@ -40,6 +46,7 @@ assert.equal(result.stderr, "");
result = run(
"rust/crates/vecdb/examples/vecdb_bench.rs",
'#![expect(clippy::expect_used, reason = "fixture")]\nfn main() {}\n',
+ ["clippy::expect_used"],
);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr, "");
@@ -47,21 +54,59 @@ assert.equal(result.stderr, "");
result = run(
"rust/crates/vecdb/examples/vecdb_bench.rs",
'#![expect(clippy::expect_used, clippy::unwrap_used, reason = "fixture")]\nfn main() {}\n',
+ ["clippy::expect_used", "clippy::unwrap_used"],
);
assert.equal(result.status, 1, result.stderr);
result = run(
"rust/crates/fixture/src/lib.rs",
'#[expect(clippy::unwrap_used, reason = "fixture")]\nmod frb_generated;\n',
+ ["clippy::unwrap_used"],
);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr, "");
-function run(path, source) {
+for (const source of [
+ '#[expect(dead_code, reason = "fixture")] fn helper() {}',
+ "#[allow(dead_code)] fn helper() {}",
+ '#[cfg_attr(unix, expect(dead_code, reason = "fixture"))] fn helper() {}',
+ '#[r#expect(dead_code, reason = "fixture")] fn helper() {}',
+]) {
+ const path = "rust/crates/fixture/src/lib.rs";
+ const rejected = run(path, source, []);
+ assert.equal(rejected.status, 1, rejected.stderr);
+ assert.match(rejected.stderr, /dead_code is not listed/);
+ const allowed = run(path, source, ["dead_code"]);
+ assert.equal(allowed.status, 0, allowed.stderr);
+}
+
+const path = "rust/crates/fixture/src/lib.rs";
+const suppression = '#[expect(dead_code, reason = "fixture")] fn helper() {}\n';
+for (const source of [
+ suppression + suppression.replace("fn helper", "fn other"),
+ suppression,
+]) {
+ const result = run(path, source);
+ assert.equal(result.status, 0, result.stderr);
+}
+for (const source of ["fn helper() {}", null]) {
+ const result = run(path, source);
+ assert.equal(result.status, 1, result.stderr);
+ assert.match(result.stderr, /dead_code has no suppression/);
+ const cleaned = run(path, source, []);
+ assert.equal(cleaned.status, 0, cleaned.stderr);
+}
+
+function run(path, source, rules = ["dead_code"]) {
const root = mkdtempSync(join(tmpdir(), "ente-rust-lint-exceptions-"));
try {
spawn("git", ["init", "-q"], root);
- write(root, path, source);
+ if (source !== null) write(root, path, source);
+ write(
+ root,
+ "rust/checks/lint-exceptions/suppressions.json",
+ JSON.stringify({ [path]: rules }),
+ );
spawn("git", ["add", "."], root);
return spawnSync(process.execPath, [check, root], { encoding: "utf8" });
} finally {
diff --git a/web/checks/lint-exceptions/check.mjs b/web/checks/lint-exceptions/check.mjs
new file mode 100644
index 0000000000..50ef9a1ac3
--- /dev/null
+++ b/web/checks/lint-exceptions/check.mjs
@@ -0,0 +1,8 @@
+import { execFileSync } from "node:child_process";
+import { resolve } from "node:path";
+
+for (const script of ["lint.mjs", "test.mjs"]) {
+ execFileSync(process.execPath, [resolve(import.meta.dirname, script)], {
+ stdio: "inherit",
+ });
+}
diff --git a/web/checks/lint-exceptions/lint.mjs b/web/checks/lint-exceptions/lint.mjs
new file mode 100644
index 0000000000..d9de5a4b37
--- /dev/null
+++ b/web/checks/lint-exceptions/lint.mjs
@@ -0,0 +1,83 @@
+import { SourceCode } from "eslint";
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { parser } from "typescript-eslint";
+
+const root = resolve(
+ process.argv[2] ?? resolve(import.meta.dirname, "../../.."),
+);
+const listPath = "web/checks/lint-exceptions/suppressions.json";
+const allowed = JSON.parse(readFileSync(resolve(root, listPath), "utf8"));
+const unused = new Map(
+ Object.entries(allowed).map(([path, rules]) => [path, new Set(rules)]),
+);
+const files = execFileSync(
+ "git",
+ [
+ "ls-files",
+ "--cached",
+ "--others",
+ "--exclude-standard",
+ "-z",
+ "--",
+ "web",
+ ],
+ { cwd: root, encoding: "utf8" },
+).split("\0");
+
+for (const path of new Set(files)) {
+ if (!/\.[cm]?[jt]sx?$/.test(path) || !existsSync(resolve(root, path)))
+ continue;
+ const text = readFileSync(resolve(root, path), "utf8");
+ const parsed = parser.parseForESLint(text, {
+ filePath: path,
+ sourceType: "module",
+ ecmaFeatures: { jsx: /x$/.test(path) },
+ });
+ const source = new SourceCode({ text, ...parsed });
+ const { directives, problems } = source.getDisableDirectives();
+ const inline = source.applyInlineConfig();
+ for (const { message, loc } of [...problems, ...inline.problems]) {
+ reject(path, loc.start.line, message);
+ }
+ for (const { type, value, node } of directives) {
+ if (type === "enable") continue;
+ const rules = value
+ .split(",")
+ .map((rule) => rule.trim().replace(/^(['"])(.*)\1$/, "$2"))
+ .filter(Boolean);
+ if (!rules.length)
+ reject(
+ path,
+ node.loc.start.line,
+ "Name the rules being suppressed",
+ );
+ for (const rule of rules) check(path, node.loc.start.line, rule);
+ }
+ for (const { config, loc } of inline.configs) {
+ for (const rule of Object.keys(config.rules))
+ check(path, loc.start.line, rule);
+ }
+}
+
+for (const [path, rules] of unused) {
+ for (const rule of rules) {
+ console.error(
+ `${path}: ${rule} has no suppression; remove it from ${listPath}`,
+ );
+ process.exitCode = 1;
+ }
+}
+
+function check(path, line, rule) {
+ unused.get(path)?.delete(rule);
+ if (!allowed[path]?.includes(rule)) {
+ reject(path, line, `${rule} is not listed in ${listPath}`);
+ }
+}
+
+function reject(path, line, message) {
+ console.error(`${path}:${line}: ${message}`);
+ process.exitCode = 1;
+}
diff --git a/web/checks/lint-exceptions/suppressions.json b/web/checks/lint-exceptions/suppressions.json
new file mode 100644
index 0000000000..57aeb1367e
--- /dev/null
+++ b/web/checks/lint-exceptions/suppressions.json
@@ -0,0 +1,79 @@
+{
+ "web/apps/albums/src/public-album/page/PublicAlbumPage.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/albums/src/public-album/upload/components/Upload.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/albums/src/public-album/upload/pipeline/thumbnail.ts": [
+ "@typescript-eslint/prefer-promise-reject-errors"
+ ],
+ "web/apps/albums/src/public-album/viewer/components/FileViewer.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/photos/src/components/Collections/CollectionShare.tsx": [
+ "@typescript-eslint/no-unnecessary-condition"
+ ],
+ "web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/photos/src/components/PlanSelector.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/photos/src/components/Sidebar.tsx": [
+ "@typescript-eslint/no-floating-promises"
+ ],
+ "web/apps/photos/src/components/Upload.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/photos/src/components/WatchFolder.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/photos/src/pages/gallery.tsx": ["react-hooks/exhaustive-deps"],
+ "web/apps/photos/src/services/export.ts": [
+ "@typescript-eslint/no-non-null-asserted-optional-chain",
+ "@typescript-eslint/no-unnecessary-condition"
+ ],
+ "web/apps/photos/src/services/watch.ts": [
+ "@typescript-eslint/no-misused-promises"
+ ],
+ "web/apps/space/src/components/MessagesPage.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/apps/space/src/hooks/use-pwa-install-prompt.ts": [
+ "@typescript-eslint/no-deprecated"
+ ],
+ "web/packages/base/kv.ts": ["@typescript-eslint/no-base-to-string"],
+ "web/packages/base/log.ts": [
+ "@typescript-eslint/no-base-to-string",
+ "@typescript-eslint/no-unsafe-argument",
+ "@typescript-eslint/no-unsafe-assignment"
+ ],
+ "web/packages/gallery/components/viewer/FileViewer.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/packages/gallery/components/viewer/photoswipe-core.ts": [
+ "@typescript-eslint/no-unnecessary-condition"
+ ],
+ "web/packages/gallery/services/save-core.ts": [
+ "@typescript-eslint/no-unnecessary-condition"
+ ],
+ "web/packages/gallery/services/upload/thumbnail.ts": [
+ "@typescript-eslint/prefer-promise-reject-errors"
+ ],
+ "web/packages/gallery/utils/leaflet.ts": [
+ "@typescript-eslint/no-require-imports"
+ ],
+ "web/packages/new/photos/components/EditLocationDialog.tsx": [
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/packages/new/photos/components/ImageEditorOverlay.tsx": [
+ "@typescript-eslint/no-floating-promises",
+ "@typescript-eslint/no-unnecessary-condition",
+ "@typescript-eslint/prefer-promise-reject-errors",
+ "react-hooks/exhaustive-deps"
+ ],
+ "web/packages/new/photos/services/search/worker.ts": [
+ "@typescript-eslint/no-unnecessary-condition"
+ ]
+}
diff --git a/web/checks/lint-exceptions/test.mjs b/web/checks/lint-exceptions/test.mjs
new file mode 100644
index 0000000000..a00737ad0e
--- /dev/null
+++ b/web/checks/lint-exceptions/test.mjs
@@ -0,0 +1,72 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const check = join(import.meta.dirname, "lint.mjs");
+const root = mkdtempSync(join(tmpdir(), "ente-web-lint-exceptions-"));
+const file = "web/example.tsx";
+try {
+ assert.equal(spawnSync("git", ["init", "-q"], { cwd: root }).status, 0);
+ mkdirSync(join(root, "web/checks/lint-exceptions"), { recursive: true });
+ for (const source of [
+ '// eslint-disable-next-line no-console -- Intentional diagnostic\nconsole.log("hello");',
+ 'console.log("hello"); // eslint-disable-line no-console',
+ '/* eslint-disable "no-console" */\nconsole.log("hello");',
+ '/* eslint no-console: "off" */\nconsole.log("hello");',
+ '{/* eslint-disable-next-line no-console */}\nconsole.log("hello");',
+ ]) {
+ assert.equal(run(source).status, 1);
+ const allowed = run(source, { [file]: ["no-console"] });
+ assert.equal(allowed.status, 0, allowed.stderr);
+ assert.equal(
+ run(source, { "web/other.tsx": ["no-console"] }).status,
+ 1,
+ );
+ }
+ assert.equal(
+ run("/* eslint-disable */", { [file]: ["no-console"] }).status,
+ 1,
+ );
+ assert.equal(
+ run("/* eslint-disable no-console, no-alert */", {
+ [file]: ["no-console"],
+ }).status,
+ 1,
+ );
+ assert.equal(run("/* eslint-enable no-console */").status, 0);
+ assert.equal(
+ run('const example = "/* eslint-disable no-console */";').status,
+ 0,
+ );
+ assert.equal(
+ run("const example = <div>eslint-disable no-console</div>;").status,
+ 0,
+ );
+ const suppression =
+ '// eslint-disable-next-line no-console\nconsole.log("hello");\n';
+ for (const source of [suppression + suppression, suppression]) {
+ const result = run(source, { [file]: ["no-console"] });
+ assert.equal(result.status, 0, result.stderr);
+ }
+ for (const source of ['console.log("hello");', null]) {
+ const result = run(source, { [file]: ["no-console"] });
+ assert.equal(result.status, 1, result.stderr);
+ assert.match(result.stderr, /no-console has no suppression/);
+ const cleaned = run(source);
+ assert.equal(cleaned.status, 0, cleaned.stderr);
+ }
+} finally {
+ rmSync(root, { recursive: true });
+}
+
+function run(source, allowed = {}) {
+ if (source === null) rmSync(join(root, file), { force: true });
+ else writeFileSync(join(root, file), source);
+ writeFileSync(
+ join(root, "web/checks/lint-exceptions/suppressions.json"),
+ JSON.stringify(allowed),
+ );
+ return spawnSync(process.execPath, [check, root], { encoding: "utf8" });
+}