UNPKG

alfred-bear

Version:

Alfred Workflow to handle bear templates

55 lines (54 loc) 2.11 kB
import { checkIfTemplateIndexExists, resolveHomePath } from "./utils.js"; import yaml from "yaml"; import fs from "fs"; import { BearTemplateError } from "./Error.js"; export class TemplateIndex { constructor(pathToIndexFile) { this.templateIndex = null; this.pathToIndexFile = resolveHomePath(pathToIndexFile); } checkFileIntegrity(indexFile) { if (!indexFile.templates) { throw new BearTemplateError("The field `templates` is not defined inside your bearTemplateIndex"); } if (indexFile.templates.some((t) => !t)) { throw new BearTemplateError("There is at least one of your templates not defined inside your bearTemplateIndex"); } if (indexFile.templates.some((t) => !t.file)) throw new BearTemplateError('At least one of your templates has no "file" property'); } async readIndexFile() { const indexFile = await checkIfTemplateIndexExists(this.pathToIndexFile); return new Promise((resolve, _reject) => { fs.readFile(indexFile, "utf8", (err, data) => { if (err) throw new BearTemplateError(`Could not read index file at ${indexFile}`); let parsedFile = { templates: [] }; try { parsedFile = yaml.parse(data); } catch (e) { throw new BearTemplateError(`bearTemplateIndex yaml seems to be malformed: ${e}`); } this.checkFileIntegrity(parsedFile); resolve(parsedFile); }); }); } async init() { this.templateIndex = await this.readIndexFile(); } get templates() { return this.templateIndex ? this.templateIndex.templates : []; } get indexFile() { return this.pathToIndexFile; } mapTemplates(mapper) { var _a; if ((_a = this.templateIndex) === null || _a === void 0 ? void 0 : _a.templates) { return this.templateIndex.templates.map(mapper); } return []; } }