Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding configuration option #21

Merged
merged 3 commits into from
Oct 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"input": "./test",
"output": "./dist",
"stylesheet": "https://cdn.jsdelivr.net/npm/water.css@2/out/water.css",
"lang": "fr"
}
294 changes: 162 additions & 132 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,140 @@ const { program } = require('commander');


program.version( require('./package.json').version); // Getting the verison of the file
program.option('-i ,--index', 'Single txt file ') // option for adding a single text file

program
.option('-i ,--index', 'Single txt file ') // option for adding a single text file
.option('-c ,--config','JSON configuration file');

program.parse(process.argv);

const options = program.opts(); // The --index or -i options

if(options.index){
let stats = fs.statSync(process.argv[3]); // Finding out if the file is a file or folder
try{ // checking the JSON file exist
const config = require('./config.json');

var data = {
input: config.input ?? "./text files",
output: config.output ?? "./dist"
}

}catch(e){ // throw error message when JSON file does not exist
if (e instanceof Error && e.code === "MODULE_NOT_FOUND")
console.log("Can't load JSON file!");
else
throw e;
}

if(options.index || options.config){
let stats = fs.statSync(process.argv[3]); // Finding out if the file is a file or folder

let isFile = stats.isFile()
let isDir = stats.isDirectory()

if (isFile) { // if the passed value is a file
let isJson = isJSON(process.argv[3]) // check this is JSON file

if (isFile && !isJson) { // if the passed value is a file
generateHTMLFromFile() // using default parameter
} else if (isDir) {
generateHTMLFromDir() // using default parameter
} else if(isJson){
let status = fs.statSync(data.input);
let fileStatus = status.isFile();

if(fileStatus){
generateHTMLFromFile(path.basename(data.input), data.output);
}
else
generateHTMLFromDir(path.basename(data.input), data.output)
}

}

function createHTMLFromMarkdown(para) {
let p = para
.replace(/^# (.*$)/gim, "<h1>$1</h1>")
.replace(/^## (.*$)/gim, "<h2>$1</h2>")
.replace(/^--- (.*$)/gim, "<hr/>")
.replace(/^### (.*$)/gim, '<h3>$1</h3>')
.replace(/^\> (.*$)/gim, '<blockquote>$1</blockquote>')
.replace(/\*\*(.*)\*\*/gim, '<b>$1</b>')
.replace(/\*(.*)\*/gim, '<i>$1</i>')
.replace(/\[(.*?)\]\((.*?)\)/gim, "<a href='$2'>$1</a>")
.replace(/\n$/gim, '<br /><br />')
.replace(/^( ?[-_*]){3,} ?[\t]*$/ , '<hr>')
.replace(/`([^`]+)`/g, '<code>$1</code>');

return `<p style=" font-family: 'Gentium Basic', serif; font-size: 24px; padding: 10px; border-radius: 20px">${p}</p>`;
}

function removeMarkdownFormatting(text){
return text
.replace(/^### (.*$)/gim, '$1')
.replace(/^## (.*$)/gim, '$1')
.replace(/^# (.*$)/gim, '$1')
.replace(/^\> (.*$)/gim, '$1')
.replace(/\*\*(.*)\*\*/gim, '$1')
.replace(/\*(.*)\*/gim, '$1')
.replace(/\n$/gim, '$1')
}

function readMarkdownFile(file, folderName) {
fs.readFile(
file,
{ encoding: "utf8", flag: "r" },
function (err, data) {
if (err) console.log(err);
let title = removeMarkdownFormatting(data.split("\n")[0]);
data = data.replace(title, ""); // removes the title from the text

const folderName = 'dist';
var editedText = data
.split(/\r?\n\r?\n/)
.map((para) => `<p style="font-family: 'Gentium Basic', serif; font-size: 20px; ">` + createHTMLFromMarkdown(para) + `</p>`)
.join("\n");

let titleInsidePTag = `<h1 style="text-align: center; background-color: black; color: white; width: 50%; border-radius: 10px; margin: auto; top: 15px; ">${title}</h1>`;

// Appending the title
fs.appendFile(
`${process.cwd()}/${folderName}/${path.parse(file).name}.html`,
titleInsidePTag,
function (err) {
if (err) throw err;
}
);

// Appending the rest of the text
fs.appendFile(
`${process.cwd()}/${folderName}/${path.parse(file).name}.html`,
editedText.replace(title, ""),
function (err) {
if (err) throw err;
}
);
}
);
}

function emptyDirectory(directory){
fs.readdir(directory, (err, files) => {
if (err) throw err;

for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
});
}

function isJSON(stats){
if(path.extname(stats) == ".json")
return true
else
return false
}

function generateHTMLFromFile(input = process.argv[3], output="./dist"){
const folderName = output;
console.log(input);
// creating the dist folder if it doesn't exist

try {
Expand All @@ -37,64 +154,61 @@ if(options.index){
}

function createHTML(){


var filename = process.argv[3]
var filename = input
const htmlFile = fs.readFileSync(`${__dirname}/index.html`)

filenameWithoutExt = path.parse(filename).name; // The name part of the file (EX: name.txt => name)
fs.writeFileSync(`${process.cwd()}/${folderName}/${filenameWithoutExt}.html` , htmlFile);
fs.readFile(filename , {encoding:'utf8', flag:'r'},
function(err, data) {
if(err)
console.log(err);
else
var editedText = data // Editing the text to recieved from the files
.split(/\r?\n\r?\n/)
.map(para =>
`<p font-family: 'Gentium Basic', serif; font-size: 24px; padding: 10px; border-radius: 20px">${para.replace(/\r?\n/, ' ')}</p>`
)
.join(' ');
let title = editedText.split("</p>")[0].split(">" , 2)[1]; // getting the title of the text

fs.writeFileSync(`${process.cwd()}/${folderName}/${filenameWithoutExt}.html`, htmlFile);

fs.readFile(filename, { encoding: 'utf8', flag: 'r' },
function (err, data) {
if (err)
console.log(err);
else

var editedText = data // Editing the text to recieved from the files
.split(/\r?\n\r?\n/)
.map(para =>
`<p font-family: 'Gentium Basic', serif; font-size: 24px; padding: 10px; border-radius: 20px">${para.replace(/\r?\n/, ' ')}</p>`
)
.join(' ');


let title = editedText.split("</p>")[0].split(">", 2)[1]; // getting the title of the text

titleInsidePTag = `<h1 style="text-align: center; background-color: black; color: white; width: 50%; border-radius: 10px; margin: auto; top: 15px; ">${title}</h1>`

// Appending the title
fs.appendFile(`${process.cwd()}/${folderName}/${path.parse(filename).name}.html` , titleInsidePTag , function(err){
if(err) throw err;
fs.appendFile(`${process.cwd()}/${folderName}/${path.parse(filename).name}.html`, titleInsidePTag, function (err) {
if (err) throw err;
})

// Appending the rest of the text
fs.appendFile(`${process.cwd()}/${folderName}/${path.parse(filename).name}.html` , editedText.replace(title , "") , function(err){
if(err) throw err;
fs.appendFile(`${process.cwd()}/${folderName}/${path.parse(filename).name}.html`, editedText.replace(title, ""), function (err) {
if (err) throw err;
})
})

}

let extension = path.extname(process.argv[3]);

}
let extension = path.extname(input);
if (extension === ".txt") {
const directory = 'dist';
const directory = output;
emptyDirectory(directory);
createHTML();

console.log("Operation Successful\nHTML file created");
} else if (extension === ".md") {
const directory = 'dist'
emptyDirectory(directory);
readMarkdownFile(process.argv[3], "dist")
readMarkdownFile(input, output)
console.log("Operation Successful\nHTML file created");
}

} else if (isDir) {

const folderName = 'dist';
}

function generateHTMLFromDir(input = process.argv[3], output = "dist"){
const folderName = output;

// creating the dir folder if it doesn't exist

Expand All @@ -108,16 +222,14 @@ if(options.index){

// If a FOLDER is passed (reza-ssg --folder "text files")

console.log(process.argv[3]);

// Function to get current filenames
// in directory with specific extension
files = fs.readdirSync(__dirname + '/text files');
files = fs.readdirSync(__dirname + "\\" + input);

files.forEach(file => { // getting the files inside the folder

if (path.extname(file) == ".txt"){ // Finding the text files
const folderName = 'dist';
//const folderName = 'dist';

const htmlFile = fs.readFileSync(`${__dirname}/index.html`)

Expand Down Expand Up @@ -156,7 +268,7 @@ if(options.index){

})
}else if (path.extname(file) == ".md") {
const folderName = "dist";
const folderName = output;

const htmlFile = fs.readFileSync(`${__dirname}/index.html`);

Expand All @@ -173,88 +285,6 @@ if(options.index){

console.log('Files processed.');
console.log('HTML Files created.');
}

}

function createHTMLFromMarkdown(para) {
let p = para
.replace(/^# (.*$)/gim, "<h1>$1</h1>")
.replace(/^## (.*$)/gim, "<h2>$1</h2>")
.replace(/^--- (.*$)/gim, "<hr/>")
.replace(/^### (.*$)/gim, '<h3>$1</h3>')
.replace(/^\> (.*$)/gim, '<blockquote>$1</blockquote>')
.replace(/\*\*(.*)\*\*/gim, '<b>$1</b>')
.replace(/\*(.*)\*/gim, '<i>$1</i>')
.replace(/\[(.*?)\]\((.*?)\)/gim, "<a href='$2'>$1</a>")
.replace(/\n$/gim, '<br /><br />')
.replace(/^( ?[-_*]){3,} ?[\t]*$/ , '<hr>')
.replace(/`([^`]+)`/g, '<code>$1</code>');

return `<p style=" font-family: 'Gentium Basic', serif; font-size: 24px; padding: 10px; border-radius: 20px">${p}</p>`;
}

function removeMarkdownFormatting(text){
return text
.replace(/^### (.*$)/gim, '$1')
.replace(/^## (.*$)/gim, '$1')
.replace(/^# (.*$)/gim, '$1')
.replace(/^\> (.*$)/gim, '$1')
.replace(/\*\*(.*)\*\*/gim, '$1')
.replace(/\*(.*)\*/gim, '$1')
.replace(/\n$/gim, '$1')
}

function readMarkdownFile(file, folderName) {
fs.readFile(
file,
{ encoding: "utf8", flag: "r" },
function (err, data) {
if (err) console.log(err);
let title = removeMarkdownFormatting(data.split("\n")[0]);
data = data.replace(title, ""); // removes the title from the text

var editedText = data
.split(/\r?\n\r?\n/)
.map((para) => `<p style="font-family: 'Gentium Basic', serif; font-size: 20px; ">` + createHTMLFromMarkdown(para) + `</p>`)
.join("\n");

let titleInsidePTag = `<h1 style="text-align: center; background-color: black; color: white; width: 50%; border-radius: 10px; margin: auto; top: 15px; ">${title}</h1>`;

// Appending the title
fs.appendFile(
`${process.cwd()}/${folderName}/${path.parse(file).name}.html`,
titleInsidePTag,
function (err) {
if (err) throw err;
}
);

// Appending the rest of the text
fs.appendFile(
`${process.cwd()}/${folderName}/${path.parse(file).name}.html`,
editedText.replace(title, ""),
function (err) {
if (err) throw err;
}
);
}
);
}

function emptyDirectory(directory){
fs.readdir(directory, (err, files) => {
if (err) throw err;

for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
});
}



// ----------------------------------------------------------------------------------------------------------