Sort frontmatter according to the fields order in config file. Closes #215

This commit is contained in:
Cássio Zen 2017-01-19 12:09:18 -02:00
parent 01e11e9213
commit b64259cb5a
3 changed files with 20 additions and 5 deletions

View File

@ -202,7 +202,8 @@ class Backend {
entryToRaw(collection, entry) { entryToRaw(collection, entry) {
const format = resolveFormat(collection, entry); const format = resolveFormat(collection, entry);
return format && format.toFile(entry); const fieldsOrder = collection.get('fields').map(f => f.get('name')).toArray();
return format && format.toFile(entry, fieldsOrder);
} }
} }

View File

@ -10,7 +10,7 @@ export default class YAMLFrontmatter {
return obj; return obj;
} }
toFile(data) { toFile(data, sortedKeys) {
const meta = {}; const meta = {};
let body = ''; let body = '';
let content = ''; let content = '';
@ -23,7 +23,7 @@ export default class YAMLFrontmatter {
} }
content += '---\n'; content += '---\n';
content += new YAML().toFile(meta); content += new YAML().toFile(meta, sortedKeys);
content += '---\n\n'; content += '---\n\n';
content += body; content += body;
return content; return content;

View File

@ -35,12 +35,26 @@ const OutputSchema = new yaml.Schema({
explicit: yaml.DEFAULT_SAFE_SCHEMA.explicit, explicit: yaml.DEFAULT_SAFE_SCHEMA.explicit,
}); });
const sortKeys = (sortedKeys = []) => (a, b) => {
const idxA = sortedKeys.indexOf(a);
const idxB = sortedKeys.indexOf(b);
if (idxA === -1 || idxB === -1) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
if (idxA > idxB) return 1;
if (idxA < idxB) return -1;
return 0;
};
export default class YAML { export default class YAML {
fromFile(content) { fromFile(content) {
return yaml.safeLoad(content); return yaml.safeLoad(content);
} }
toFile(data) { toFile(data, sortedKeys = []) {
return yaml.safeDump(data, { schema: OutputSchema }); return yaml.safeDump(data, { schema: OutputSchema, sortKeys: sortKeys(sortedKeys) });
} }
} }