Skip to content

Commit

Permalink
Re-add ability to parse frontmatter like ---json.
Browse files Browse the repository at this point in the history
  • Loading branch information
tech4him1 committed Sep 14, 2017
1 parent fe50397 commit be05569
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/formats/frontmatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,42 @@ import matter from 'gray-matter';
import tomlEng from 'toml';
import YAML from './yaml';

const parsers = {
toml: tomlEng.parse.bind(tomlEng),
json: (input) => {
let JSONinput = input.trim();
// Fix JSON if leading and trailing brackets were trimmed.
if (JSONinput.substr(0, 1) !== '{') {
JSONinput = '{' + JSONinput;
}
if (JSONinput.substr(-1) !== '}') {
JSONinput = JSONinput + '}';
}
return matter.engines.json.parse(JSONinput);
},
}

function inferFrontmatterFormat(str) {
const firstLine = str.substr(0, str.indexOf('\n')).trim();
if ((firstLine.length > 3) && (firstLine.substr(0, 3) === "---")) {
// No need to infer, `gray-matter` will handle things like `---toml` for us.
return;
}
switch (firstLine) {
case "---":
return { language: "yaml", delimiters: "---" };
case "+++":
return { language: "toml", delimiters: "+++", engines: { toml: tomlEng.parse.bind(tomlEng) } };
return { language: "toml", delimiters: "+++" };
case "{":
return { language: "json", delimiters: ["{", "}"], engines: { json: ((input) => matter.engines.json.parse('{' + input + '}')) } };
return { language: "json", delimiters: ["{", "}"] };
default:
throw "Unrecgonized front-matter format.";
}
}

export default class Frontmatter {
fromFile(content) {
const result = matter(content, inferFrontmatterFormat(content));
const result = matter(content, { engines: parsers, ...inferFrontmatterFormat(content) });
const data = result.data;
data.body = result.content;
return data;
Expand Down

0 comments on commit be05569

Please sign in to comment.