版本比较
config.yml 生成器
正文
增加 3 行删除 237 行
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362371234```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);
})();新建一个收藏夹,url 里面写下面这一坨,在编辑题目页面点收藏夹就会自动下载。```javascript:(async()=>{try{const pid=location.pathname.match(/^\/problem\/([^/]+)\/edit/)?.[1];if(!pid)throw Error("请先打开洛谷题目编辑页面");function extract(o){for(const x of[o,o?.data,o?.currentData,o?.data?.data,o?.currentData?.data]){const c=x?.problemDataSetting?.cases;if(Array.isArray(c)&&(!x.problem?.pid||String(x.problem.pid)===pid))return c;}return null;}let cases=null;const url="/problem/"+pid+"/edit?tab=testcase";for(const headers of[{"x-lentille-request":"content-only"},{"x-luogu-type":"content-only"},{}]){try{const r=await fetch(url,{credentials:"same-origin",cache:"no-store",headers});if(!r.ok)continue;const t=await r.text();let data;if(t.trimStart().startsWith("<")){const doc=new DOMParser().parseFromString(t,"text/html");const raw=doc.getElementById("lentille-context")?.textContent;if(!raw)continue;data=JSON.parse(raw);}else data=JSON.parse(t);cases=extract(data);if(cases)break;}catch(e){console.warn(e);}}if(!cases){const raw=document.getElementById("lentille-context")?.textContent;if(raw)cases=extract(JSON.parse(raw));}if(!cases?.length)throw Error("无法读取测试点,请先保存修改");const yaml=cases.map((c,i)=>{if(!Array.isArray(c)||typeof c[0]!=="string")throw Error("第 "+(i+1)+" 个测试点格式错误");const name=c[0].split("/").pop();const key=/^[A-Za-z0-9_.-]+$/.test(name)?name:JSON.stringify(name);const lines=[key+":"];for(const[field,index]of[["timeLimit",2],["memoryLimit",3],["score",4],["subtaskId",6]])if(c[index]!=null)lines.push(" "+field+": "+c[index]);return lines.join("\n");}).join("\n\n")+"\n";const blob=new Blob([yaml],{type:"text/yaml;charset=utf-8"});const objectUrl=URL.createObjectURL(blob);const a=document.createElement("a");a.href=objectUrl;a.download="config.yml";document.documentElement.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(objectUrl),1000);console.log("成功生成 "+cases.length+" 个测试点");}catch(e){console.error(e);alert("生成失败:"+e.message);}})();```