Skip to content

Commit

Permalink
Refactoring to improve code maintainability:
Browse files Browse the repository at this point in the history
	* Move handler file to handler folder

	* remove unused package

	* Remove duplicate code

	* Add error handling for await

	* Use promisified versions of fs

	* Isolate function not related to ssgHandler to it own files

	* Refactor names
  • Loading branch information
Kevan-Y committed Oct 14, 2021
1 parent de50842 commit b092da9
Show file tree
Hide file tree
Showing 8 changed files with 349 additions and 333 deletions.
55 changes: 23 additions & 32 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const yargs = require('yargs');
const version = require('../package.json').version;
const clear = require('clear');
const convertToHtml = require('../ssgHandler');
const convertToHtml = require('./utils/handler/ssgHandler');
const chalk = require('chalk');
const figlet = require('figlet');
const { stylesheetCheck } = require('./utils/yargsOptionCheck/stylesheetCheck');
Expand All @@ -12,7 +12,8 @@ const { langCheck } = require('./utils/yargsOptionCheck/langCheck');
const {
configurationCheck,
} = require('./utils/yargsOptionCheck/configurationCheck');
const { readConfig } = require('../applyConfiguration');
const { readConfig } = require('./utils/handler/readConfiguration');

//Clear CLI and display Header
clear();
console.log(
Expand Down Expand Up @@ -44,7 +45,6 @@ yargs.example(`ssg -c <path> -i <path>`);
yargs.strict().fail((msg, err, yargs) => {
//Print Error with help option
console.log(yargs.help());

console.error(`\n\n${chalk.red.bold('Error:')} ${chalk.red(msg || err)}`);
process.exit(1);
});
Expand Down Expand Up @@ -114,36 +114,27 @@ yargs
});

//if the option is c or config, use the custom configuration
if (yargs.argv.c) {
try {
const config = readConfig(yargs.argv.c);
if (!config.input) throw new Error('Directory or file must exist.');
convertToHtml(
config.input,
config.stylesheet,
config.output || './dist',
isFile(config.input),
config.lang,
);
} catch (e) {
console.error(`\n\n${chalk.red.bold('Error:')} ${chalk.red(e)}`);
process.exit(1);
}
} else {
yargs.demandOption(['input']);
try {
let config = null;
if (yargs.argv.c) {
config = readConfig(yargs.argv.c);
inputCheck(config.input);
langCheck((config.lang ||= 'en-CA'));
outputCheck((config.output ||= './dist'));
stylesheetCheck(config.stylesheet);
} else yargs.demandOption(['input']);

//Call convertToHtml
try {
convertToHtml(
yargs.argv.i,
yargs.argv.s,
yargs.argv.o,
isFile(yargs.argv.i),
yargs.argv.l,
);
} catch (e) {
console.error(`\n\n${chalk.red.bold('Error:')} ${chalk.red(e)}`);
process.exit(1);
}
convertToHtml(
config ? config.input : yargs.argv.i,
config ? config.stylesheet : yargs.argv.s,
config ? config.output : yargs.argv.o,
isFile(config ? config.input : yargs.argv.i),
config ? config.lang : yargs.argv.l,
);
} catch (e) {
yargs.showHelp('log');
console.error(`\n\n${chalk.red.bold('Error:')} ${chalk.red(e.message)}`);
process.exit(1);
}
yargs.argv;
68 changes: 68 additions & 0 deletions src/utils/handler/dataProcessing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* dataProcessing separate data title and content
* @param {string} data
* @return {object} title and content
*/
const dataProcessing = (data, fileExtension) => {
let dataTreated = { title: '', content: '' };

if (fileExtension === '.txt') {
//convert data into an array
data = data.split('\n').map((sentence) => sentence.replace('\r', ''));

if (data.length >= 3) {
//Check if title exist
if (data[0] && !data[1] && !data[2]) {
dataTreated.title = data[0];
data = data.slice(3);
}
}

//Remove empty array and combine sentence together
data.forEach((phase, i) => {
if (!phase) data[i] = '_space_';
});
data = data.join('').split('_space_');
dataTreated.content = data.map((paragraph) => `<p>${paragraph}</p>`);
} else {
// If file is .md, assuming the Markdown syntax is correct, replace each Markdown tag to its HTML equivalent

// convert --- to <hr>
const hr = new RegExp(/^---$/, 'gm');
data = data.replaceAll(hr, '<hr>');

// Links could have the form of [name](href title) or [name](href)
const links = new RegExp(/\[(.*?)\]\((.+?)(?:\s"(.*?)")?\)/, 'gm');
data = data.replaceAll(
links,
(match, p1, p2, p3) =>
`<a href="${p2}" ${p3 ? `title="${p3}"` : ''}>${p1}</a>`,
);

const bolds = new RegExp(/\*{2}(.+?)\*{2}/, 'gm');
data = data.replaceAll(bolds, '<strong>$1</strong>');

const italics = new RegExp(/\*{1}(.+?)\*{1}/, 'gm');
data = data.replaceAll(italics, '<i>$1</i>');

data = data.split(/(?:\r?\n)+/).map((paragraph) => {
// heading starts with 1 or more hash sign followed by a white space
const headings = new RegExp(/^\s*(#{1,6})\s+(.+)$/, 'gm');
if (headings.test(paragraph)) {
return paragraph.replaceAll(headings, (match, hash, title) => {
dataTreated.title =
!dataTreated.title && hash.length === 1 ? title : dataTreated.title;
const tag = `h${hash.length}`;
return `<${tag}>${title}</${tag}>`;
});
}
if (/^<.*>$/.test(paragraph)) return paragraph;
return `<p>${paragraph}</p>`;
});

// in markdown, paragraphs are splitted by one or more New line.
dataTreated.content = data;
}
return dataTreated;
};
module.exports = { dataProcessing };
90 changes: 90 additions & 0 deletions src/utils/handler/generateHtmlFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
const {
generateHtmlTemplate,
generateHtmlMenuTemplate,
} = require('./htmlTemplate');
const path = require('path');
const { dataProcessing } = require('./dataProcessing');
const fs = require('fs');

/**
* createHtmlFile generateHTML file
* @param {string} fileName
* @param {string} data
* @param {string} stylesheet
* @param {string} outputPath
* @param {string} langCode
*/
const createHtmlFile = async (
fileName,
data,
stylesheet,
outputPath,
langCode,
) => {
const extname = path.extname(fileName);
fileName = path.basename(fileName, extname);

let htmlOption = {
...dataProcessing(data, extname),
style: stylesheet,
extname,
langCode,
};

const noSpaceFileName = fileName.replaceAll(' ', '-');
try {
//Create a new html file
await fs.promises.writeFile(
path.join(`${outputPath}`, `${noSpaceFileName}.html`),
generateHtmlTemplate(htmlOption),
(err) => {
if (err) throw new Error(err);
},
);
} catch (e) {
throw new Error(
`On write file ${path.join(`${outputPath}`, `${noSpaceFileName}.html`)}`,
);
}
console.log(
`File created -> ${path.join(`${outputPath}`, `${noSpaceFileName}.html`)}`,
);
return path.join(`${outputPath}`, `${fileName}.html`);
};

/**
* createHtmlFile generateHTML file
* @param {Array} routeList - Array containing name and url for the file route
* @param {string} stylesheet
* @param {string} outputPath
* @param {string} langCode
*/
const createIndexHtmlFile = async (
routeList,
stylesheet,
outputPath,
langCode,
) => {
let htmlOption = {
routeList,
style: stylesheet,
langCode,
};
try {
//Create a new html file
await fs.promises.writeFile(
path.join(`${outputPath}`, `index.html`),
generateHtmlMenuTemplate(htmlOption),
(err) => {
if (err) throw new Error(err);
},
);
} catch (e) {
throw new Error(
`On write file ${path.join(`${outputPath}`, `index.html`)}`,
);
}
console.log(`File created -> ${path.join(`${outputPath}`, `index.html`)}`);
};

module.exports = { createHtmlFile, createIndexHtmlFile };
30 changes: 30 additions & 0 deletions src/utils/handler/getAllFiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const path = require('path');
const fs = require('fs');

/**
* getAllFiles getting all file of a folder recursively
* @param {string} dirPath
* @param {Array} filesPathList
*/
const getAllFiles = async (dirPath, filesPathList) => {
const files = await fs.promises.readdir(dirPath);
filesPathList ||= [];

for (const file of files) {
const fileLstat = await fs.promises.lstat(path.join(dirPath, file));
if (fileLstat.isDirectory()) {
filesPathList = await getAllFiles(
path.join(dirPath, file),
filesPathList,
);
} else {
const extname = path.extname(file);
if (extname === '.txt' || extname === '.md')
filesPathList.push(path.join(dirPath, file));
}
}

return filesPathList;
};

module.exports = { getAllFiles };
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
const path = require('path');
const fs = require('fs');


/**
* readConfig reads the configuration options
* @param {string} fileName
Expand Down
Loading

1 comment on commit b092da9

@vercel
Copy link

@vercel vercel bot commented on b092da9 Oct 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.