markugen
Version:
Markdown to HTML/PDF static site generation tool
60 lines (59 loc) • 2.81 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = markedCommands;
const node_child_process_1 = require("node:child_process");
const node_path_1 = __importDefault(require("node:path"));
const node_fs_1 = __importDefault(require("node:fs"));
const htmlgenerator_1 = __importDefault(require("../htmlgenerator"));
/**
* Extension for allowing execution of markugen commands
* within code blocks.
* @returns the marked extension
*/
function markedCommands(options) {
return {
walkTokens(token) {
if (token.type !== 'code')
return;
const match = token.text.match(htmlgenerator_1.default.cmdRegex);
if (match && match.groups && match.groups.cmd && match.groups.args) {
// allow commands to be escaped
if (match.groups.esc) {
token.text = `markugen.${match.groups.cmd} ${match.groups.args}`;
}
else if (match.groups.cmd === 'exec') {
options.generator.log('Executing:', match.groups.args);
const result = (0, node_child_process_1.spawnSync)(match.groups.args, [], {
shell: true,
encoding: 'utf8',
windowsVerbatimArguments: process.platform === 'win32' ? true : undefined,
});
const text = (result.stdout + '\n' + result.stderr).trim();
// remove coloring characters
token.text = text.replace(/(\x1b[^m]+m)/gi, '');
if (result.stderr) {
options.generator.group();
options.generator.warning(text);
options.generator.groupEnd();
}
}
else if (match.groups.cmd === 'import') {
const reldir = options.file ? node_path_1.default.dirname(options.file) : process.cwd();
const importfile = node_path_1.default.resolve(reldir, match.groups.args);
options.generator.log('Importing:', importfile);
if (node_fs_1.default.existsSync(importfile)) {
token.text = node_fs_1.default.readFileSync(importfile, { encoding: 'utf8' });
}
else {
options.generator.group();
options.generator.warning(`Unable to locate import file [${importfile}]`);
options.generator.groupEnd();
}
}
}
},
};
}