workspace.ts 1.98 KB
import fs from "node:fs";
import path from "node:path";

/**
 * 依赖分析结果接口
 */
export interface DependencyAnalysis {
	/** 是否包含 catalog: 类型的依赖 */
	hasCatalogDeps: boolean;
	/** 是否包含常规版本类型的依赖(如 ^1.0.0、workspace:* 等) */
	hasRegularDeps: boolean;
}

/**
 * 从指定目录向上递归查找 workspace 根目录
 * @param startPath 起始目录
 * @returns workspace 根目录路径,如果未找到返回 null
 */
export function findWorkspaceRoot(startPath: string): null | string {
	let currentPath = path.resolve(startPath);

	while (currentPath !== path.parse(currentPath).root) {
		const workspaceFile = path.join(currentPath, "pnpm-workspace.yaml");
		if (fs.existsSync(workspaceFile)) {
			return currentPath;
		}
		currentPath = path.dirname(currentPath);
	}

	return null;
}

/**
 * 检查指定目录是否在 pnpm workspace 中
 * @param dir 目录路径
 * @returns 如果在 workspace 中返回 true
 */
export function isInWorkspace(dir: string): boolean {
	return findWorkspaceRoot(dir) !== null;
}

/**
 * 分析项目的依赖类型
 * @param packageJsonPath package.json 文件路径
 * @returns 依赖分析结果
 */
export function analyzeProjectDependencies(packageJsonPath: string): DependencyAnalysis {
	try {
		if (!fs.existsSync(packageJsonPath)) {
			return { hasCatalogDeps: false, hasRegularDeps: false };
		}

		const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
		const allDeps = {
			...packageJson.dependencies,
			...packageJson.devDependencies,
			...packageJson.peerDependencies,
			...packageJson.optionalDependencies,
		};

		const deps = Object.values(allDeps);
		const hasCatalogDeps = deps.some((dep) => dep === "catalog:");
		const hasRegularDeps = deps.some((dep) => typeof dep === "string" && dep !== "catalog:");

		return { hasCatalogDeps, hasRegularDeps };
	} catch {
		// 如果解析失败,返回默认值,避免中断流程
		return { hasCatalogDeps: false, hasRegularDeps: false };
	}
}