feat$(scripts, util): add md anchor and getFilesInDir methods

This commit is contained in:
Felix Wu
2018-07-28 23:24:34 +02:00
parent 9b09735231
commit 71ffd7373b

View File

@ -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
};