Commit 754ed25d authored by Miguel Angel Reina Ortega's avatar Miguel Angel Reina Ortega
Browse files

Adding hanlding for PlantUML diagrams

parent e239078f
Loading
Loading
Loading
Loading
Loading
+1
Changes for .gitlab-ci.yml: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -102,3 +102,4 @@ Build Pandoc docker image:
      changes:
        - generateBaseline/dockerfile.pandoc
        - generateBaseline/mermaid-filter.js
        - generateBaseline/plantuml-filter.js
+4 −2
Changes for generateBaseline/dockerfile.pandoc: 4 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -15,7 +15,8 @@ ENV DEBIAN_FRONTEND=noninteractive \
    PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
    PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome-stable \
    MERMAID_FILTER_PUPPETEER_CONFIG=/opt/mermaid/puppeteer.json \
    MERMAID_FILTER_CMD_MMDC=/opt/mermaidcli/node_modules/@mermaid-js/mermaid-cli/src/cli.js
    MERMAID_FILTER_CMD_MMDC=/opt/mermaidcli/node_modules/@mermaid-js/mermaid-cli/src/cli.js \
    PLANTUML_SERVER=https://tools.etsi.org/plant

RUN echo 'man-db man-db/auto-update boolean false' | debconf-set-selections && \
    rm -f /var/lib/man-db/auto-update && \
@@ -45,8 +46,9 @@ RUN wget --timeout=30 --tries=2 --progress=dot:giga \
COPY --from=nodejs /usr/local/bin/node /usr/local/bin/node
COPY --from=mermaidcli /home/mermaidcli/node_modules /opt/mermaidcli/node_modules
COPY generateBaseline/mermaid-filter.js /usr/local/bin/mermaid-filter
COPY generateBaseline/plantuml-filter.js /usr/local/bin/plantuml-filter

RUN chmod +x /usr/local/bin/mermaid-filter && \
RUN chmod +x /usr/local/bin/mermaid-filter /usr/local/bin/plantuml-filter && \
    mkdir -p /opt/mermaid && \
    printf '%s\n' \
        '{' \
+239
Changes for generateBaseline/plantuml-filter.js: 239 added lines, 0 removed lines.
Original line number Diff line number Diff line
#!/usr/bin/env node
'use strict';

// Pandoc JSON filter: render ```plantuml blocks via the PlantUML server, write AST to stdout.
const fs = require('fs');
const os = require('os');
const path = require('path');
const zlib = require('zlib');
const { execFileSync } = require('child_process');

const SERVER = (process.env.PLANTUML_SERVER || 'https://tools.etsi.org/plant').replace(/\/+$/, '');
const WGET = process.env.PLANTUML_FILTER_WGET || 'wget';

function isPlantumlBlock(el) {
	return el && el.t === 'CodeBlock' && Array.isArray(el.c) &&
		Array.isArray(el.c[0]) && Array.isArray(el.c[0][1]) &&
		el.c[0][1].indexOf('plantuml') >= 0;
}

function stringifyInlines(inlines) {
	if (!inlines) {
		return '';
	}
	if (typeof inlines === 'string') {
		return inlines;
	}
	if (Array.isArray(inlines)) {
		return inlines.map(stringifyInlines).join('');
	}
	if (inlines && typeof inlines === 'object') {
		if (inlines.t === 'Str') {
			return inlines.c || '';
		}
		if (inlines.t === 'Space' || inlines.t === 'SoftBreak') {
			return ' ';
		}
		if (Object.prototype.hasOwnProperty.call(inlines, 'c')) {
			return stringifyInlines(inlines.c);
		}
	}
	return '';
}

function isFigureCaptionPara(el) {
	if (!el || el.t !== 'Para' || !Array.isArray(el.c) || el.c.length === 0) {
		return false;
	}
	if (el.c[0].t !== 'Strong') {
		return false;
	}
	return /^Figure\s/.test(stringifyInlines(el.c).trim());
}

function figureCaptionInlines(el) {
	if (el.c.length === 1 && el.c[0].t === 'Strong' && Array.isArray(el.c[0].c)) {
		return el.c[0].c;
	}
	const out = [];
	for (let i = 0; i < el.c.length; i++) {
		const inline = el.c[i];
		if (inline && inline.t === 'Strong' && Array.isArray(inline.c)) {
			Array.prototype.push.apply(out, inline.c);
		} else {
			out.push(inline);
		}
	}
	return out;
}

function encode6bit(b) {
	if (b < 10) {
		return String.fromCharCode(48 + b);
	}
	b -= 10;
	if (b < 26) {
		return String.fromCharCode(65 + b);
	}
	b -= 26;
	if (b < 26) {
		return String.fromCharCode(97 + b);
	}
	b -= 26;
	if (b === 0) {
		return '-';
	}
	if (b === 1) {
		return '_';
	}
	return '?';
}

function append3bytes(b1, b2, b3) {
	const c1 = b1 >> 2;
	const c2 = ((b1 & 0x3) << 4) | (b2 >> 4);
	const c3 = ((b2 & 0xF) << 2) | (b3 >> 6);
	const c4 = b3 & 0x3F;
	return encode6bit(c1 & 0x3F) + encode6bit(c2 & 0x3F) +
		encode6bit(c3 & 0x3F) + encode6bit(c4 & 0x3F);
}

function encode64(data) {
	let r = '';
	for (let i = 0; i < data.length; i += 3) {
		if (i + 2 === data.length) {
			r += append3bytes(data[i], data[i + 1], 0);
		} else if (i + 1 === data.length) {
			r += append3bytes(data[i], 0, 0);
		} else {
			r += append3bytes(data[i], data[i + 1], data[i + 2]);
		}
	}
	return r;
}

function encodePlantuml(text) {
	return encode64(zlib.deflateRawSync(Buffer.from(text, 'utf8')));
}

function ensureStartUml(content) {
	const text = String(content).trim();
	if (/@startuml/i.test(text)) {
		return text + '\n';
	}
	return '@startuml\n' + text + '\n@enduml\n';
}

function figureFromPng(id, png, caption) {
	const captionInlines = Array.isArray(caption) ? caption : [];
	const src = 'data:image/png;base64,' + png.toString('base64');
	const image = {
		t: 'Image',
		c: [[id, [], []], captionInlines, [src, 'fig:']]
	};
	return {
		t: 'Figure',
		c: [
			[id, [], []],
			[null, captionInlines.length ? [{ t: 'Plain', c: captionInlines }] : []],
			[{ t: 'Plain', c: [image] }]
		]
	};
}

function renderPlantuml(el, caption) {
	const attrs = el.c[0];
	const id = attrs[0] || '';
	const source = ensureStartUml(el.c[1]);
	const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'plantuml-'));
	const output = path.join(tmp, 'out.png');
	const url = SERVER + '/png/' + encodePlantuml(source);

	try {
		execFileSync(WGET, [
			'--timeout=30',
			'--tries=2',
			'-q',
			'-O', output,
			url
		], { stdio: ['ignore', 'pipe', 'pipe'] });
	} catch (err) {
		const stderr = err.stderr ? err.stderr.toString() : String(err);
		fs.writeSync(2, 'plantuml server failed (' + SERVER + '):\n' + stderr + '\n');
		process.exit(1);
	}

	const data = fs.readFileSync(output);
	if (data.length < 8 || data[0] !== 0x89 || data[1] !== 0x50) {
		fs.writeSync(2, 'plantuml server did not return a PNG from ' + SERVER + '\n');
		process.exit(1);
	}
	try {
		fs.rmSync(tmp, { recursive: true, force: true });
	} catch (e) { /* ignore */ }

	return figureFromPng(id, data, caption);
}

function captionFromAttrs(el) {
	const kvs = el && el.c && el.c[0] && el.c[0][2];
	if (!Array.isArray(kvs)) {
		return [];
	}
	for (let i = 0; i < kvs.length; i++) {
		if (kvs[i] && kvs[i][0] === 'caption' && kvs[i][1]) {
			return [{ t: 'Str', c: String(kvs[i][1]) }];
		}
	}
	return [];
}

function walkBlocks(blocks) {
	const out = [];
	for (let i = 0; i < blocks.length; i++) {
		const el = blocks[i];
		if (isPlantumlBlock(el)) {
			let caption = captionFromAttrs(el);
			if (isFigureCaptionPara(blocks[i + 1])) {
				caption = figureCaptionInlines(blocks[i + 1]);
				i += 1;
			}
			out.push(renderPlantuml(el, caption));
		} else {
			out.push(walk(el));
		}
	}
	return out;
}

function walk(node) {
	if (Array.isArray(node)) {
		if (node.some(isPlantumlBlock)) {
			return walkBlocks(node);
		}
		return node.map(walk);
	}
	if (node && typeof node === 'object') {
		if (isPlantumlBlock(node)) {
			return renderPlantuml(node, []);
		}
		if (Object.prototype.hasOwnProperty.call(node, 'c')) {
			node.c = walk(node.c);
		}
		if (Object.prototype.hasOwnProperty.call(node, 'blocks')) {
			node.blocks = walk(node.blocks);
		}
		return node;
	}
	return node;
}

let raw = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
	raw += chunk;
});
process.stdin.on('end', function () {
	const doc = JSON.parse(raw);
	process.stdout.write(JSON.stringify(walk(doc)));
});