跳到正文

个人记录

config.yml 生成器

水星湖约 19 分钟
原文

这是 2026年9月11日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年9月5日
收录
2026年9月11日
更新
2026年11月9日
篇幅
约 19 分钟
获赞
1

版本

  1. v2当前
  2. v1
JavaScript
// ==UserScript==
// @name         洛谷测试点 config.yml 生成器
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  在洛谷题目测试点配置页面自动生成 config.yml,方便打包上传数据。
// @author       Assistant
// @match        https://www.luogu.com.cn/problem/*/edit*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    console.log("[ConfigGen] 脚本已加载,等待进入测试点配置页面...");

    // ========== 核心逻辑:获取与解析数据 ==========
    async function fetchLatestData() {
        let cases = null;
        let source = "none";

        try {
            // 策略 1:使用洛谷的内容接口请求最新保存的数据
            console.log("[ConfigGen] 尝试通过 content-only 接口获取最新数据...");
            const res = await fetch(location.href, {
                headers: { 'x-luogu-type': 'content-only' }
            });
            if (res.ok) {
                const json = await res.json();
                if (json.code === 200) {
                    cases = json.currentData?.problemDataSetting?.cases;
                    source = "API";
                } else {
                    console.warn("[ConfigGen] API 响应不为 200", json);
                }
            }
        } catch (apiErr) {
            console.warn("[ConfigGen] API 获取失败,准备回退到 DOM 解析:", apiErr);
        }

        // 策略 2:回退到页面自带的 `<script id="lentille-context">`
        if (!cases || !Array.isArray(cases)) {
            try {
                console.log("[ConfigGen] 尝试从 lentille-context 中读取数据...");
                const contextStr = document.getElementById('lentille-context')?.textContent;
                if (!contextStr) throw new Error("页面中找不到 lentille-context 元素。");

                const json = JSON.parse(contextStr);
                cases = json.data?.problemDataSetting?.cases;
                source = "DOM";

                if (!cases || !Array.isArray(cases)) {
                    throw new Error("成功解析了 JSON,但没有找到 problemDataSetting.cases 字段!");
                }
            } catch (domErr) {
                console.error("[ConfigGen] DOM 解析也失败:", domErr);
                throw new Error("无法获取测试点数据,详情请看 F12 控制台日志。");
            }
        }

        console.log(`[ConfigGen] 成功获取到测试点数据,数据来源: ${source}`, cases);
        return cases;
    }

    // ========== 核心逻辑:生成 Yaml 字符串 ==========
    function generateYaml(cases) {
        let yamlStr = '';

        cases.forEach((c, index) => {
            try {
                // 洛谷的 cases 数组举例:
                //["/data/1248379/subtask4_2.in", "/data/1248379/subtask4_2.ans", 2500, 1048576, 20, 0, 4]
                // 下标 0: 输入文件
                // 下标 1: 输出文件
                // 下标 2: 时间限制
                // 下标 3: 内存限制
                // 下标 4: 分数
                // 下标 5: (未知/保留字段)
                // 下标 6: Subtask ID

                let inPath = c[0];
                if (!inPath || typeof inPath !== 'string') {
                    console.warn(`[ConfigGen] 警告:第 ${index + 1} 个测试点缺少输入文件路径,已跳过。`, c);
                    return;
                }

                let fileName = inPath.split('/').pop(); // 从类似 /data/12345/a.in 中提取 a.in
                let timeLimit = c[2];
                let memoryLimit = c[3];
                let score = c[4];
                let subtaskId = c[6]; // 修改:把 subtaskId 的读取下标修正为了 6

                yamlStr += `${fileName}:\n`;

                // 仅当存在且不为空时才写入(YAML要求2个空格缩进)
                if (timeLimit !== null && timeLimit !== undefined) {
                    yamlStr += `  timeLimit: ${timeLimit}\n`;
                }
                if (memoryLimit !== null && memoryLimit !== undefined) {
                    yamlStr += `  memoryLimit: ${memoryLimit}\n`;
                }
                if (score !== null && score !== undefined) {
                    yamlStr += `  score: ${score}\n`;
                }
                if (subtaskId !== null && subtaskId !== undefined) {
                    yamlStr += `  subtaskId: ${subtaskId}\n`;
                }
                // 移除了 isPretest 的判定和写入

                yamlStr += '\n';

            } catch(e) {
                console.error(`[ConfigGen] 处理第 ${index + 1} 个测试点时出错:`, e, c);
                throw new Error(`处理第 ${index + 1} 个测试点时数据格式异常!`);
            }
        });

        return yamlStr.trim();
    }

    // ========== 交互与 UI:处理点击与弹窗 ==========
    async function handleGenerate() {
        const btn = document.getElementById('lg-config-gen-btn');
        btn.innerText = '正在获取...';
        btn.disabled = true;

        try {
            const cases = await fetchLatestData();
            if (!cases || cases.length === 0) {
                throw new Error("获取到的测试点列表为空!\n如果你刚刚更改了数据,请先点击洛谷页面上的【保存修改】,然后再生成 config.yml。");
            }

            const yamlContent = generateYaml(cases);
            if (!yamlContent) {
                throw new Error("生成的 YAML 内容为空,可能是数据解析逻辑不匹配。");
            }

            showModal(yamlContent);
        } catch (err) {
            console.error("[ConfigGen] 捕获到异常:", err);
            alert(`生成失败!\n\n错误信息:\n${err.message}\n\n请按 F12 打开控制台查看详细信息并反馈给开发者。`);
        } finally {
            if (btn) {
                btn.innerText = '生成 config.yml';
                btn.disabled = false;
            }
        }
    }

    function showModal(yamlContent) {
        let existing = document.getElementById('lg-config-modal');
        if (existing) existing.remove();

        const modal = document.createElement('div');
        modal.id = 'lg-config-modal';
        modal.style.cssText = `
            position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
            background: white; padding: 20px; border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5); z-index: 999999;
            width: 500px; max-width: 90vw; display: flex; flex-direction: column; gap: 15px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        `;

        modal.innerHTML = `
            <h3 style="margin: 0; color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px;">🎉 config.yml 生成成功</h3>
            <p style="margin: 0; font-size: 13px; color: #666;">
                请确保你已经<b>保存了页面上的修改</b>。如果有缺漏可在此框中手动修改。
            </p>
            <textarea id="lg-config-textarea" style="width: 100%; height: 300px; font-family: Consolas, monospace; padding: 10px; box-sizing: border-box; resize: vertical; background: #f9f9f9; border: 1px solid #ccc; border-radius: 4px;"></textarea>
            <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 5px;">
                <button id="lg-config-copy" style="padding: 8px 15px; cursor: pointer; background: #3498db; color: white; border: none; border-radius: 4px;">📋 复制内容</button>
                <button id="lg-config-download" style="padding: 8px 15px; cursor: pointer; background: #2ecc71; color: white; border: none; border-radius: 4px;">⬇️ 下载文件</button>
                <button id="lg-config-close" style="padding: 8px 15px; cursor: pointer; background: #e74c3c; color: white; border: none; border-radius: 4px;">❌ 关闭</button>
            </div>
        `;

        document.body.appendChild(modal);

        // 绑定事件
        document.getElementById('lg-config-textarea').value = yamlContent;

        document.getElementById('lg-config-copy').onclick = (e) => {
            const ta = document.getElementById('lg-config-textarea');
            ta.select();
            document.execCommand('copy');
            e.target.innerText = '✔️ 已复制!';
            setTimeout(() => e.target.innerText = '📋 复制内容', 2000);
        };

        document.getElementById('lg-config-download').onclick = () => {
            const taContent = document.getElementById('lg-config-textarea').value;
            const blob = new Blob([taContent], { type: 'text/yaml' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'config.yml';
            a.click();
            URL.revokeObjectURL(url);
        };

        document.getElementById('lg-config-close').onclick = () => modal.remove();
    }

    // ========== 监听器:只在测试点页面显示按钮 ==========
    function injectButton() {
        if (document.getElementById('lg-config-gen-btn')) return;

        const btn = document.createElement('button');
        btn.id = 'lg-config-gen-btn';
        btn.innerText = '生成 config.yml';
        btn.style.cssText = `
            position: fixed; bottom: 30px; right: 30px; z-index: 99998;
            padding: 12px 20px; background-color: #e74c3c; color: white;
            border: none; border-radius: 5px; cursor: pointer;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3); font-family: inherit;
            font-size: 15px; font-weight: bold; transition: background 0.3s;
        `;
        btn.onmouseover = () => btn.style.backgroundColor = '#c0392b';
        btn.onmouseout = () => btn.style.backgroundColor = '#e74c3c';
        btn.onclick = handleGenerate;
        document.body.appendChild(btn);
    }

    // 动态检测是否为测试点选项卡
    setInterval(() => {
        const isTestcaseTab = location.href.includes('/edit') && location.href.includes('tab=testcase');
        let btn = document.getElementById('lg-config-gen-btn');

        if (isTestcaseTab) {
            injectButton();
            if (btn) btn.style.display = 'block';
        } else {
            if (btn) btn.style.display = 'none';
        }
    }, 1000);

})();