lint-changed.mjs 1.99 KB
#!/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);
	}
}