ai-test-gen.mjs 5.78 KB
import { execSync } from "node:child_process";
import fs from "node:fs";
import https from "node:https";
import path from "node:path";

// 配置
const QWEN_API_KEY = process.env.QWEN_API_KEY;
// 默认使用 DashScope OpenAI 兼容接口
const QWEN_API_URL = process.env.QWEN_API_URL || "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
const QWEN_MODEL = process.env.QWEN_MODEL || "qwen-coder-plus";
const GITLAB_TOKEN = process.env.GITLAB_TOKEN || process.env.CI_JOB_TOKEN;
const PROJECT_ID = process.env.CI_PROJECT_ID;
const COMMIT_SHA = process.env.CI_COMMIT_SHA;
// 例如:https://gitlab.com/api/v4
const API_URL = process.env.CI_API_V4_URL;

if (!QWEN_API_KEY) {
	console.error("错误: 未设置 QWEN_API_KEY 环境变量。");
	process.exit(1);
}

if (!GITLAB_TOKEN) {
	console.error("错误: 未设置 GITLAB_TOKEN 环境变量。");
	process.exit(1);
}

if (!PROJECT_ID || !COMMIT_SHA || !API_URL) {
	console.error("错误: 缺少必要的 CI 环境变量 (CI_PROJECT_ID, CI_COMMIT_SHA, CI_API_V4_URL)。");
	process.exit(1);
}

// 发送 HTTPS 请求的辅助函数
function request(url, options, data) {
	return new Promise((resolve, reject) => {
		const req = https.request(url, options, (res) => {
			let body = "";
			res.on("data", (chunk) => body += chunk);
			res.on("end", () => {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					try {
						resolve(JSON.parse(body));
					} catch {
						// 如果不是 JSON
						resolve(body);
					}
				} else {
					reject(new Error(`请求失败,状态码 ${res.statusCode}: ${body}`));
				}
			});
		});

		req.on("error", (e) => reject(e));
		if (data) {
			req.write(typeof data === "string" ? data : JSON.stringify(data));
		}
		req.end();
	});
}

// 获取变更的文件
function getChangedFiles() {
	try {
		// 检查 git 是否可用以及是否在 git 仓库内
		// 在 GitLab CI 中,通常是浅克隆 (shallow fetch)。
		// 我们尝试与上一次提交进行差异比较。
		const output = execSync("git diff --name-only HEAD~1 HEAD", { encoding: "utf8" });
		return output.split("\n").filter(line => line.trim() !== "");
	} catch (error) {
		console.warn("警告: 无法通过 git diff 获取变更文件。假设没有变更或发生错误:", error.message);
		return [];
	}
}

async function generateUnitTest(filePath, content) {
	const prompt = `You are an expert software engineer and unit test writer.
					Your task is to write a comprehensive unit test for the following code file.
					File Path: ${filePath}
					Language: ${path.extname(filePath).slice(1)}

					Source Code:
					\`\`\`${path.extname(filePath).slice(1)}
					${content}
					\`\`\`

					Please provide only the unit test code. Use Vitest or Jest if it's JavaScript/TypeScript.
					If it's another language, use the standard testing framework for that language.
					Wrap the code in a markdown code block.
					Add brief comments explaining the test cases in Chinese.`;

	try {
		const response = await request(QWEN_API_URL, {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"Authorization": `Bearer ${QWEN_API_KEY}`
			}
		}, {
			model: QWEN_MODEL,
			messages: [
				{ role: "system", content: "You are a helpful assistant that writes unit tests." },
				{ role: "user", content: prompt }
			]
		});

		if (response.choices && response.choices.length > 0) {
			return response.choices[0].message.content;
		} else {
			console.error("Qwen API 返回结果为空:", response);
			return null;
		}
	} catch (error) {
		console.error("调用 Qwen API 出错:", error);
		return null;
	}
}

async function postGitLabComment(filePath, testCode) {
	const commentBody = `### 🤖 AI 生成的单元测试 \`${filePath}\`

${testCode}

_Generated by Qwen AI_`;

	const url = `${API_URL}/projects/${PROJECT_ID}/repository/commits/${COMMIT_SHA}/comments`;

	try {
		await request(url, {
			method: "POST",
			headers: {
				"PRIVATE-TOKEN": GITLAB_TOKEN,
				"Content-Type": "application/json"
			}
		}, {
			note: commentBody,
			path: filePath,
			line: 1, // 文件开头
			line_type: "new"
		});
		console.log(`成功为 ${filePath} 发布评论`);
	} catch (error) {
		console.error(`向 GitLab 发布评论失败 (${filePath}):`, error);
		// 如果行内评论失败(例如文件已删除或为二进制文件),则回退到普通评论
		try {
			await request(url, {
				method: "POST",
				headers: {
					"PRIVATE-TOKEN": GITLAB_TOKEN,
					"Content-Type": "application/json"
				}
			}, {
				note: commentBody
			});
			console.log(`成功为 ${filePath} 发布普通评论`);
		} catch (error) {
			console.error("发布普通评论失败:", error);
		}
	}
}

async function main() {
	const changedFiles = getChangedFiles();
	if (changedFiles.length === 0) {
		console.log("最近一次提交没有文件变更。");
		return;
	}

	const targetExtensions = new Set([".js", ".jsx", ".ts", ".tsx", ".uts", ".uvue", ".vue"]);
	const ignorePatterns = [".test.", ".spec.", "node_modules", "dist/", "build/"];

	for (const file of changedFiles) {
		if (!fs.existsSync(file)) {
			console.log(`文件 ${file} 不存在 (可能已删除),跳过。`);
			continue;
		}

		const ext = path.extname(file);
		const isTarget = targetExtensions.has(ext);
		const shouldIgnore = ignorePatterns.some(pattern => file.includes(pattern));

		if (isTarget && !shouldIgnore) {
			console.log(`正在处理 ${file}...`);
			const content = fs.readFileSync(file, "utf8");

			// 限制内容大小以避免超出 Token 限制(估算)
			if (content.length > 20_000) {
				console.log(`文件 ${file} 太大 (${content.length} 字符),跳过。`);
				continue;
			}

			const testCode = await generateUnitTest(file, content);
			if (testCode) {
				await postGitLabComment(file, testCode);
			}
		}
	}
}

main().catch(error => {
	console.error("未捕获的错误:", error);
	process.exit(1);
});