diagnostics.ts 10.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
import type { DependencyAnalysis } from "./workspace";

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

import { analyzeProjectDependencies, findWorkspaceRoot } from "./workspace";

/**
 * 诊断结果接口
 */
export interface DiagnosticResult {
	findings: DiagnosticFinding[];
	projectPath: string;
	recommendations: string[];
	success: boolean;
}

/**
 * 诊断发现接口
 */
export interface DiagnosticFinding {
	category: "config" | "dependencies" | "files" | "workspace";
	details?: string;
	message: string;
	severity: "error" | "info" | "warning";
}

/**
 * 检查项目配置文件
 */
function checkConfigFiles(projectPath: string): DiagnosticFinding[] {
	const findings: DiagnosticFinding[] = [];
	const configFiles = [
		{ file: "package.json", required: true },
		{ file: "tsconfig.json", required: false },
		{ file: "vite.config.ts", required: false },
		{ file: "vite.config.mjs", required: false },
		{ file: ".eslintrc.js", required: false },
		{ file: "eslint.config.mjs", required: false },
		{ file: ".prettierrc", required: false },
		{ file: "prettier.config.mjs", required: false },
		{ file: ".gitignore", required: false },
		{ file: ".env.example", required: false },
	];

	for (const config of configFiles) {
		const configPath = path.join(projectPath, config.file);
		if (fs.existsSync(configPath)) {
			findings.push({
				severity: "info",
				category: "config",
				message: `配置文件存在: ${config.file}`,
			});
		} else if (config.required) {
			findings.push({
				severity: "error",
				category: "config",
				message: `缺少必需的配置文件: ${config.file}`,
			});
		} else {
			findings.push({
				severity: "warning",
				category: "config",
				message: `建议添加配置文件: ${config.file}`,
			});
		}
	}

	return findings;
}

/**
 * 检查 package.json 有效性
 */
function checkPackageJson(projectPath: string): DiagnosticFinding[] {
	const findings: DiagnosticFinding[] = [];
	const packageJsonPath = path.join(projectPath, "package.json");

	if (!fs.existsSync(packageJsonPath)) {
		return [
			{
				severity: "error",
				category: "files",
				message: "package.json 文件不存在",
			},
		];
	}

	try {
		const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));

		// 检查必需字段
		if (!packageJson.name) {
			findings.push({
				severity: "error",
				category: "config",
				message: "package.json 缺少 name 字段",
			});
		}

		if (!packageJson.version) {
			findings.push({
				severity: "warning",
				category: "config",
				message: "package.json 缺少 version 字段",
			});
		}

		// 检查 scripts
		if (!packageJson.scripts || Object.keys(packageJson.scripts).length === 0) {
			findings.push({
				severity: "warning",
				category: "config",
				message: "package.json 缺少 scripts 字段",
			});
		}

		// 检查依赖
		if (!packageJson.dependencies && !packageJson.devDependencies) {
			findings.push({
				severity: "info",
				category: "dependencies",
				message: "项目没有定义任何依赖",
			});
		}
	} catch (error) {
		findings.push({
			severity: "error",
			category: "files",
			message: `package.json 格式错误: ${error instanceof Error ? error.message : String(error)}`,
		});
	}

	return findings;
}

/**
 * 检查依赖问题
 */
function checkDependencyIssues(
	projectPath: string,
	dependencyAnalysis: DependencyAnalysis,
	workspaceRoot: null | string,
): DiagnosticFinding[] {
	const findings: DiagnosticFinding[] = [];
	const nodeModulesPath = path.join(projectPath, "node_modules");

	// 检查 node_modules 状态
	if (fs.existsSync(nodeModulesPath)) {
		if (workspaceRoot && dependencyAnalysis.hasCatalogDeps) {
			// 检查是否有完整的依赖副本(而不是软链接)
			const reactPath = path.join(nodeModulesPath, "react");
			if (fs.existsSync(reactPath)) {
				try {
					const stats = fs.lstatSync(reactPath);
					if (!stats.isSymbolicLink()) {
						findings.push({
							severity: "warning",
							category: "dependencies",
							message: "检测到完整的依赖副本而非软链接",
							details: "建议使用 'venus fix --dependencies' 修复",
						});
					}
				} catch {
					// 无法判断,忽略
				}
			}
		}
	} else {
		findings.push({
			severity: "error",
			category: "dependencies",
			message: "依赖未安装,node_modules 目录不存在",
			details: "请运行 'pnpm install' 或 'venus fix --dependencies'",
		});
	}

	// 检查依赖类型混合
	if (dependencyAnalysis.hasCatalogDeps && dependencyAnalysis.hasRegularDeps) {
		findings.push({
			severity: "info",
			category: "dependencies",
			message: "项目同时包含 catalog: 依赖和常规版本依赖",
			details: "catalog: 依赖将在 workspace 根目录安装,常规依赖将在项目目录安装",
		});
	}

	// 检查缺少依赖
	if (!dependencyAnalysis.hasCatalogDeps && !dependencyAnalysis.hasRegularDeps) {
		findings.push({
			severity: "warning",
			category: "dependencies",
			message: "项目没有定义任何依赖",
		});
	}

	return findings;
}

/**
 * 检查 workspace 环境
 */
function checkWorkspaceEnvironment(projectPath: string): DiagnosticFinding[] {
	const findings: DiagnosticFinding[] = [];
	const workspaceRoot = findWorkspaceRoot(projectPath);

	if (!workspaceRoot) {
		findings.push({
			severity: "info",
			category: "workspace",
			message: "项目不在 pnpm workspace 中",
			details: "这是一个独立项目,依赖将正常安装",
		});
		return findings;
	}

	findings.push({
		severity: "info",
		category: "workspace",
		message: `检测到 pnpm workspace: ${workspaceRoot}`,
	});

	// 检查 workspace 配置文件
	const workspaceConfig = path.join(workspaceRoot, "pnpm-workspace.yaml");
	if (fs.existsSync(workspaceConfig)) {
		findings.push({
			severity: "info",
			category: "workspace",
			message: "Workspace 配置文件存在",
		});
	} else {
		findings.push({
			severity: "error",
			category: "workspace",
			message: "Workspace 配置文件缺失",
			details: `${workspaceRoot} 中缺少 pnpm-workspace.yaml`,
		});
	}

	return findings;
}

/**
 * 执行完整诊断
 */
export function runDiagnostics(projectPath: string): DiagnosticResult {
	const findings: DiagnosticFinding[] = [];
	const recommendations: string[] = [];

	// 检查 workspace 环境
	const workspaceFindings = checkWorkspaceEnvironment(projectPath);
	findings.push(...workspaceFindings);

	// 检查 package.json
	const packageJsonFindings = checkPackageJson(projectPath);
	findings.push(...packageJsonFindings);

	// 分析依赖
	const packageJsonPath = path.join(projectPath, "package.json");
	const dependencyAnalysis = analyzeProjectDependencies(packageJsonPath);
	const workspaceRoot = findWorkspaceRoot(projectPath);

	// 检查依赖问题
	const dependencyFindings = checkDependencyIssues(
		projectPath,
		dependencyAnalysis,
		workspaceRoot,
	);
	findings.push(...dependencyFindings);

	// 检查配置文件
	const configFindings = checkConfigFiles(projectPath);
	findings.push(...configFindings);

	// 生成建议
	const errors = findings.filter((f) => f.severity === "error");
	const warnings = findings.filter((f) => f.severity === "warning");

	if (errors.length > 0) {
		recommendations.push("发现严重问题,建议立即修复");
	}

	if (warnings.length > 0) {
		recommendations.push("发现警告问题,建议尽快处理");
	}

	// 根据具体问题提供针对性建议
	if (findings.some((f) => f.message.includes("完整的依赖副本"))) {
		recommendations.push("运行 'venus fix --dependencies' 修复依赖问题");
	}

	if (findings.some((f) => f.message.includes("依赖未安装"))) {
		recommendations.push("运行 'venus fix --dependencies' 或 'pnpm install' 安装依赖");
	}

	if (errors.length === 0 && warnings.length === 0) {
		recommendations.push("项目配置正常,无需修复");
	}

	return {
		success: errors.length === 0,
		projectPath,
		findings,
		recommendations,
	};
}

/**
 * 格式化诊断结果为可读文本
 */
export function formatDiagnostics(result: DiagnosticResult): string {
	const lines: string[] = [];

	lines.push(`\n📋 项目诊断报告`, `\n项目路径: ${result.projectPath}`, `\n诊断结果: ${result.success ? "✓ 正常" : "✗ 发现问题"}`);

	const errors = result.findings.filter(f => f.severity === "error");
	const warnings = result.findings.filter(f => f.severity === "warning");
	const infos = result.findings.filter(f => f.severity === "info");

	// 只显示真正的问题(错误和警告)
	if (errors.length > 0 || warnings.length > 0) {
		lines.push(`\n发现 ${errors.length + warnings.length} 个问题:`);
		
		if (errors.length > 0) {
			lines.push(`  ❌ 错误: ${errors.length}个`);
		}
		if (warnings.length > 0) {
			lines.push(`  ⚠️  警告: ${warnings.length}个`);
		}

		result.findings
			.filter(f => f.severity !== "info")
			.forEach((finding, index) => {
				const icon = finding.severity === "error" ? "✗" : "⚠️";
				lines.push(`\n  ${index + 1}. ${icon} [${finding.category}] ${finding.message}`);
				if (finding.details) {
					lines.push(`     详情: ${finding.details}`);
				}
			});
	} else {
		lines.push("\n✓ 未发现严重问题");
	}

	// 单独显示信息性内容
	if (infos.length > 0) {
		lines.push(`\n📊 项目信息 (${infos.length}项):`);
		infos.forEach((finding, index) => {
			lines.push(`  ${index + 1}. ℹ️ [${finding.category}] ${finding.message}`);
			if (finding.details) {
				lines.push(`     详情: ${finding.details}`);
			}
		});
	}

	if (result.recommendations.length > 0) {
		lines.push(`\n💡 建议:`);
		result.recommendations.forEach((rec) => {
			lines.push(`  - ${rec}`);
		});
	}

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

/**
 * 检查依赖冲突
 */
export async function checkDependencyConflicts(projectPath: string): Promise<string[]> {
	const conflicts: string[] = [];
	const packageJsonPath = path.join(projectPath, "package.json");

	if (!fs.existsSync(packageJsonPath)) {
		return conflicts;
	}

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

		// 检查常见冲突
		if (allDeps.vue && allDeps.vue !== "catalog:") {
			// 检查是否在 workspace 中
			const workspaceRoot = findWorkspaceRoot(projectPath);
			if (workspaceRoot) {
				conflicts.push(
					`项目在 workspace 中但 vue 未使用 catalog:,可能导致版本不一致`,
				);
			}
		}

		// 检查对等依赖冲突
		if (packageJson.peerDependencies) {
			for (const [dep, range] of Object.entries(packageJson.peerDependencies)) {
				if (allDeps[dep] && typeof range === "string") {
					// 简化的版本冲突检查
					conflicts.push(
						`对等依赖 ${dep} 与普通依赖 ${dep} 可能存在版本冲突`,
					);
				}
			}
		}
	} catch {
		// 解析失败,跳过冲突检查
	}

	return conflicts;
}