feat(plugins): 新增资料目录插件索引体检/修复脚本 plugins:doctor
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 51s

背景:手工往 <资料目录>/plugins/ 拷文件、没更新同目录 index.json 时,加载器按索引里的旧哈希校验,
报「完整性校验失败(main.js 的 sha256 不符)」(2026-11-29 便利贴 1.0.8 实发)。

- scripts/plugin-index-doctor.js:扫描目录与索引,逐条报告 版本差异 / 哈希不符 / 文件缺失 / 未登记 / 孤儿条目;
  默认只报告(有待修项时非 0 退出),--write 按实际文件重写索引并自动备份 index.json.bak-<时间戳>
- package.json: npm run plugins:doctor(可带资料目录与 --write)
- docs/standards/plugin-source-of-truth.md:命令表补该脚本,排错行的处置改为指向它

用法:
  npm run plugins:doctor                          # 默认扫 ~/Documents/ImageWorkbench
  npm run plugins:doctor -- /path/to/data         # 指定资料目录(只报告)
  npm run plugins:doctor -- /path/to/data --write # 写入修复
This commit is contained in:
qiqi committed 2026-11-29 12:48:02 +08:00
1 parent a9b19e67de
commit 8e9a3b6ded
3 files changed
+110 -1

No files matched your search

+107
View File
@@ -0,0 +1,107 @@
'use strict'
// 资料目录插件索引体检/修复(v3.26.109)
//
// 背景:手工往 <资料目录>/plugins/ 拷插件文件、但没更新同目录的 index.json 时,加载器会按索引里的旧哈希
// 校验 main.js → 「完整性校验失败(main.js 的 sha256 不符)」(2026-11-29 便利贴 1.0.8 实发)。
// 这个脚本扫描目录与索引,报告差异;加 --write 会按实际文件重写索引(先备份)。
//
// 用法:
// node scripts/plugin-index-doctor.js # 默认扫 ~/Documents/ImageWorkbench(只报告)
// node scripts/plugin-index-doctor.js /path/to/data # 指定资料目录
// node scripts/plugin-index-doctor.js /path/to/data --write # 写入修复
const fs = require('fs')
const path = require('path')
const os = require('os')
const crypto = require('crypto')
const args = process.argv.slice(2)
const write = args.includes('--write')
const dataDir = path.resolve(args.find((a) => !a.startsWith('--')) || path.join(os.homedir(), 'Documents', 'ImageWorkbench'))
const dir = path.join(dataDir, 'plugins')
const indexPath = path.join(dir, 'index.json')
const sha = (p) => crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex')
if (!fs.existsSync(dir)) { console.error('找不到 ' + dir + '(资料目录不对?)'); process.exit(2) }
let index = []
try { index = JSON.parse(fs.readFileSync(indexPath, 'utf8')) } catch (e) { console.log('索引缺失或损坏,将按目录重建:' + (e && e.message)) }
if (!Array.isArray(index)) index = []
const byId = new Map(index.filter((e) => e && e.id).map((e) => [e.id, e]))
const rows = []
const fixed = []
const seen = new Set()
for (const name of fs.readdirSync(dir).sort()) {
const abs = path.join(dir, name)
if (!fs.statSync(abs).isDirectory()) continue
const manifestPath = path.join(abs, 'manifest.json')
if (!fs.existsSync(manifestPath)) { rows.push(['warn', name, '目录里没有 manifest.json(不是插件目录,跳过)']); continue }
let m = null
try { m = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) } catch (e) { rows.push(['bad', name, 'manifest.json 解析失败:' + (e && e.message)]); continue }
const id = String(m.id || name)
seen.add(id)
const main = String(m.main || 'main.js')
const style = String(m.style || '')
const files = {}
const missing = []
for (const f of ['manifest.json', main, ...(style ? [style] : [])]) {
const p = path.join(abs, f)
if (!fs.existsSync(p)) { missing.push(f); continue }
files[f] = sha(p)
}
const entry = byId.get(id)
const next = { id: id, dir: name, main: main, style: style, version: String(m.version || ''), files: files }
if (missing.length) rows.push(['bad', id, '文件缺失:' + missing.join('、')])
if (!entry) {
rows.push(['fix', id, '索引里没有这条 → 补登记(v' + next.version + ')'])
fixed.push({ before: null, after: next })
continue
}
const diffs = []
if (String(entry.version) !== next.version) diffs.push('版本 ' + entry.version + ' → ' + next.version)
const ef = entry.files || {}
for (const f of Object.keys(files)) {
if (!ef[f]) diffs.push(f + ' 未登记哈希')
else if (ef[f] !== files[f]) diffs.push(f + ' 哈希不符')
}
for (const f of Object.keys(ef)) if (!files[f]) diffs.push(f + ' 索引里有、磁盘上没有')
if (String(entry.dir) !== name) diffs.push('目录名 ' + entry.dir + ' → ' + name)
if (diffs.length) { rows.push(['fix', id, diffs.join(';')]); fixed.push({ before: entry, after: next }) }
else rows.push(['ok', id, 'v' + next.version])
}
// 索引里有、磁盘上没有的条目
for (const e of index) {
if (!e || !e.id || seen.has(e.id)) continue
if (e.dir && !fs.existsSync(path.join(dir, e.dir))) { rows.push(['bad', e.id, '索引登记了但目录不存在 → 建议删除该条目']); fixed.push({ before: e, after: null }) }
else if (!e.dir) rows.push(['warn', e.id, '单文件插件条目(本脚本不处理文件搬运)'])
}
const order = { bad: 0, fix: 1, warn: 2, ok: 3 }
rows.sort((a, b) => (order[a[0]] - order[b[0]]) || a[1].localeCompare(b[1]))
const mark = { ok: '✅', fix: '🔧', warn: '⚠️', bad: '❌' }
console.log('资料目录:' + dataDir)
console.log('索引:' + indexPath)
console.log('')
for (const [kind, id, msg] of rows) console.log(' ' + mark[kind] + ' ' + id.padEnd(16) + msg)
const counts = rows.reduce((a, r) => { a[r[0]] = (a[r[0]] || 0) + 1; return a }, {})
console.log('')
console.log('合计:' + Object.keys(counts).map((k) => mark[k] + ' ' + k + ' ' + counts[k]).join(' ') + '(共 ' + rows.length + ' 个目录)')
if (!fixed.length) { console.log('索引与实际文件一致,无需修复。'); process.exit(0) }
if (!write) { console.log(''); console.log('以上差异可加 --write 修复(会先备份 index.json)。'); process.exit(1) }
// 写回:保持原有顺序,更新/补登记/删除失效条目
const out = []
for (const e of index) {
if (!e || !e.id) continue
const upd = fixed.find((x) => x.after && x.after.id === e.id)
if (upd) out.push(upd.after)
else if (!fixed.some((x) => !x.after && x.before && x.before.id === e.id)) out.push(e)
}
for (const x of fixed) if (x.after && !out.some((e) => e.id === x.after.id)) out.push(x.after)
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
try { fs.copyFileSync(indexPath, indexPath + '.bak-' + stamp) } catch (e) { /* 首次没有索引 */ }
fs.writeFileSync(indexPath, JSON.stringify(out, null, 2) + '\n')
console.log('已修复并写回:' + out.length + ' 条(备份 index.json.bak-' + stamp + ')')