Skip to content

Commit

Permalink
Refactoring code into argv.ts and html-maker.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
tpmai22 committed Oct 15, 2021
1 parent 17b11cc commit 6f20f71
Show file tree
Hide file tree
Showing 6 changed files with 138 additions and 125 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2021 Amazing
Copyright (c) 2021 James Mai Email: thienphuoc.0108@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ ts-node src/index.ts -i .\testFolder\
Using config file:

```
ts-node src/index.ts -c config.json
ts-node src/index.ts -c src/config.json
```

## License
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"chalk": "^3.0.0",
"commander": "^8.2.0",
"fs-extra": "^10.0.0",
"typescipt": "^1.0.0",
"typescript": "^1.0.0",
"yargs": "^17.1.1"
}
}
24 changes: 24 additions & 0 deletions src/argv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as yargs from 'yargs';

const argv = yargs
.option({
input: {
alias: 'i',
describe: 'Text file to create an html file',
type: 'string',
demandOption: true,
requiresArg: true,
},
})
.config()
.alias('config', 'c')
.help()
.alias('help', 'h')
.version()
.alias('version', 'v').argv as {
input: string;
_: (string | number)[];
$0: string;
};

export default argv;
77 changes: 77 additions & 0 deletions src/html-maker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import * as fs from 'fs-extra';
import * as path from 'path';

const heading1Markdown = (content: string): string => { //heading1Markdown() takes the content which is unformatted md file text.

return content.split(/[\r?\n\r?\n]/g)
.map((line) =>
line
.replace (/(^`)(.+?(?=`))(`$)/gim, '<code>$2</code>')
.replace(/-{3}/gim, '<hr>')
.replace(/(^(?!<)[^#](.*$))/gim, '<p>$1</p>')
.replace(/^##\s(.*$)/gim, "<h2>$1</h2>")
.replace(/^#\s(.*$)/gim, '<h1>$1</h1>')

/*
replace any line starting with # and a space with <h1> surrounding itself.
replace any line starting with an alphabetical character followed by 0 or more of anything with <p> surrounding itself.
*/
).join('\n'); //this makes the content a string rather than array.
};

const processMarkdown = (data: string): string => {
let processedContent: string = "";
processedContent = heading1Markdown(data);
return processedContent;
};
//Create html markup file from provided text file
const processingFile = (filePath: string): string => {
const fileExt = path.extname(filePath).toLowerCase();
if (fileExt !== '.txt' && fileExt !== ".md") {
return '';
}

const file = fs.readFileSync(filePath, 'utf-8');

// title is before the first 2 blank lines of the text
let titleAndContent = file.split(/\n\n\n/);
let title = '';
let content = '';

if (titleAndContent.length >= 2) {
[title] = titleAndContent;
content = titleAndContent.slice(1).join('\n\n\n');
} else {
[content] = titleAndContent;
}

const head = `<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>${title || path.basename(filePath, '.txt') || path.basename(filePath, '.md')}</title>`;
const body = `
${title ? `<h1 class="text-center">${title}</h1>` : ''}
${
fileExt === ".md" //if it's markdown do some extra processing.
? processMarkdown(content)
: content //for regular txt files.
.split(/\r?\n\r?\n/)
.map((para) => `<p>${para.replace(/\r?\n/, ' ')}</p>`)
.join('\n')
}
`;
const markup = `<!DOCTYPE html>
<html lang="en">
<head>
${head}
</head>
<body>
${body}
</body>
</html>`;

return markup.split(/\n\s+/).join('\n'); // formatting the html.
};

export default processingFile;
156 changes: 34 additions & 122 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,10 @@
#!/usr/bin/env node

import * as yargs from 'yargs';
import * as fs from 'fs-extra';
import * as path from 'path';

const argv = yargs
.option({
input: {
alias: 'i',
describe: 'Text file to create an html file',
type: 'string',
demandOption: true,
requiresArg: true,
},
})
.config()
.alias('config', 'c')
.help()
.alias('help', 'h')
.version()
.alias('version', 'v').argv as {
input: string;
_: (string | number)[];
$0: string;
};
import argv from './argv';
import processingFile from './html-maker';

const { input } = argv;

const outputDir = 'dist';
Expand All @@ -33,79 +14,7 @@ fs.ensureFileSync(`${outputDir}/index.css`);

fs.copyFileSync('src/styles/index.css', `${outputDir}/index.css`);

const heading1Markdown = (content: string): string => { //heading1Markdown() takes the content which is unformatted md file text.

return content.split(/[\r?\n\r?\n]/g)
.map((line) =>
line
.replace (/(^`)(.+?(?=`))(`$)/gim, '<code>$2</code>')
.replace(/-{3}/gim, '<hr>')
.replace(/(^(?!<)[^#](.*$))/gim, '<p>$1</p>')
.replace(/^##\s(.*$)/gim, "<h2>$1</h2>")
.replace(/^#\s(.*$)/gim, '<h1>$1</h1>')

/*
replace any line starting with # and a space with <h1> surrounding itself.
replace any line starting with an alphabetical character followed by 0 or more of anything with <p> surrounding itself.
*/
).join('\n'); //this makes the content a string rather than array.
};

const processMarkdown = (data: string): string => {
let processedContent: string = "";
processedContent = heading1Markdown(data);
return processedContent;
};
//Create html markup file from provided text file
const processingFile = (filePath: string): string => {
const fileExt = path.extname(filePath).toLowerCase();
if (fileExt !== '.txt' && fileExt !== ".md") {
return '';
}

const file = fs.readFileSync(filePath, 'utf-8');

// title is before the first 2 blank lines of the text
let titleAndContent = file.split(/\n\n\n/);
let title = '';
let content = '';

if (titleAndContent.length >= 2) {
[title] = titleAndContent;
content = titleAndContent.slice(1).join('\n\n\n');
} else {
[content] = titleAndContent;
}

const head = `<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>${title || path.basename(filePath, '.txt') || path.basename(filePath, '.md')}</title>`;
const body = `
${title ? `<h1 class="text-center">${title}</h1>` : ''}
${
fileExt === ".md" //if it's markdown do some extra processing.
? processMarkdown(content)
: content //for regular txt files.
.split(/\r?\n\r?\n/)
.map((para) => `<p>${para.replace(/\r?\n/, ' ')}</p>`)
.join('\n')
}
`;
const markup = `<!DOCTYPE html>
<html lang="en">
<head>
${head}
</head>
<body>
${body}
</body>
</html>`;

return markup.split(/\n\s+/).join('\n'); // formatting the html.
};

const processFilePath = (any) : void =>{
let inputPath;
try {
inputPath = fs.statSync(input);
Expand Down Expand Up @@ -136,34 +45,37 @@ if (inputPath.isFile()) {
});

const indexMarkup = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>${path.basename(input)}</title>
</head>
<body>
<h1>${path.basename(input)}</h1>
<ul>
${dists
.map(
(dist) =>
`<li><a href="${path.relative(outputDir, dist)}">${path.basename(
dist,
'.html'
)}</a></li>`
)
.join('\n')}
</ul>
</body>
</html>`
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>${path.basename(input)}</title>
</head>
<body>
<h1>${path.basename(input)}</h1>
<ul>
${dists
.map(
(dist) =>
`<li><a href="${path.relative(outputDir, dist)}">${path.basename(
dist,
'.html'
)}</a></li>`
)
.join('\n')}
</ul>
</body>
</html>`
.split(/\n\s+/)
.join('\n');

fs.writeFileSync(`${outputDir}/index.html`, indexMarkup, { flag: 'w' });
} else {
console.error(`${input}: No such file or directory`);
process.exit(1);
fs.writeFileSync(`${outputDir}/index.html`, indexMarkup, { flag: 'w' });
} else {
console.error(`${input}: No such file or directory`);
process.exit(1);
}
}


0 comments on commit 6f20f71

Please sign in to comment.