From 71ffd7373bac2a64db466fd1b3f34f6f82c7db98 Mon Sep 17 00:00:00 2001 From: Felix Wu Date: Sat, 28 Jul 2018 23:24:34 +0200 Subject: [PATCH] feat$(scripts, util): add md anchor and getFilesInDir methods --- scripts/util.js | 54 +++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/scripts/util.js b/scripts/util.js index d6440f96f..ee4bbf1e3 100644 --- a/scripts/util.js +++ b/scripts/util.js @@ -2,23 +2,48 @@ const fs = require('fs-extra'), path = require('path'), chalk = require('chalk'), crypto = require('crypto'); -// Synchronously read all snippets and sort them as necessary (case-insensitive) -const readSnippets = snippetsPath => { - let snippets = {}; + +const getMarkDownAnchor = (paragraphTitle) => + paragraphTitle.trim().toLowerCase() + .replace(/[^\w\- ]+/g, '') + .replace(/\s/g, '-') + .replace(/\-+$/, ''); + +const getFilesInDir = (directoryPath, withPath, exclude = null) => { try { - let snippetFilenames = fs.readdirSync(snippetsPath); - snippetFilenames.sort((a, b) => { + let directoryFilenames = fs.readdirSync(directoryPath); + directoryFilenames.sort((a, b) => { a = a.toLowerCase(); b = b.toLowerCase(); if (a < b) return -1; if (a > b) return 1; return 0; }); - // Store the data read from each snippet in the appropriate object + + if (withPath) { + // a hacky way to do conditional array.map + return directoryFilenames.reduce((fileNames, fileName) => { + if (exclude == null || !exclude.some(toExclude => fileName === toExclude)) + fileNames.push(`${directoryPath}/${fileName}`); + return fileNames; + }, []); + } + return directoryFilenames; + } catch (err) { + console.log(`${chalk.red('ERROR!')} During snippet loading: ${err}`); + process.exit(1); + } +} + +// Synchronously read all snippets and sort them as necessary (case-insensitive) +const readSnippets = snippetsPath => { + const snippetFilenames = getFilesInDir(snippetsPath, false); + + let snippets = {}; + try { for (let snippet of snippetFilenames) snippets[snippet] = fs.readFileSync(path.join(snippetsPath, snippet), 'utf8'); } catch (err) { - // Handle errors (hopefully not!) console.log(`${chalk.red('ERROR!')} During snippet loading: ${err}`); process.exit(1); } @@ -108,4 +133,17 @@ const getTextualContent = str => { } return results[1]; }; -module.exports = {readSnippets, readTags, optimizeNodes, capitalize, objectFromPairs, isTravisCI, hashData, shuffle, getCodeBlocks, getTextualContent}; +module.exports = { + getMarkDownAnchor, + getFilesInDir, + readSnippets, + readTags, + optimizeNodes, + capitalize, + objectFromPairs, + isTravisCI, + hashData, + shuffle, + getCodeBlocks, + getTextualContent +};