info.ts 8.28 KB
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { findWorkspaceRoot } from "../utils/workspace";

/**
 * 项目信息
 */
export interface ProjectInfo {
	author?: string;
	configs: ConfigInfo;
	dependencies: DependencyInfo;
	description?: string;
	devDependencies: DependencyInfo;
	inWorkspace: boolean;
	license?: string;
	name: string;
	path: string;
	template?: string;
	version: string;
	workspaceRoot?: string;
}

/**
 * 依赖信息
 */
export interface DependencyInfo {
	catalogDeps: number;
	list?: string[];
	regularDeps: number;
	total: number;
}

/**
 * 配置信息
 */
export interface ConfigInfo {
	eslint: boolean;
	exists: string[];
	git: boolean;
	missing: string[];
	prettier: boolean;
	typeScript: boolean;
	vite: boolean;
	workspace: boolean;
}

/**
 * 获取项目信息
 */
export async function getProjectInfo(projectPath?: string): Promise<ProjectInfo> {
	const cwd = projectPath || process.cwd();
	const packageJsonPath = path.join(cwd, "package.json");

	if (!fs.existsSync(packageJsonPath)) {
		throw new Error(`不是有效的项目,package.json 不存在: ${packageJsonPath}`);
	}

	const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
	const workspaceRoot = findWorkspaceRoot(cwd);

	// 分析配置文件
	const configInfo = analyzeConfigFiles(cwd);

	// 分析依赖
	const deps = analyzeDependencies(packageJson);

	// 检测模板类型
	const template = detectTemplate(packageJson);

	return {
		name: packageJson.name || "unknown",
		version: packageJson.version || "0.0.0",
		description: packageJson.description,
		author: packageJson.author ? String(packageJson.author) : undefined,
		license: packageJson.license,
		template,
		path: cwd,
		workspaceRoot: workspaceRoot || undefined,
		inWorkspace: !!workspaceRoot,
		dependencies: deps.dependencies,
		devDependencies: deps.devDependencies,
		configs: configInfo,
	};
}

/**
 * 分析配置文件
 */
function analyzeConfigFiles(projectPath: string): ConfigInfo {
	const configFiles = {
		typescript: ["tsconfig.json", "tsconfig.ts"],
		vite: ["vite.config.ts", "vite.config.mjs", "vite.config.js"],
		eslint: [".eslintrc.js", "eslint.config.mjs", ".eslintrc.cjs"],
		prettier: [".prettierrc", "prettier.config.mjs", ".prettierrc.json"],
		git: [".git"],
		workspace: ["pnpm-workspace.yaml"],
	};

	const exists: string[] = [];
	const missing: string[] = [];

	// 检查配置文件
	for (const [configType, files] of Object.entries(configFiles)) {
		const hasFile = files.some((file) => fs.existsSync(path.join(projectPath, file)));
		if (hasFile) {
			exists.push(configType);
		} else {
			missing.push(configType);
		}
	}

	return {
		typeScript: exists.includes("typescript"),
		vite: exists.includes("vite"),
		eslint: exists.includes("eslint"),
		prettier: exists.includes("prettier"),
		git: exists.includes("git"),
		workspace: exists.includes("workspace"),
		exists,
		missing,
	};
}

/**
 * 分析依赖
 */
function analyzeDependencies(
	packageJson: any,
): { dependencies: DependencyInfo; devDependencies: DependencyInfo } {
	const countDeps = (deps: Record<string, string>) => {
		const list = Object.keys(deps);
		const catalogCount = Object.values(deps).filter((dep) => dep === "catalog:").length;
		return {
			total: list.length,
			catalogDeps: catalogCount,
			regularDeps: list.length - catalogCount,
			list,
		};
	};

	const dependencies = countDeps(packageJson.dependencies || {});
	const devDependencies = countDeps(packageJson.devDependencies || {});

	return { dependencies, devDependencies };
}

/**
 * 检测模板类型
 */
function detectTemplate(packageJson: any): string {
	const deps = packageJson.dependencies || {};

	// 检查是否是 React 项目
	if (deps.react || deps["react-dom"]) {
		if (deps.antd) {
			return "React + Ant Design";
		}
		return "React";
	}

	// 检查是否是 Vue 项目
	if (deps.vue) {
		if (deps["element-plus"]) {
			return "Vue + Element Plus";
		}
		if (deps["ant-design-vue"]) {
			return "Vue + Ant Design Vue";
		}
		return "Vue";
	}

	// 检查其他特征
	if (deps.uniapp) {
		return "UniApp";
	}

	return "未知";
}

/**
 * 格式化项目信息
 */
export function formatProjectInfo(info: ProjectInfo): string {
	const lines: string[] = [];

	lines.push("📋 项目信息\n", `名称: ${info.name}`, `版本: ${info.version}`);
	if (info.description) {
		lines.push(`描述: ${info.description}`);
	}
	if (info.author) {
		lines.push(`作者: ${info.author}`);
	}
	if (info.license) {
		lines.push(`许可证: ${info.license}`);
	}
	if (info.template) {
		lines.push(`模板: ${info.template}`);
	}
	lines.push(`路径: ${info.path}`, `Workspace: ${info.inWorkspace ? "是" : "否"}`);
	if (info.workspaceRoot) {
		lines.push(`Workspace 根目录: ${info.workspaceRoot}`);
	}

	// 依赖信息
	lines.push("\n📦 依赖信息", `生产依赖: ${info.dependencies.total}`, `  - Catalog: ${info.dependencies.catalogDeps}`, `  - 常规: ${info.dependencies.regularDeps}`, `开发依赖: ${info.devDependencies.total}`, `  - Catalog: ${info.devDependencies.catalogDeps}`, `  - 常规: ${info.devDependencies.regularDeps}`, "\n⚙️  配置信息", `TypeScript: ${info.configs.typeScript ? "✓" : "✗"}`, `Vite: ${info.configs.vite ? "✓" : "✗"}`, `ESLint: ${info.configs.eslint ? "✓" : "✗"}`, `Prettier: ${info.configs.prettier ? "✓" : "✗"}`, `Git: ${info.configs.git ? "✓" : "✗"}`, `Workspace: ${info.configs.workspace ? "✓" : "✗"}`);

	return lines.join("\n");
}

/**
 * 显示依赖列表
 */
export function showDependencyList(info: ProjectInfo): string {
	const lines: string[] = [];

	lines.push("📦 依赖详情\n");

	if (info.dependencies.list && info.dependencies.list.length > 0) {
		lines.push("生产依赖:");
		info.dependencies.list.forEach((dep) => {
			lines.push(`  - ${dep}`);
		});
	}

	if (info.devDependencies.list && info.devDependencies.list.length > 0) {
		lines.push("\n开发依赖:");
		info.devDependencies.list.forEach((dep) => {
			lines.push(`  - ${dep}`);
		});
	}

	return lines.join("\n");
}

/**
 * 比较两个项目的依赖差异
 */
export function compareDependencies(
	projectA: ProjectInfo,
	projectB: ProjectInfo,
): string {
	const lines: string[] = [];

	lines.push("📊 依赖对比\n", `项目 A: ${projectA.name}`, `项目 B: ${projectB.name}`);

	// 对比生产依赖
	const depsA = new Set(projectA.dependencies.list || []);
	const depsB = new Set(projectB.dependencies.list || []);

	const onlyInA = [...depsA].filter((dep) => !depsB.has(dep));
	const onlyInB = [...depsB].filter((dep) => !depsA.has(dep));
	const common = [...depsA].filter((dep) => depsB.has(dep));

	lines.push(`\n仅在项目 A 中 (${onlyInA.length}):`);
	if (onlyInA.length > 0) {
		onlyInA.forEach((dep) => lines.push(`  - ${dep}`));
	} else {
		lines.push("  无");
	}

	lines.push(`\n仅在项目 B 中 (${onlyInB.length}):`);
	if (onlyInB.length > 0) {
		onlyInB.forEach((dep) => lines.push(`  - ${dep}`));
	} else {
		lines.push("  无");
	}

	lines.push(`\n共同依赖 (${common.length}):`);
	if (common.length > 0) {
		common.forEach((dep) => lines.push(`  - ${dep}`));
	} else {
		lines.push("  无");
	}

	return lines.join("\n");
}

/**
 * 生成 JSON 格式的项目信息
 */
export function toJson(info: ProjectInfo): string {
	return JSON.stringify(
		{
			name: info.name,
			version: info.version,
			description: info.description,
			template: info.template,
			dependencies: {
				production: info.dependencies.total,
				development: info.devDependencies.total,
			},
			configs: info.configs.exists,
			inWorkspace: info.inWorkspace,
		},
		null,
		2,
	);
}

/**
 * 验证项目配置
 */
export function validateProjectConfig(info: ProjectInfo): boolean {
	// 检查必需配置
	const requiredConfigs = ["eslint", "prettier"];
	const missingRequired = requiredConfigs.filter((config) => !info.configs.exists.includes(config));

	if (missingRequired.length > 0) {
		console.log(`❌ 缺少必需配置: ${missingRequired.join(", ")}`);
		return false;
	}

	// 检查依赖
	if (info.dependencies.total === 0 && info.devDependencies.total === 0) {
		console.log("❌ 项目没有定义任何依赖");
		return false;
	}

	// 检查 TypeScript(推荐)
	if (!info.configs.typeScript) {
		console.log("⚠️  建议启用 TypeScript");
	}

	// 检查 Git(推荐)
	if (!info.configs.git) {
		console.log("⚠️  建议初始化 Git");
	}

	return true;
}