2017-09-13 08:55:10 -06:00
|
|
|
import matter from 'gray-matter';
|
|
|
|
import tomlEng from 'toml';
|
2017-04-20 15:37:52 -04:00
|
|
|
import YAML from './yaml';
|
2016-02-25 20:40:35 -08:00
|
|
|
|
2017-09-12 20:51:40 -06:00
|
|
|
function inferFrontmatterFormat(str) {
|
|
|
|
const firstLine = str.substr(0, str.indexOf('\n')).trim();
|
|
|
|
switch (firstLine) {
|
|
|
|
case "---":
|
2017-09-13 08:55:10 -06:00
|
|
|
return { language: "yaml", delimiters: "---" };
|
2017-09-12 20:51:40 -06:00
|
|
|
case "+++":
|
2017-09-13 08:55:10 -06:00
|
|
|
return { language: "toml", delimiters: "+++", engines: { toml: tomlEng.parse.bind(tomlEng) } };
|
2017-09-12 20:51:40 -06:00
|
|
|
case "{":
|
2017-09-13 19:46:45 -06:00
|
|
|
return { language: "json", delimiters: ["{", "}"], engines: { json: ((input) => matter.engines.json.parse('{' + input + '}')) } };
|
2017-09-12 20:51:40 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-09 19:32:33 +01:00
|
|
|
export default class Frontmatter {
|
2016-02-25 20:40:35 -08:00
|
|
|
fromFile(content) {
|
2017-09-13 08:55:10 -06:00
|
|
|
const result = matter(content, inferFrontmatterFormat(content));
|
2017-04-07 22:40:30 +01:00
|
|
|
const data = result.data;
|
|
|
|
data.body = result.content;
|
|
|
|
return data;
|
2016-02-25 20:40:35 -08:00
|
|
|
}
|
|
|
|
|
2017-01-19 12:09:18 -02:00
|
|
|
toFile(data, sortedKeys) {
|
2016-02-25 20:40:35 -08:00
|
|
|
const meta = {};
|
|
|
|
let body = '';
|
2017-04-07 22:40:30 +01:00
|
|
|
Object.keys(data).forEach((key) => {
|
2016-02-25 20:40:35 -08:00
|
|
|
if (key === 'body') {
|
|
|
|
body = data[key];
|
|
|
|
} else {
|
|
|
|
meta[key] = data[key];
|
|
|
|
}
|
2017-04-07 22:40:30 +01:00
|
|
|
});
|
2017-04-20 15:37:52 -04:00
|
|
|
|
2017-04-07 22:40:30 +01:00
|
|
|
// always stringify to YAML
|
2017-04-20 15:37:52 -04:00
|
|
|
const parser = {
|
|
|
|
stringify(metadata) {
|
|
|
|
return new YAML().toFile(metadata, sortedKeys);
|
|
|
|
},
|
|
|
|
};
|
2017-09-13 08:55:10 -06:00
|
|
|
return matter.stringify(body, meta, { language: "yaml", delimiters: "---", engines: { yaml: parser } });
|
2016-02-25 20:40:35 -08:00
|
|
|
}
|
|
|
|
}
|