2017-04-07 22:40:30 +01:00
|
|
|
import preliminaries from 'preliminaries';
|
|
|
|
import yamlParser from 'preliminaries-parser-yaml';
|
|
|
|
import tomlParser from 'preliminaries-parser-toml';
|
2017-04-20 15:37:52 -04:00
|
|
|
import YAML from './yaml';
|
2016-02-25 20:40:35 -08:00
|
|
|
|
2017-04-07 22:40:30 +01:00
|
|
|
// Automatically register parsers
|
|
|
|
preliminaries(true);
|
|
|
|
yamlParser(true);
|
|
|
|
tomlParser(true);
|
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 "---":
|
|
|
|
return { lang: "yaml", delims: "---" };
|
|
|
|
case "+++":
|
|
|
|
return { lang: "toml", delims: "+++" };
|
|
|
|
case "{":
|
|
|
|
return { lang: "json", delims: ["{", "}"] };
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-09 19:32:33 +01:00
|
|
|
export default class Frontmatter {
|
2016-02-25 20:40:35 -08:00
|
|
|
fromFile(content) {
|
2017-09-12 20:51:40 -06:00
|
|
|
const result = preliminaries.parse(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);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
return preliminaries.stringify(body, meta, { lang: "yaml", delims: "---", parser });
|
2016-02-25 20:40:35 -08:00
|
|
|
}
|
|
|
|
}
|