lint-changed.mjs
1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env node
import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
const changedFiles = resolveChangedFiles().filter((file) => fs.existsSync(path.join(repoRoot, file)));
if (changedFiles.length === 0) {
console.log("[lint-changed] no changed files detected");
process.exit(0);
}
runPrettier(changedFiles);
const eslintFiles = changedFiles.filter((file) => /\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx|vue)$/.test(file));
if (eslintFiles.length > 0) {
runCommand("pnpm", ["exec", "eslint", "--max-warnings=0", ...eslintFiles]);
}
const stylelintFiles = changedFiles.filter((file) => /\.(?:css|scss|vue)$/.test(file));
if (stylelintFiles.length > 0) {
runCommand("pnpm", ["exec", "stylelint", "--max-warnings=0", ...stylelintFiles]);
}
console.log("[lint-changed] passed");
function resolveChangedFiles() {
const fromArgs = process.argv.slice(2).filter(Boolean);
if (fromArgs.length > 0) {
return normalize(fromArgs);
}
const combined = [
...runGit("git diff --name-only"),
...runGit("git diff --cached --name-only"),
...runGit("git ls-files --others --exclude-standard"),
];
return normalize(combined);
}
function runGit(command) {
const result = childProcess.spawnSync(command, {
cwd: repoRoot,
shell: true,
encoding: "utf8",
});
if (result.status !== 0 || !result.stdout) {
return [];
}
return result.stdout.split(/\r?\n/).filter(Boolean);
}
function normalize(files) {
return [...new Set(files.map((file) => file.replaceAll("\\", "/")))];
}
function runPrettier(files) {
runCommand("pnpm", ["exec", "prettier", "--check", "--ignore-unknown", ...files]);
}
function runCommand(command, args) {
const result = childProcess.spawnSync(command, args, {
cwd: repoRoot,
shell: process.platform === "win32",
stdio: "inherit",
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}