Generate publication badges from exact pushed commits in CI

This commit is contained in:
unimatrixgit 2026-11-15 00:52:00 +01:00
commit 9e400357b7
5 changed files with 57 additions and 3 deletions

View file

@ -27,6 +27,20 @@ jobs:
with:
node-version: '22'
- name: Prepare publication comparison
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");')
if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA"
BEFORE=$(git rev-parse HEAD^)
else
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$BEFORE"
fi
node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA"
- name: Verify deployment policy
run: node --test .forgejo/tests/web-deploy.test.mjs

View file

@ -1,6 +1,6 @@
import{readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs';
export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();}
export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.length){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;}
import{existsSync,readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs';
export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(!p.includes('/tests/')){const scopes=[[/postbank|bank-rates/,'bank'],[/politic|election|charter/,'politics'],[/internal-mail|mail-service|post-pages/,'post'],[/organisation-|citizen-directory|account-admin|honours|permissions/,'bureau'],[/forge-pages|dev-request|git-identity/,'forge'],[/exchange-public|commodity/,'market'],[/passport|personal-records|user-pages/,'realm']];for(const [pattern,scope]of scopes)if(pattern.test(p)){pages.add('https://cp.dunerealms.com/');pages.add('https://cp.dunerealms.com/#'+scope);}}if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();}
export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');const publication=path.join(root,'publication-changes.json');if(paths===undefined&&existsSync(publication)){const change=JSON.parse(readFileSync(publication,'utf8'));if(!Array.isArray(change.paths)||!Array.isArray(change.added))throw Error('Invalid publication change record.');paths=change.paths;newPages=pagesForChanges(change.added).filter(href=>!href.startsWith('https://cp.dunerealms.com/'));}if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.length||existsSync(publication)){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;}
export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;}
export function withMenuBadges(s){return s.replace(/\n?\/\* Central automatic release menu badges \*\/[\s\S]*?(?=\n\/\*|$)/,'').replace(/\(\(\)=>\{const items=\[[\s\S]*?new MutationObserver\(mark\)\.observe\(document.body,\{childList:true,subtree:true,characterData:true\}\);\}\)\(\);/,'')+menuBadgeScript();}
export function patchMenuBadges(root=fileURLToPath(new URL('../',import.meta.url))){const file=path.join(root,'web/portal-navigation.js');writeFileSync(file,withMenuBadges(readFileSync(file,'utf8')));}

View file

@ -0,0 +1,17 @@
import {execFileSync} from 'node:child_process';
import {readFileSync,writeFileSync} from 'node:fs';
import {fileURLToPath} from 'node:url';
import path from 'node:path';
export function publicationChanges(repo,base,head='HEAD'){
if(!/^[a-f0-9]{40}$/i.test(base)||!(/^[a-f0-9]{40}$/i.test(head)||head==='HEAD'))throw Error('Publication comparison requires exact commit IDs.');
const raw=execFileSync('git',['diff','--name-status','--no-renames','-z',base,head],{cwd:repo,encoding:'utf8'}).split('\0');
const paths=[],added=[];
for(let i=0;i<raw.length-1;i+=2){const [status,file]=raw.slice(i,i+2);if(!file)continue;paths.push(file);if(status==='A')added.push(file);}
return {base,head,paths,added};
}
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
const repo=path.resolve(fileURLToPath(new URL('../../',import.meta.url)));
const result=publicationChanges(repo,process.argv[2],process.argv[3]||'HEAD');
writeFileSync(new URL('../publication-changes.json',import.meta.url),JSON.stringify(result));
console.log('Recorded '+result.paths.length+' publication paths.');
}

View file

@ -25,3 +25,5 @@ test('Explicit changed paths still update menu badges without Git metadata',()=>
test('V2 workspace tiles use the shared manifest even with the simple Alpha header',()=>{const s=menuBadgeScript();assert(s.includes('#portals .portal[data-id]'));assert(s.includes("'https://cp.dunerealms.com/#'+a.dataset.id"));assert(!s.includes('if(!release)return'));new Function(s);});
test('New publication clears untouched badges and distinguishes a new page from an update',()=>{const repo=mkdtempSync(path.join(tmpdir(),'dune-badge-expiry-'));try{const root=path.join(repo,'website');mkdirSync(path.join(root,'web'),{recursive:true});const file=path.join(root,'web/menu-new-items.json');writeFileSync(file,JSON.stringify({items:[{href:'https://clans.dunerealms.com/',badge:'NEW'},{href:'https://www.dunerealms.com/staff.html',badge:'NEW',introducedIn:'1.0.0.4'}]}));recordPageUpdates({root,version:'1.0.0.4',paths:['website/node/staff-roster.mjs','website/web/rates-and-charges.html'],newPages:['https://www.dunerealms.com/rates-and-charges.html']});const items=JSON.parse(readFileSync(file)).items;assert.equal(items.find(x=>x.href==='https://clans.dunerealms.com/').badge,undefined);assert.equal(items.find(x=>x.href.endsWith('/staff.html')).badge,'UPDATE');assert.equal(items.find(x=>x.href.endsWith('/rates-and-charges.html')).badge,'NEW');}finally{rmSync(repo,{recursive:true,force:true});}});
test('Bank changes update the bank workspace badge without marking unrelated workspace tiles',()=>{assert.deepEqual(pagesForChanges(['website/node/postbank-payments.mjs']),['https://cp.dunerealms.com/','https://cp.dunerealms.com/#bank']);assert.deepEqual(pagesForChanges(['website/tests/postbank-payments.test.mjs']),[]);});

View file

@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {mkdtempSync,writeFileSync,rmSync} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {publicationChanges} from '../scripts/publication-changes.mjs';
test('Publication comparison uses committed changes, including additions and filenames with spaces',()=>{
const repo=mkdtempSync(path.join(tmpdir(),'dune-push-'));
const git=(...args)=>execFileSync('git',args,{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();
try{
git('init');git('config','user.name','Publication test');git('config','user.email','test@example.invalid');
writeFileSync(path.join(repo,'existing.txt'),'before');git('add','.');git('commit','-m','base');const base=git('rev-parse','HEAD');
writeFileSync(path.join(repo,'existing.txt'),'after');writeFileSync(path.join(repo,'new page.html'),'new');git('add','.');git('commit','-m','published');const head=git('rev-parse','HEAD');
writeFileSync(path.join(repo,'unpublished.txt'),'not published');
const change=publicationChanges(repo,base,head);
assert.deepEqual(change.paths,['existing.txt','new page.html']);assert.deepEqual(change.added,['new page.html']);
assert.deepEqual(publicationChanges(repo,head,head).paths,[]);
assert.throws(()=>publicationChanges(repo,'HEAD~1'),/exact commit/);
}finally{rmSync(repo,{recursive:true,force:true});}
});