feat(rss): лента готова к Дзену — лимит 20, PNG-обложки covergen в палитре dedinit-dark
deploy-dedinit / Build & SFTP Deploy (push) Successful in 12m53s
wiki-sync / Publish docs/wiki to Gitea wiki (push) Successful in 21s

- tools/covergen из ветки covergen-tooling + флаг --palette auto|dedinit-dark (цвета theme-vars/hero.svg)
- scripts/gen-covers.mjs: SVG в static/covers (в git), PNG — артефакт сборки (gitignore), --png/--force/--only
- rss.xml: <enclosure> с covers/<slug>.png при fileExists, <language>ru</language>, описание канала по-русски
- hugo.toml: limit 5 → 20, enableRobotsTXT
- deploy.yml: nodejs + librsvg2-bin, шаг генерации обложек перед hugo
- docs: DZEN_RSS (итог), covergen (палитра, SVG/PNG, питфолл snap-chromium), вики reference-covers/reference-rss-dzen
- openspec change dzen-rss-compliance
This commit is contained in:
2026-11-14 14:07:41 +00:00
parent 6276d06ea2
commit 4cb6323e4c
224 changed files with 4019 additions and 22 deletions
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env node
/**
* Обложки постов из frontmatter: SVG (в git) + PNG (артефакт сборки).
*
* node scripts/gen-covers.mjs # добить отсутствующие SVG
* node scripts/gen-covers.mjs --png # + растр из готовых SVG (rsvg/resvg/chromium)
* node scripts/gen-covers.mjs --force # перегенерировать всё
* node scripts/gen-covers.mjs --only <slug> # один пост
* node scripts/gen-covers.mjs --dry-run # показать план
*
* Палитра по умолчанию — `dedinit-dark` (цвета интерфейса сайта и hero.svg).
* SVG коммитятся; PNG лежат в .gitignore и создаются на сборке.
*/
'use strict';
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
const ROOT = path.resolve(new URL('..', import.meta.url).pathname);
const POSTS = path.join(ROOT, 'content', 'posts');
const OUTDIR = path.join(ROOT, 'static', 'covers');
const COVERGEN = path.join(ROOT, 'tools', 'covergen', 'bin', 'covergen.js');
const PALETTE = process.env.COVERS_PALETTE || 'dedinit-dark';
const argv = process.argv.slice(2);
const has = (flag) => argv.includes(flag);
const valueOf = (flag, fallback = null) => {
const i = argv.indexOf(flag);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const FORCE = has('--force');
const DRY = has('--dry-run');
const WANT_PNG = has('--png');
const ONLY = valueOf('--only');
const AUDIT = has('--audit');
function frontMatter(text) {
if (!text.startsWith('---')) return {};
const end = text.indexOf('\n---', 3);
if (end < 0) return {};
const block = text.slice(3, end).split('\n');
const fm = {};
let currentKey = null;
for (const raw of block) {
const line = raw.replace(/\t/g, ' ');
const itemMatch = /^\s*-\s*(.+)$/.exec(line);
if (itemMatch && currentKey) {
fm[currentKey] = Array.isArray(fm[currentKey]) ? fm[currentKey] : [];
fm[currentKey].push(itemMatch[1].trim().replace(/^['"]|['"]$/g, ''));
continue;
}
const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line);
if (!kv) continue;
const [, key, rawValue] = kv;
currentKey = key;
const value = rawValue.trim().replace(/^['"]|['"]$/g, '');
fm[key] = value === '' ? [] : value === 'true' ? true : value === 'false' ? false : value;
}
return fm;
}
function collect() {
const entries = [];
for (const dir of fs.readdirSync(POSTS, { withFileTypes: true })) {
if (!dir.isDirectory()) continue;
const index = path.join(POSTS, dir.name, 'index.md');
if (!fs.existsSync(index)) continue;
const fm = frontMatter(fs.readFileSync(index, 'utf8'));
if (fm.draft === true && !FORCE) continue;
const slug = String(fm.slug || dir.name).trim();
if (!slug || !fm.title) continue;
const date = String(fm.date || '').slice(0, 10);
const tags = Array.isArray(fm.tags) ? fm.tags.map(String) : String(fm.tags || '').split(',').filter(Boolean);
entries.push({
slug,
title: String(fm.title),
subtitle: [date, tags[0]].filter(Boolean).join(' · '),
tags: tags.slice(0, 3),
style: fm.cover_style || 'auto',
palette: PALETTE,
});
}
return entries;
}
function toPng(svgPath) {
const pngPath = svgPath.replace(/\.svg$/i, '.png');
const tries = [
['rsvg-convert', ['-o', pngPath, svgPath]],
['resvg', ['--use-fonts-dir', '/usr/share/fonts', svgPath, pngPath]],
];
for (const [bin, args] of tries) {
const res = spawnSync(bin, args, { encoding: 'utf8' });
if (res.status === 0 && fs.existsSync(pngPath)) return pngPath;
}
// snap-chromium под AppArmor не читает /opt и /tmp — копируем SVG в НАСТОЯЩИЙ домашний
// каталог пользователя (os.homedir() отдаёт $HOME агента, а он у нас в /opt)
const realHome = process.env.COVERS_HOME || os.userInfo().homedir || os.homedir();
// каталог НЕ скрытый: snap-chromium не видит каталоги с точкой в имени
const tmpDir = fs.mkdtempSync(path.join(realHome, 'covergen-tmp-'));
const tmpSvg = path.join(tmpDir, path.basename(svgPath));
const tmpPng = path.join(tmpDir, 'cover.png');
fs.copyFileSync(svgPath, tmpSvg);
const chrome = spawnSync('chromium-browser', [
'--headless=new', '--no-sandbox', '--disable-gpu', '--hide-scrollbars',
'--window-size=1200,630', `--screenshot=${tmpPng}`, `file://${tmpSvg}`,
], { encoding: 'utf8', timeout: 120000 });
let ok = chrome.status === 0 && fs.existsSync(tmpPng);
if (ok) fs.copyFileSync(tmpPng, pngPath);
fs.rmSync(tmpDir, { recursive: true, force: true });
return ok ? pngPath : null;
}
function main() {
if (!fs.existsSync(COVERGEN)) {
console.error(`нет генератора: ${COVERGEN} (ожидается из ветки covergen-tooling)`);
return 1;
}
fs.mkdirSync(OUTDIR, { recursive: true });
let entries = collect();
if (ONLY) entries = entries.filter((e) => e.slug === ONLY);
const missing = entries.filter((e) => FORCE || !fs.existsSync(path.join(OUTDIR, `${e.slug}.svg`)));
console.log(`постов: ${entries.length}, обложек к генерации: ${missing.length} (палитра ${PALETTE})`);
if (DRY) return 0;
if (missing.length) {
const manifest = path.join(os.tmpdir(), `covers-manifest-${process.pid}.json`);
fs.writeFileSync(manifest, JSON.stringify(missing, null, 2));
const args = [COVERGEN, '--manifest', manifest, '--outdir', OUTDIR, '--palette', PALETTE];
if (AUDIT) args.push('--audit');
const res = spawnSync(process.execPath, args, { encoding: 'utf8' });
fs.rmSync(manifest, { force: true });
process.stdout.write(res.stdout || '');
if (res.stderr) process.stderr.write(res.stderr);
if (res.status !== 0) console.error('covergen завершился с замечаниями аудита (сборка продолжается)');
}
if (WANT_PNG) {
const svgs = fs.readdirSync(OUTDIR).filter((f) => f.endsWith('.svg'));
let made = 0;
let skipped = 0;
for (const file of svgs) {
const svgPath = path.join(OUTDIR, file);
const pngPath = svgPath.replace(/\.svg$/i, '.png');
if (!FORCE && fs.existsSync(pngPath)) {
skipped += 1;
continue;
}
if (toPng(svgPath)) made += 1;
else {
console.error(`PNG не создан: ${file} — нет rsvg-convert/resvg, chromium недоступен`);
break;
}
}
console.log(`PNG: создано ${made}, уже было ${skipped}`);
}
return 0;
}
process.exit(main());