diagnose.ts 5.78 KB

import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { formatDiagnostics, runDiagnostics } from "../utils/diagnostics";

/**
 * 诊断命令选项
 */
export interface DiagnoseOptions {
	fix?: boolean;
	projectPath?: string;
	verbose?: boolean;
}

/**
 * 运行项目诊断
 */
export async function runDiagnose(options: DiagnoseOptions = {}): Promise<number> {
	const { projectPath = process.cwd(), verbose, fix } = options;

	// 验证项目路径
	if (!fs.existsSync(projectPath)) {
		console.error(`✗ 项目路径不存在: ${projectPath}`);
		return 1;
	}

	const packageJsonPath = path.join(projectPath, "package.json");
	if (!fs.existsSync(packageJsonPath)) {
		console.error(`✗ 不是有效的 Venus 项目,package.json 不存在`);
		return 1;
	}

	// 显示诊断开始
	console.log("\n🔍 开始诊断项目...\n");

	try {
		// 运行诊断
		const result = runDiagnostics(projectPath);

		// 显示结果
		console.log(formatDiagnostics(result));

		// 详细模式
		if (verbose) {
			console.log("\n📊 详细信息:");
			console.log(`项目路径: ${result.projectPath}`);
			console.log(`发现问题数: ${result.findings.length}`);
			console.log(`错误数: ${result.findings.filter((f) => f.severity === "error").length}`);
			console.log(`警告数: ${result.findings.filter((f) => f.severity === "warning").length}`);
		}

		// 询问是否修复
		if (fix && !result.success) {
			console.log("\n🔧 自动修复问题...");

			try {
				// 调用修复功能
				const { runFix } = await import("./fix");
				const fixExitCode = await runFix(projectPath, { dependencies: true, config: true });
				if (fixExitCode !== 0) {
					return fixExitCode;
				}

				// 重新诊断
				console.log("\n🔍 重新诊断...");
				const newResult = runDiagnostics(projectPath);
				console.log(formatDiagnostics(newResult));

				if (newResult.success) {
					console.log("\n✅ 所有问题已修复!");
				} else {
					console.log("\n⚠️  部分问题需要手动处理");
				}
			} catch (error) {
				console.error(`\n✗ 自动修复失败: ${error instanceof Error ? error.message : String(error)}`);
				console.log("请手动处理上述问题");
			}
		} else if (!result.success && !fix) {
			console.log("\n💡 提示: 使用 'venus fix --all' 可以自动修复部分问题");
		}

		// 返回适当的退出码
		return result.success ? 0 : 1;
	} catch (error) {
		console.error(`\n✗ 诊断失败: ${error instanceof Error ? error.message : String(error)}`);
		if (verbose && error instanceof Error) {
			console.error(error.stack);
		}
		return 1;
	}
}

/**
 * 运行依赖检查
 */
export function runDependencyCheck(projectPath: string): void {
	console.log("🔍 检查依赖...");

	const packageJsonPath = path.join(projectPath, "package.json");
	if (!fs.existsSync(packageJsonPath)) {
		console.error("✗ package.json 不存在");
		return;
	}

	try {
		// 检查依赖是否正确安装
		const nodeModulesPath = path.join(projectPath, "node_modules");
		if (!fs.existsSync(nodeModulesPath)) {
			console.error("✗ node_modules 不存在,请运行 'pnpm install'");
			return;
		}

		// 检查常见依赖
		const commonDeps = ["react", "vue", "typescript", "vite", "eslint"];
		for (const dep of commonDeps) {
			const depPath = path.join(nodeModulesPath, dep);
			if (fs.existsSync(depPath)) {
				const stats = fs.lstatSync(depPath);
				if (stats.isSymbolicLink()) {
					console.log(`✓ ${dep}: 软链接`);
				} else {
					console.warn(`⚠️  ${dep}: 完整副本`);
				}
			}
		}

		console.log("\n💡 如需修复依赖问题,运行: venus fix --dependencies");
	} catch (error) {
		console.error(`✗ 依赖检查失败: ${error instanceof Error ? error.message : String(error)}`);
	}
}

/**
 * 运行配置检查
 */
export function runConfigCheck(projectPath: string): void {
	console.log("🔍 检查配置...");

	const configFiles = [
		"package.json",
		"tsconfig.json",
		"vite.config.ts",
		".eslintrc.js",
		".prettierrc",
	];

	let missingFiles = 0;
	let existingFiles = 0;

	for (const configFile of configFiles) {
		const configPath = path.join(projectPath, configFile);
		if (fs.existsSync(configPath)) {
			console.log(`✓ ${configFile}`);
			existingFiles++;
		} else {
			console.log(`✗ ${configFile} (缺失)`);
			missingFiles++;
		}
	}

	console.log(`\n📊 配置文件: ${existingFiles} 个存在, ${missingFiles} 个缺失`);

	if (missingFiles > 0) {
		console.log("💡 建议补充缺失的配置文件");
	}
}

/**
 * 运行环境检查
 */
export function runEnvironmentCheck(): void {
	console.log("🔍 检查开发环境...\n");

	// Node.js 版本
	const nodeVersion = process.version;
	const nodeRequired = ">=20.10.0";
	const nodeVersionOk = nodeVersion >= "v20.10.0";
	console.log(`Node.js: ${nodeVersion} ${nodeVersionOk ? "✓" : "✗"} (需要 ${nodeRequired})`);

	// pnpm 版本
	try {
		const pnpmVersion = child_process
			.execSync("pnpm --version", { encoding: "utf8" })
			.trim();
		const pnpmRequired = ">=9.12.0";
		// 简化的版本比较
		const pnpmVersionOk = pnpmVersion >= "9.12.0";
		console.log(`pnpm: ${pnpmVersion} ${pnpmVersionOk ? "✓" : "✗"} (需要 ${pnpmRequired})`);
	} catch {
		console.log("pnpm: ✗ (未安装或无法获取版本)");
	}

	// Git
	try {
		child_process.execSync("git --version", { encoding: "utf8", stdio: ["ignore"] });
		console.log("Git: ✓");
	} catch {
		console.log("Git: ✗ (未安装)");
	}

	// 检查当前目录
	const cwd = process.cwd();
	const packageJsonPath = path.join(cwd, "package.json");
	if (fs.existsSync(packageJsonPath)) {
		console.log(`当前目录: ✓ (Venus 项目)`);
	} else {
		console.log(`当前目录: ✗ (不是 Venus 项目)`);
	}

	console.log("\n💡 如需修复环境问题,请按照上述提示操作");
}