Skip to content

Commit

Permalink
It works 🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
astronomersiva committed Jul 30, 2018
1 parent 6447c63 commit 0d20d4d
Show file tree
Hide file tree
Showing 18 changed files with 1,499 additions and 75 deletions.
14 changes: 10 additions & 4 deletions lib/lego.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
const Site = require('./site');

const runTask = require('./utils/runTask');

module.exports = async function(args) {
const site = new Site();

const [task] = args;
try {
if (task) {
runTask(task);
runTask(task, site);
} else {
const taskList = [
'cleanBuild',
'copyCNAME',
'generate404Page',
'generatePages',
'generatePostsFromMarkdown',
'generatePagesForTags',
'copyMinorStaticAssets',
'copyMajorStaticAssets'
'copyMajorStaticAssets',
'startServer'
];

for (const task of taskList) {
await runTask(task);
await runTask(task, site);
}
}
} catch (error) {
Expand Down
66 changes: 66 additions & 0 deletions lib/site.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const fs = require('fs-extra');
const path = require('path');
const markdownIt = require('markdown-it');
const markdownItContainer = require('markdown-it-container');
const frontMatter = require('markdown-it-front-matter');

const filterFileList = require('./utils/filterFileList');
const yamlToObject = require('./utils/yamlToObject');

const { POSTS, LAYOUTS } = require('./utils/constants');

let _post = {};

const mdOptions = {
html: true
};

const md = markdownIt(mdOptions)
.use(frontMatter, function(fm) {
_post = yamlToObject(fm);
})
.use(markdownItContainer, 'include', {
validate: function(params) {
return params.endsWith(':::') && params.includes('include');
},

render: function(tokens, idx) {
let statement = tokens[idx];
if (statement.type === 'container_include_open') {
let [, elements] = statement.info.trim().split(' ');
return fs.readFileSync(`${LAYOUTS}/${elements}`).toString();
}
}
});

class Site {
constructor() {
this._posts = [];
this._tags = [];

const posts = fs.readdirSync(POSTS);
const filteredPages = filterFileList(posts, 'md');

for (const post of filteredPages) {
const pageContents = fs.readFileSync(`${POSTS}/${post}`).toString();
const renderedMarkdown = md.render(pageContents);
let postData = Object.assign({
path: path.parse(post).name,
html: renderedMarkdown
}, _post);

this._posts.push(postData);
this._tags = this._tags.concat(postData.tags || []);
}
}

getPosts() {
return this._posts;
}

getTags() {
return this._tags;
}
}

module.exports = Site;
5 changes: 2 additions & 3 deletions lib/tasks/copyCNAME.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
const fs = require('fs-extra');
const path = require('path');

const { BUILD } = require('../utils/constants');

module.exports = async function() {
module.exports = function() {
try {
await fs.copy('CNAME', path.join(BUILD, 'CNAME'));
fs.copySync('CNAME', `${BUILD}/CNAME`);
} catch (error) {
throw error;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/tasks/copyMajorStaticAssets.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ module.exports = async function() {

for (const asset of assets) {
let destination = path.join(BUILD, asset);
let destinationDir = path.join(BUILD, path.dirname(asset));
let destinationDir = `${BUILD}/${path.dirname(asset)}`;

if (!fs.existsSync(destinationDir)) {
fs.mkdirpSync(destinationDir);
Expand Down
5 changes: 2 additions & 3 deletions lib/tasks/copyMinorStaticAssets.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const fs = require('fs-extra');
const path = require('path');

const cleanFileList = require('../utils/cleanFileList');
const { STATIC, BUILD } = require('../utils/constants');
Expand All @@ -11,8 +10,8 @@ module.exports = async function() {

for (const asset of minorStaticFiles) {
fs.copySync(
path.join(STATIC, asset),
path.join(BUILD, STATIC, asset)
`${STATIC}/${asset}`,
`${BUILD}/${STATIC}/${asset}`
);
}
} catch (error) {
Expand Down
19 changes: 0 additions & 19 deletions lib/tasks/generate404Page.js

This file was deleted.

34 changes: 34 additions & 0 deletions lib/tasks/generatePages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const fs = require('fs-extra');
const path = require('path');

const generateHtmlFromLiquid = require('../utils/generateHtmlFromLiquid');
const filterFileList = require('../utils/filterFileList');
const { PAGES, BUILD } = require('../utils/constants');

module.exports = async function(site) {
try {
const posts = site.getPosts();
const pages = fs.readdirSync(PAGES);
const filteredPages = filterFileList(pages, 'html')
.filter(page => page !== '404.html');

for (const page of filteredPages) {
const pageContents = fs.readFileSync(`${PAGES}/${page}`).toString();
const htmlPath = `${BUILD}/${path.parse(page).name}`;
fs.mkdirp(htmlPath);

const renderedHtml = await generateHtmlFromLiquid(pageContents, { posts });
fs.writeFileSync(`${htmlPath}/index.html`, renderedHtml);
}

// copy index/index.html to index.html also
fs.copySync(`${BUILD}/index/index.html`, `${BUILD}/index.html`);

// generate 404 page
const pageContents = fs.readFileSync(`${PAGES}/404.html`).toString();
const renderedHtml = await generateHtmlFromLiquid(pageContents, { posts });
fs.writeFileSync(`${BUILD}/404.html`, renderedHtml);
} catch (error) {
throw error;
}
}
22 changes: 22 additions & 0 deletions lib/tasks/generatePagesForTags.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const fs = require('fs-extra');

const generateHtmlFromLiquid = require('../utils/generateHtmlFromLiquid');
const { BUILD, LAYOUTS } = require('../utils/constants');

module.exports = async function(site) {
try {
const baseTemplate = fs.readFileSync(`${LAYOUTS}/tag.html`).toString();
const tags = [...new Set(site.getTags())];
const posts = site.getPosts();

for (const tag of tags) {
const htmlPath = `${BUILD}/tag/${tag}`;
fs.mkdirp(htmlPath);

const renderedHtml = await generateHtmlFromLiquid(baseTemplate, { posts, tag });
fs.writeFileSync(`${htmlPath}/index.html`, renderedHtml);
}
} catch (error) {
throw error;
}
}
36 changes: 7 additions & 29 deletions lib/tasks/generatePostsFromMarkdown.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,18 @@
const fs = require('fs-extra');
const path = require('path');
const markdownIt = require('markdown-it');
const frontMatter = require('markdown-it-front-matter');

const generateHtmlFromLiquid = require('../utils/generateHtmlFromLiquid');
const filterFileList = require('../utils/filterFileList');
const yamlToObject = require('../utils/yamlToObject');
const { BUILD, PAGES, LAYOUTS } = require('../utils/constants');
const { BUILD, LAYOUTS } = require('../utils/constants');

let postData = {};
const md = markdownIt()
.use(frontMatter, function(fm) {
postData = yamlToObject(fm);
});

module.exports = async function() {
module.exports = async function(site) {
try {
const baseTemplate = fs.readFileSync(path.join(LAYOUTS, 'post.html')).toString();
const pages = fs.readdirSync(PAGES, { encoding: 'utf8' });
const filteredPages = filterFileList(pages, 'md');

if (!fs.existsSync(BUILD)) {
fs.mkdirSync(BUILD);
}

for (const page of filteredPages) {
const pageContents = fs.readFileSync(path.join(PAGES, page)).toString();
const htmlPath = path.join(BUILD, path.parse(page).name);
const baseTemplate = fs.readFileSync(`${LAYOUTS}/post.html`).toString();

for (const post of site.getPosts()) {
const htmlPath = `${BUILD}/${post.path}`;
fs.mkdirp(htmlPath);
const renderedMarkdown = md.render(pageContents);
const post = { html: renderedMarkdown };
Object.assign(post, postData);
const renderedHtml = await generateHtmlFromLiquid(baseTemplate, { page: post });

fs.writeFileSync(path.join(htmlPath, 'index.html'), renderedHtml);
const renderedHtml = await generateHtmlFromLiquid(baseTemplate, { post });
fs.writeFileSync(`${htmlPath}/index.html`, renderedHtml);
}
} catch (error) {
throw error;
Expand Down
15 changes: 15 additions & 0 deletions lib/tasks/startServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const liveServer = require('live-server');
const { BUILD } = require('../utils/constants');

module.exports = function() {
const params = {
port: 8181,
host: '0.0.0.0',
root: BUILD,
open: true,
wait: 500,
logLevel: 1
};

liveServer.start(params);
}
1 change: 1 addition & 0 deletions lib/utils/constants.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = {
BUILD: 'build',
PAGES: 'pages',
POSTS: 'posts',
STATIC: 'static',
LAYOUTS: 'layouts'
}
3 changes: 2 additions & 1 deletion lib/utils/filterFileList.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const cleanFileList = require('./cleanFileList');
const extensions = {
js: '.js',
css: '.css',
md: '.md'
md: '.md',
html: '.html'
};

module.exports = function(files, extension) {
Expand Down
15 changes: 15 additions & 0 deletions lib/utils/generateHtmlFromLiquid.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,21 @@ const { LAYOUTS } = require('./constants');
// needed for `include` statements
engine.registerFileSystem(new Liquid.LocalFileSystem(LAYOUTS));

// custom filters
engine.registerFilters({
sortByDate: function(array) {
return array.sort(function(first, second) {
return new Date(second.date) - new Date(first.date);
});
},

sortByOrder: function(array) {
return array.sort(function(first, second) {
return Number(second.order) - Number(first.order);
});
}
});

module.exports = function(contents, options = {}) {
return engine.parseAndRender(contents, options);
}
6 changes: 2 additions & 4 deletions lib/utils/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@ const {

class Logger {
refresh() {
if (process.env.DEBUG) {
return;
if (!process.env.DEBUG) {
clear();
}

clear();

let { message, stack } = this;
process.stdout.write(`${message}\n\n\n`);
if (stack) {
Expand Down
4 changes: 2 additions & 2 deletions lib/utils/runTask.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const Logger = require('./logger');
const tasks = require('./tasks');

module.exports = async function(task) {
module.exports = async function(task, site) {
const logger = new Logger();

try {
logger.setMessage(`Running ${task}`);
await tasks[task]();
await tasks[task](site);
logger.setMessage(`Finished running ${task}`);
} catch (error) {
logger.setError(error);
Expand Down
2 changes: 1 addition & 1 deletion lib/utils/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const pathToTasks = path.join(__dirname, '../tasks');
const taskFiles = fs.readdirSync(pathToTasks, { encoding: 'utf8' });
const taskList = filterFileList(taskFiles, 'js');
taskList.forEach((task) => {
tasks[path.parse(task).name] = require(path.join(pathToTasks, task));
tasks[path.parse(task).name] = require(`${pathToTasks}/${task}`);
});

module.exports = tasks;
Loading

0 comments on commit 0d20d4d

Please sign in to comment.