7cf88d3035
deploy-dedinit / Build & SFTP Deploy (push) Successful in 14m27s
- SERIF/SANS/MONO переведены на одиночные кавычки: SVG теперь well-formed (проверены все 189) - тест на отсутствие двойных кавычек в шрифтовых семействах - gen-covers: черновики не получают обложек даже с --force - обложки перегенерированы (палитра dedinit-dark)
180 lines
7.3 KiB
JavaScript
180 lines
7.3 KiB
JavaScript
#!/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 slugify(value) {
|
|
return String(value)
|
|
.toLowerCase()
|
|
.replace(/[^\p{L}\p{N}]+/gu, '-')
|
|
.replace(/^-+|-+$/g, '')
|
|
.slice(0, 80) || 'cover';
|
|
}
|
|
|
|
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) continue; // черновики не публикуются — обложки им не нужны
|
|
const slug = slugify(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]],
|
|
];
|
|
const errors = [];
|
|
for (const [bin, args] of tries) {
|
|
const res = spawnSync(bin, args, { encoding: 'utf8' });
|
|
if (res.status === 0 && fs.existsSync(pngPath)) return pngPath;
|
|
errors.push(`${bin}: status=${res.status} ${(res.error && res.error.code) || ''} ${(res.stderr || '').trim().slice(-200)}`);
|
|
}
|
|
// 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) errors.push(`chromium: status=${chrome.status} ${(chrome.error && chrome.error.code) || ''}`);
|
|
if (ok) fs.copyFileSync(tmpPng, pngPath);
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
if (!ok) console.error(` подробности: ${errors.join(' | ')}`);
|
|
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());
|