73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
import * as _ from "lodash";
|
|
import * as fs from "fs";
|
|
import * as scanner from "../scanner";
|
|
import * as yaml from "js-yaml";
|
|
import * as yargs from "yargs";
|
|
|
|
export var command = "extract";
|
|
export var describe = "Extracts a YAML from a list of files";
|
|
|
|
export function builder(yargs: yargs.Arguments) {
|
|
return yargs
|
|
.help("help")
|
|
|
|
.option("list", {
|
|
type: "boolean",
|
|
default: true,
|
|
describe:
|
|
"Extract the data as a list of files, otherwise as a single file",
|
|
})
|
|
.option("output", {
|
|
alias: "o",
|
|
default: "-",
|
|
describe: "Write output to a file or `-` for standard out",
|
|
})
|
|
.option("yaml", {
|
|
alias: "y",
|
|
type: "boolean",
|
|
default: false,
|
|
describe: "Extract the output as YAML instead of JSON",
|
|
})
|
|
.option("content", {
|
|
type: "string",
|
|
describe: "Include the content as a property in the extracted data",
|
|
})
|
|
|
|
.demand(1);
|
|
}
|
|
|
|
export function handler(argv: any) {
|
|
// Parse through the files and retrieve the metadata.
|
|
var files = argv._.splice(1);
|
|
var data: any = scanner.scanFiles(argv, files);
|
|
|
|
// Figure out how to handle the content property.
|
|
if (!argv.content) {
|
|
// Remove the content from the parsed file.
|
|
data.forEach((x) => delete x.__content);
|
|
} else if (argv.content !== "__content") {
|
|
// Rename the content property.
|
|
data.forEach((x) => {
|
|
x[argv.content] = x.__content;
|
|
delete x.__content;
|
|
});
|
|
}
|
|
|
|
// Determine if we are displaying a list of items. If we want a list, then
|
|
// we wrap the data in another list (list of a list) so it writes out only
|
|
// one item. Otherwise, we write out each one.
|
|
const items = argv.list ? [data] : data;
|
|
|
|
// Figure the output of the results (JSON or YAML).
|
|
const output = argv.yaml
|
|
? items.map((x: any) => yaml.safeDump(x)).join("\n")
|
|
: items.map((x: any) => JSON.stringify(x)).join("\n");
|
|
|
|
// Figure out where to write.
|
|
if (argv.output === "-") {
|
|
console.log(output);
|
|
} else {
|
|
fs.writeFileSync(argv.output, Buffer.from(output, "utf-8"));
|
|
}
|
|
}
|