fix.ts 7.44 KB
import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";

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

/**
 * 修复命令选项
 */
export interface FixOptions {
	all?: boolean;
	config?: boolean;
	dependencies?: boolean;
	dryRun?: boolean;
	force?: boolean;
}

/**
 * 运行项目修复
 */
export async function runFix(projectPath: string, options: FixOptions = {}): Promise<number> {
	const { dependencies, config, all, force, dryRun } = 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🔧 开始修复项目: ${projectPath}\n`);

	if (dryRun) {
		console.log("📋 模拟模式 (dry-run),不会实际执行修复\n");
	}

	try {
		// 先诊断问题
		console.log("🔍 诊断项目问题...");
		const diagnosticResult = runDiagnostics(projectPath);
		console.log(`发现 ${diagnosticResult.findings.filter((f) => f.severity !== "info").length} 个问题\n`);

		// 确定修复范围
		const fixDependencies = dependencies || all;
		const fixConfig = config || all;

		if (!fixDependencies && !fixConfig) {
			console.log("请指定修复内容:--dependencies, --config, 或 --all");
			console.log("使用 --help 查看帮助");
			return 1;
		}

		// 执行修复
		let fixedCount = 0;
		let skippedCount = 0;

		// 修复依赖问题
		if (fixDependencies) {
			console.log("📦 修复依赖问题...");
			const dependencyFixResult = await fixDependenciesProblem(
				projectPath,
				dryRun,
				force,
			);
			if (dependencyFixResult) {
				fixedCount++;
			} else {
				skippedCount++;
			}
		}

		// 修复配置问题
		if (fixConfig) {
			console.log("\n⚙️  修复配置问题...");
			const configFixResult = await fixConfigProblem(projectPath, dryRun, force);
			if (configFixResult) {
				fixedCount++;
			} else {
				skippedCount++;
			}
		}

		// 显示修复结果
		console.log("\n📊 修复结果:");
		console.log(`  - 已修复: ${fixedCount} 项`);
		console.log(`  - 跳过: ${skippedCount} 项`);

		if (!dryRun) {
			console.log("\n💡 建议运行 'venus doctor' 验证修复结果");
		}

		return 0;
	} catch (error) {
		console.error(`\n✗ 修复失败: ${error instanceof Error ? error.message : String(error)}`);
		return 1;
	}
}

/**
 * 修复依赖问题
 */
async function fixDependenciesProblem(
	projectPath: string,
	dryRun: boolean,
	force: boolean,
): Promise<boolean> {
	const workspaceRoot = findWorkspaceRoot(projectPath);
	const nodeModulesPath = path.join(projectPath, "node_modules");

	// 检查是否需要修复
	let needsFix = false;

	if (workspaceRoot) {
		console.log(`  ✓ 检测到 workspace: ${workspaceRoot}`);

		if (fs.existsSync(nodeModulesPath)) {
			console.log(`  ✓ node_modules 存在`);

			// 检查是否有完整的依赖副本
			const reactPath = path.join(nodeModulesPath, "react");
			if (fs.existsSync(reactPath)) {
				try {
					const stats = fs.lstatSync(reactPath);
					if (!stats.isSymbolicLink()) {
						console.log(`  ⚠️  检测到完整依赖副本而非软链接`);
						needsFix = true;
					} else {
						console.log(`  ✓ 依赖已是软链接,无需修复`);
					}
				} catch {
					needsFix = true;
				}
			}
		} else {
			console.log(`  ✓ node_modules 不存在,将创建软链接`);
			needsFix = true;
		}
	} else {
		console.log(`  ℹ️  项目不在 workspace 中,无需特殊处理`);
		return false;
	}

	if (!needsFix && !force) {
		console.log(`  ✓ 依赖配置正常,无需修复`);
		return false;
	}

	// 执行修复
	if (dryRun) {
		console.log(`  [模拟] 将删除 ${nodeModulesPath}`);
		console.log(`  [模拟] 将在 workspace 根目录执行 pnpm install`);
		return true;
	}

	try {
		// 删除子项目 node_modules
		if (fs.existsSync(nodeModulesPath)) {
			console.log(`  🗑️  删除 ${nodeModulesPath}`);
			fs.rmSync(nodeModulesPath, { recursive: true, force: true });
		}

		// 在 workspace 根目录重新安装
		console.log(`  📦 在 workspace 根目录重新安装依赖`);
		console.log(`  📍 安装目录: ${workspaceRoot}`);

		child_process.execSync("pnpm install", {
			cwd: workspaceRoot,
			stdio: "inherit",
		});

		console.log(`  ✅ 依赖修复完成`);
		return true;
	} catch (error) {
		console.error(`  ❌ 依赖修复失败: ${error instanceof Error ? error.message : String(error)}`);
		throw error;
	}
}

/**
 * 修复配置问题
 */
async function fixConfigProblem(
	projectPath: string,
	dryRun: boolean,
	force: boolean,
): Promise<boolean> {
	const configFiles = [
		{ file: "tsconfig.json", template: "tsconfig" },
		{ file: "eslint.config.mjs", template: "eslint" },
		{ file: ".prettierrc.mjs", template: "prettier" },
	];

	let needsFix = false;
	let fixedFiles = 0;

	for (const config of configFiles) {
		const configPath = path.join(projectPath, config.file);
		if (!fs.existsSync(configPath)) {
			console.log(`  ℹ️  缺少配置: ${config.file}`);
			needsFix = true;
		}
	}

	if (!needsFix && !force) {
		console.log(`  ✓ 配置文件齐全,无需修复`);
		return false;
	}

	if (dryRun) {
		console.log(`  [模拟] 将创建缺失的配置文件`);
		return true;
	}

	try {
		// 创建基础配置
		for (const config of configFiles) {
			const configPath = path.join(projectPath, config.file);
			if (!fs.existsSync(configPath)) {
				console.log(`  📝 创建配置: ${config.file}`);
				fs.writeFileSync(configPath, getConfigTemplate(config.template));
				fixedFiles++;
			}
		}

		if (fixedFiles > 0) {
			console.log(`  ✅ 配置修复完成 (${fixedFiles} 个文件)`);
			return true;
		} else {
			console.log(`  ℹ️  配置已经是最新的`);
			return false;
		}
	} catch (error) {
		console.error(`  ❌ 配置修复失败: ${error instanceof Error ? error.message : String(error)}`);
		throw error;
	}
}

function getConfigTemplate(template: string): string {
	switch (template) {
		case "eslint": {
			return [
				"// eslint-disable-next-line n/no-extraneous-import",
				'import { defineConfig } from "@venus/eslint-config";',
				"",
				"export default defineConfig([]);",
				"",
			].join("\n");
		}
		case "prettier": {
			return 'export { default } from "@venus/prettier-config";\n';
		}
		case "tsconfig": {
			return `${JSON.stringify(
				{
					extends: "@venus/tsconfig/base.json",
					compilerOptions: {
						baseUrl: ".",
						paths: {
							"@/*": ["./src/*"],
						},
					},
					include: ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
				},
				null,
				2,
			)}\n`;
		}
		default: {
			throw new Error(`未知的配置模板: ${template}`);
		}
	}
}

/**
 * 快速修复常见问题
 */
export async function quickFix(projectPath: string, issueType: string): Promise<boolean> {
	console.log(`\n🔧 快速修复: ${issueType}`);

	try {
		switch (issueType) {
			case "config": {
				return await fixConfigProblem(projectPath, false, true);
			}
			case "dependencies": {
				return await fixDependenciesProblem(projectPath, false, true);
			}
			default: {
				console.error(`✗ 未知的修复类型: ${issueType}`);
				return false;
			}
		}
	} catch (error) {
		console.error(`✗ 快速修复失败: ${error instanceof Error ? error.message : String(error)}`);
		return false;
	}
}