markdowny/src/tools/list.ts
2023-01-26 22:19:45 -06:00

83 lines
2.2 KiB
TypeScript

import * as _ from "lodash";
import * as yargs from "yargs";
import * as scanner from "../scanner";
import * as handlebars from "handlebars";
import * as fs from "fs";
export var command = "list";
export var describe = "Extracts a YAML field into an ordered list";
export function builder(yargs: yargs.Arguments) {
return yargs
.help("help")
.alias("t", "template")
.default("template", "{{_number}}. {{{title}}}: {{{summary}}}")
.alias("s", "trim-whitespace")
.boolean("trim-whitspace")
.alias("o", "output")
.default("output", "-")
.demand(1);
}
export function handler(argv: any) {
var files = argv._.splice(1);
var data = scanner.scanFiles(argv, files);
render(argv, data);
}
export function render(argv, files) {
// Compile the handlebars template.
handlebars.registerHelper("eq", function (a, b) {
return a === b;
});
handlebars.registerHelper("gt", function (a, b) {
return a > b;
});
handlebars.registerHelper("gte", function (a, b) {
return a >= b;
});
handlebars.registerHelper("lt", function (a, b) {
return a < b;
});
handlebars.registerHelper("lte", function (a, b) {
return a <= b;
});
handlebars.registerHelper("ne", function (a, b) {
return a !== b;
});
const template = handlebars.compile(argv.template);
// Go through each of the files and create a row from each one.
const trim = /\s+/g;
let output: string[] = [];
for (var key in files) {
// Combine everything into a single parameters object including `_number`
// to represent the one-based index from the beginning.
const number = 1 + parseInt(key.toString());
let params = { ...files[key], _number: number };
// Render the results and write it out.
let result = template(params);
if (argv.trimWhitespace) {
result = result.replace(trim, " ").trim();
}
output.push(result);
}
// Write out the results as requested.
if (argv.output === "-") {
console.log(output.join("\n"));
} else {
fs.writeFileSync(argv.output, Buffer.from(output.join("\n"), "utf-8"));
}
}