Skip to content

Instantly share code, notes, and snippets.

@alexcorvi
Last active March 13, 2017 21:59
Show Gist options
  • Save alexcorvi/d2f069f0810abe1e15d9419464c4ab7a to your computer and use it in GitHub Desktop.
Save alexcorvi/d2f069f0810abe1e15d9419464c4ab7a to your computer and use it in GitHub Desktop.
/// <reference path="../node_modules/@types/node/index.d.ts"/>
import * as fs from "fs";
import {join,resolve} from "path";
import marked = require("marked");
import handlebars = require("handlebars");
import mkdirp = require("mkdirp");
// retrieve a list of all the files in a given directory
function walkSync (dir:string, fileList?:string[]) {
const files = fs.readdirSync(dir).map((x)=>join(resolve(dir),x));
fileList = fileList || [];
files.forEach((file) => {
if(fs.statSync(file).isDirectory() && !/node_modules/.test(file)) fileList = walkSync(file, fileList);
else fileList.push(file);
});
return fileList;
};
// parse markdown files
function parseMd (filePath:string) {
const contents = fs.readFileSync(filePath,"utf8");
const attrsMatch = contents.match(/<!--((.|\n)+)-->/);
if(!attrsMatch) error(`file ${filePath} doesn't have any attributes`);
let match:string[] = [];
const attrs:{[key:string]:string} = {};
const attrsRe = /(let|const|var)\s+(\w+)((\s?)+)=((\s?)+)("|')((\w?)+)("|');?/gi;
while (match = attrsRe.exec(attrsMatch[0])) {
attrs[match[2]] = match[8];
}
const H1Matches = contents.match(/\s#\s?((.)+)\n/);
if(!H1Matches) error(`file ${filePath} doesn't have any H1 titles`);
attrs["title"] = H1Matches[0].replace(/^\s#/,"").trim();
attrs["body"] = marked(contents);
return attrs;
}
function error (msg:string) {
console.error(msg);
process.exit(1);
}
const allFiles = walkSync(process.cwd())
.filter(x=>x.endsWith(".md") || x.endsWith(".hbs"));
const handlebarsFiles = allFiles.filter(x=>x.endsWith(".hbs"));
const postsTemplate = fs.readFileSync(handlebarsFiles.find(x=>/post/i.test(x)),"utf8");
const homeTemplate = fs.readFileSync(handlebarsFiles.find(x=>/home/i.test(x)),"utf8");
const markdownFiles = allFiles.filter(x=>x.endsWith(".md")).map(parseMd);
const posts = markdownFiles.map(variables=>handlebars.compile(postsTemplate)(variables));
const home = handlebars.compile(homeTemplate)({"posts":markdownFiles});
fs.writeFileSync(join(process.cwd(),"index.html"),home);
mkdirp.sync(join(process.cwd(),"blog"))
posts.forEach((post,index)=>{
fs.writeFileSync(join(process.cwd(),"blog",markdownFiles[index]["permlink"])+".html",post);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment