index.ts 5.47 KB
/**
 * Publint 命令模块
 * 用于检查 monorepo 中的包是否符合 publint 标准
 */

import type { CAC } from "cac";
import type { Result } from "publint";

import { basename, dirname, join } from "node:path";

import {
	colors,
	consola,
	ensureFile,
	findMonorepoRoot,
	generatorContentHash,
	getPackages,
	outputJSON,
	readJSON,
	UNICODE,
} from "@venus/node-utils";

import { publint } from "publint";
import { formatMessage } from "publint/utils";

/**
 * 缓存文件路径
 * 用于存储 publint 检查结果,避免重复检查未变更的包
 */
const CACHE_FILE = join("node_modules", ".cache", "publint", ".pkglintcache.json");

/**
 * Publint 命令选项接口
 */
interface PubLintCommandOptions {
	/** 仅检查模式,不执行程序退出 */
	check?: boolean;
}

/**
 * 获取需要检查的文件列表
 * @param files 指定的文件路径数组,如果为空则获取所有包的 package.json
 * @returns 返回需要检查的 package.json 文件路径数组
 */
async function getLintFiles(files: string[] = []) {
	const lintFiles: string[] = [];

	// 如果指定了文件,则只检查这些文件中的 package.json
	if (files?.length > 0) {
		return files.filter((file) => basename(file) === "package.json");
	}

	// 否则获取 monorepo 中所有包的 package.json
	const { packages } = await getPackages();

	for (const { dir } of packages) {
		lintFiles.push(join(dir, "package.json"));
	}
	return lintFiles;
}

/**
 * 获取缓存文件的完整路径
 * @returns 返回缓存文件的完整路径
 */
function getCacheFile() {
	const root = findMonorepoRoot();
	return join(root, CACHE_FILE);
}

/**
 * 读取缓存数据
 * @param cacheFile 缓存文件路径
 * @returns 返回缓存数据对象,如果读取失败则返回空对象
 */
async function readCache(cacheFile: string) {
	try {
		await ensureFile(cacheFile);
		return await readJSON(cacheFile);
	} catch {
		return {};
	}
}

/**
 * 执行 publint 检查
 * @param files 要检查的文件路径数组
 * @param options 命令选项
 */
async function runPublint(files: string[], { check }: PubLintCommandOptions) {
	const lintFiles = await getLintFiles(files);
	const cacheFile = getCacheFile();

	const cacheData = await readCache(cacheFile);
	const cache: Record<string, { hash: string; result: Result }> = cacheData;

	// 并行检查所有包
	const results = await Promise.all(
		lintFiles.map(async (file) => {
			try {
				const pkgJson = await readJSON(file);

				// 跳过私有包
				if (pkgJson.private) {
					return null;
				}

				// 移除依赖相关字段,避免依赖变更影响缓存命中
				Reflect.deleteProperty(pkgJson, "dependencies");
				Reflect.deleteProperty(pkgJson, "devDependencies");
				Reflect.deleteProperty(pkgJson, "peerDependencies");
				const content = JSON.stringify(pkgJson);
				const hash = generatorContentHash(content);

				// 如果缓存中存在且 hash 匹配,则使用缓存结果,否则执行检查
				const publintResult: Result =
					cache?.[file]?.hash === hash
						? (cache?.[file]?.result ?? [])
						: await publint({
							level: "suggestion",
							pkgDir: dirname(file),
							strict: true,
						});

				// 更新缓存
				cache[file] = {
					hash,
					result: publintResult,
				};

				return { pkgJson, pkgPath: file, publintResult };
			} catch {
				return null;
			}
		}),
	);

	// 保存缓存并打印结果
	await outputJSON(cacheFile, cache);
	printResult(results, check);
}

/**
 * 打印检查结果
 * @param results 检查结果数组
 * @param check 是否为仅检查模式,如果为 true 则不会退出程序
 */
function printResult(
	results: Array<null | {
		pkgJson: Record<string, number | string>;
		pkgPath: string;
		publintResult: Result;
	}>,
	check?: boolean,
) {
	let errorCount = 0;
	let warningCount = 0;
	let suggestionsCount = 0;

	// 遍历所有结果并统计问题数量
	for (const result of results) {
		if (!result) {
			continue;
		}
		const { pkgJson, pkgPath, publintResult } = result;
		const messages = publintResult?.messages ?? [];
		// 如果没有消息则跳过
		if (messages?.length < 1) {
			continue;
		}

		// 打印包路径和所有消息
		consola.log("");
		consola.log(pkgPath);
		for (const message of messages) {
			// 根据消息类型统计数量
			switch (message.type) {
				case "error": {
					errorCount++;

					break;
				}
				case "suggestion": {
					suggestionsCount++;
					break;
				}
				case "warning": {
					warningCount++;

					break;
				}
				// 无默认分支
			}
			// 生成规则链接并打印格式化后的消息
			const ruleUrl = `https://publint.dev/rules#${message.code.toLocaleLowerCase()}`;
			consola.log(`  ${formatMessage(message, pkgJson)}${colors.dim(` ${ruleUrl}`)}`);
		}
	}

	// 打印统计信息
	const totalCount = warningCount + errorCount + suggestionsCount;
	if (totalCount > 0) {
		consola.error(
			colors.red(
				`${UNICODE.FAILURE} ${totalCount} problem (${errorCount} errors, ${warningCount} warnings, ${suggestionsCount} suggestions)`,
			),
		);
		// 如果不是仅检查模式,则退出程序
		!check && process.exit(1);
	} else {
		consola.log(colors.green(`${UNICODE.SUCCESS} No problem`));
	}
}

/**
 * 定义 publint 命令
 * @param cac CAC 实例,用于注册命令
 */
function definePubLintCommand(cac: CAC) {
	cac.command("publint [...files]")
		.usage("检查 monorepo 中的包是否符合 publint 标准。")
		.option("--check", "仅检查模式,只检查错误,不执行程序退出。")
		.action(runPublint);
}

export { definePubLintCommand };