|
| 1 | +#!/usr/bin/env node |
| 2 | +// What's new entries as separate files, so pull requests stop colliding. |
| 3 | +// |
| 4 | +// Each pull request adds one file, e63334287a3deaa3/news/<name>.json, instead of editing the top of NEWS in |
| 5 | +// e63334287a3deaa3/news.js. Nobody else edits that file, so open pull requests no longer conflict there, and |
| 6 | +// nobody has to guess the next version or the merge date: after the merge, the "What's new: publish" workflow |
| 7 | +// runs this script, which gives the entry the next version and today's date, puts it at the top of NEWS (and its |
| 8 | +// Spanish in news-es.js), and deletes the file. See e63334287a3deaa3/news/README.md for the format. |
| 9 | +// |
| 10 | +// node .github/scripts/news.js check <file.json> ... check entries (the pull request check) |
| 11 | +// node .github/scripts/news.js publish publish every waiting entry, oldest first |
| 12 | +// |
| 13 | +// Files whose names start with _ (like _example.json) are templates and are never published. |
| 14 | +'use strict'; |
| 15 | +const fs = require('fs'); |
| 16 | +const path = require('path'); |
| 17 | +const { execFileSync } = require('child_process'); |
| 18 | + |
| 19 | +const ROOT = path.resolve(__dirname, '..', '..'); |
| 20 | +const DIR = 'e63334287a3deaa3/news'; |
| 21 | +const NEWS_JS = 'e63334287a3deaa3/news.js'; |
| 22 | +const NEWS_ES = 'e63334287a3deaa3/news-es.js'; |
| 23 | +const TZ = process.env.NEWS_TZ || 'America/New_York'; |
| 24 | +const KINDS = ['game', 'feature', 'fix', 'soon']; |
| 25 | +const FIELDS = ['kind', 'title', 'items', 'games', 'img', 'tags', 'link', 'date', 'noVersion', 'es']; |
| 26 | + |
| 27 | +const abs = (p) => path.join(ROOT, p); |
| 28 | + |
| 29 | +function read(file) { |
| 30 | + let e; |
| 31 | + try { e = JSON.parse(fs.readFileSync(abs(file), 'utf8')); } |
| 32 | + catch (err) { return { errors: [`isn't valid JSON: ${err.message}`] }; } |
| 33 | + const errors = [], warnings = []; |
| 34 | + if (!e || typeof e !== 'object' || Array.isArray(e)) return { errors: ['must be one JSON object {...}'] }; |
| 35 | + const isStr = (v) => typeof v === 'string' && v.trim() !== ''; |
| 36 | + const strList = (v) => Array.isArray(v) && v.length > 0 && v.every(isStr); |
| 37 | + for (const k of Object.keys(e)) if (!FIELDS.includes(k) && k !== 'version') errors.push(`unknown field "${k}" (allowed: ${FIELDS.join(', ')})`); |
| 38 | + if (!KINDS.includes(e.kind)) errors.push(`"kind" must be one of ${KINDS.join(', ')}`); |
| 39 | + if (!isStr(e.title)) errors.push('"title" is missing'); |
| 40 | + if (!strList(e.items)) errors.push('"items" must be a list of one or more sentences'); |
| 41 | + if ('version' in e) errors.push('leave "version" out: it is filled in when the pull request is merged'); |
| 42 | + if (e.games !== undefined && !strList(e.games)) errors.push('"games" must be a list of game names'); |
| 43 | + if (e.kind === 'game' && !e.games) errors.push('a new game needs "games": ["Its Name"] so it shows in "New games!"'); |
| 44 | + if (e.img !== undefined && !(isStr(e.img) || (strList(e.img) && e.img.length <= 3))) errors.push('"img" must be a path or a list of up to 3'); |
| 45 | + for (const p of [].concat(e.img || [])) if (!/^[\w./-]+\.(jpe?g|png|webp)$/i.test(p) || p.includes('..')) errors.push(`"img" ${p}: use a plain path inside the Back Room folder, like m/thumbs/<folder>.jpg`); |
| 46 | + for (const p of [].concat(e.img || [])) if (/^[\w./-]+$/.test(p) && !p.includes('..') && !fs.existsSync(abs('e63334287a3deaa3/' + p))) warnings.push(`"img" ${p} isn't in the Back Room folder yet`); |
| 47 | + if (e.tags !== undefined && !(strList(e.tags) && e.tags.length <= 4)) errors.push('"tags" must be a list of up to 4 words'); |
| 48 | + if (e.link !== undefined && !(e.link && isStr(e.link.text) && /^\/(?!\/)/.test(e.link.href || ''))) errors.push('"link" must be {"text": "...", "href": "/a-page-on-this-site/"}'); |
| 49 | + if (e.date !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(e.date)) errors.push('"date" must be YYYY-MM-DD (leave it out to use the merge day)'); |
| 50 | + if (e.noVersion !== undefined && e.noVersion !== true) errors.push('"noVersion" can only be true'); |
| 51 | + if (e.es !== undefined && !(e.es && typeof e.es === 'object' && !Array.isArray(e.es) && Object.values(e.es).every(isStr))) errors.push('"es" must be {"English line": "Spanish line", ...}'); |
| 52 | + if (!errors.length) { |
| 53 | + const es = e.es || {}; |
| 54 | + const lines = [e.title, ...e.items, ...(e.tags || []), ...(e.link ? [e.link.text] : [])]; |
| 55 | + const missing = lines.filter((l) => !es[l]); |
| 56 | + if (missing.length) warnings.push(`no Spanish yet for: ${missing.map((l) => JSON.stringify(l)).join(', ')} (these show in English)`); |
| 57 | + for (const k of Object.keys(es)) if (!lines.includes(k)) warnings.push(`"es" has ${JSON.stringify(k)}, which isn't a line of this entry`); |
| 58 | + } |
| 59 | + return { entry: e, errors, warnings }; |
| 60 | +} |
| 61 | + |
| 62 | +// ---- versions ---- |
| 63 | +const parseV = (s) => s.split('.').map(Number); |
| 64 | +const cmpV = (a, b) => { for (let i = 0; i < 3; i++) { const d = (a[i] || 0) - (b[i] || 0); if (d) return d; } return 0; }; |
| 65 | +function latestVersion(src) { |
| 66 | + const all = [...src.matchAll(/\bversion:\s*'(\d+(?:\.\d+){1,2})'/g)].map((m) => parseV(m[1])); |
| 67 | + if (!all.length) throw new Error(`no versions found in ${NEWS_JS}`); |
| 68 | + return all.sort(cmpV).pop(); |
| 69 | +} |
| 70 | +function bump(v, kind) { |
| 71 | + // a new game or a big feature bumps the minor number and drops the patch; a fix (or a teaser) bumps the patch |
| 72 | + if (kind === 'game' || kind === 'feature') return `${v[0]}.${(v[1] || 0) + 1}`; |
| 73 | + return `${v[0]}.${v[1] || 0}.${(v[2] || 0) + 1}`; |
| 74 | +} |
| 75 | + |
| 76 | +// ---- writing in news.js's own style ---- |
| 77 | +const q = (s) => "'" + String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\r?\n/g, ' ') + "'"; |
| 78 | +const list = (a) => '[' + a.map(q).join(', ') + ']'; |
| 79 | +function render(e, date, version) { |
| 80 | + let head = `{date: ${q(date)}, ` + (version ? `version: ${q(version)}, ` : '') + `title: ${q(e.title)}, kind: ${q(e.kind)},`; |
| 81 | + const extra = []; |
| 82 | + if (e.games) extra.push(`games: ${list(e.games)}`); |
| 83 | + if (e.img) extra.push(`img: ${Array.isArray(e.img) ? list(e.img) : q(e.img)}`); |
| 84 | + if (e.tags) extra.push(`tags: ${list(e.tags)}`); |
| 85 | + if (e.link) extra.push(`link: {text: ${q(e.link.text)}, href: ${q(e.link.href)}}`); |
| 86 | + extra.push('items: ['); |
| 87 | + const items = e.items.map((s) => ' ' + q(s)).join(',\n'); |
| 88 | + return ` ${head}\n ${extra.join(', ')}\n${items}]},\n`; |
| 89 | +} |
| 90 | + |
| 91 | +function insertAfter(src, marker, text, file) { |
| 92 | + const i = src.indexOf(marker); |
| 93 | + if (i < 0) throw new Error(`couldn't find "${marker}" in ${file}`); |
| 94 | + const at = src.indexOf('\n', i) + 1; |
| 95 | + return src.slice(0, at) + text + src.slice(at); |
| 96 | +} |
| 97 | + |
| 98 | +function today() { |
| 99 | + return new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date()); |
| 100 | +} |
| 101 | + |
| 102 | +function addedAt(file) { |
| 103 | + // when the file first reached main, so entries merged in one push keep their merge order |
| 104 | + try { |
| 105 | + const out = execFileSync('git', ['log', '--diff-filter=A', '--format=%ct', '--', file], { cwd: ROOT, encoding: 'utf8' }).trim().split('\n'); |
| 106 | + return Number(out[out.length - 1]) || 0; |
| 107 | + } catch { return 0; } |
| 108 | +} |
| 109 | + |
| 110 | +function pending() { |
| 111 | + if (!fs.existsSync(abs(DIR))) return []; |
| 112 | + return fs.readdirSync(abs(DIR)).filter((f) => f.endsWith('.json') && !f.startsWith('_')).map((f) => `${DIR}/${f}`); |
| 113 | +} |
| 114 | + |
| 115 | +function check(files) { |
| 116 | + let bad = 0; |
| 117 | + for (const f of files) { |
| 118 | + const r = read(f); |
| 119 | + for (const w of r.warnings || []) console.log(`::warning file=${f}::${w}`); |
| 120 | + for (const er of r.errors) { console.log(`::error file=${f}::${er}`); bad++; } |
| 121 | + if (!r.errors.length) console.log(`${f}: OK (${r.entry.kind}: ${r.entry.title})`); |
| 122 | + } |
| 123 | + return bad; |
| 124 | +} |
| 125 | + |
| 126 | +function publish() { |
| 127 | + const files = pending().sort((a, b) => addedAt(a) - addedAt(b) || a.localeCompare(b)); |
| 128 | + if (!files.length) { console.log('No waiting What\'s new entries.'); return []; } |
| 129 | + if (check(files)) throw new Error('fix the entries above, then push again'); |
| 130 | + let js = fs.readFileSync(abs(NEWS_JS), 'utf8'); |
| 131 | + let es = fs.readFileSync(abs(NEWS_ES), 'utf8'); |
| 132 | + const done = []; |
| 133 | + for (const f of files) { |
| 134 | + const e = read(f).entry; |
| 135 | + const version = e.noVersion ? null : bump(latestVersion(js), e.kind); |
| 136 | + const date = e.date || today(); |
| 137 | + js = insertAfter(js, 'var NEWS = [', render(e, date, version), NEWS_JS); |
| 138 | + const pairs = Object.entries(e.es || {}); |
| 139 | + if (pairs.length) es = insertAfter(es, 'BackRoomLang.add({', pairs.map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)},\n`).join(''), NEWS_ES); |
| 140 | + done.push({ file: f, version, date, title: e.title }); |
| 141 | + console.log(`${f} -> ${version || '(no version)'} ${date} ${e.title}`); |
| 142 | + } |
| 143 | + fs.writeFileSync(abs(NEWS_JS), js); |
| 144 | + fs.writeFileSync(abs(NEWS_ES), es); |
| 145 | + for (const d of done) fs.unlinkSync(abs(d.file)); |
| 146 | + const summary = done.map((d) => `${d.version || 'no version'}: ${d.title}`).join('; '); |
| 147 | + if (process.env.GITHUB_OUTPUT) fs.appendFileSync(process.env.GITHUB_OUTPUT, `summary<<EOF\n${summary}\nEOF\n`); |
| 148 | + return done; |
| 149 | +} |
| 150 | + |
| 151 | +const [mode, ...args] = process.argv.slice(2); |
| 152 | +try { |
| 153 | + if (mode === 'check') process.exit(check(args) ? 1 : 0); |
| 154 | + else if (mode === 'publish') publish(); |
| 155 | + else { console.error('usage: news.js check <file.json>... | news.js publish'); process.exit(2); } |
| 156 | +} catch (err) { console.error(`::error::${err.message}`); process.exit(1); } |
0 commit comments