This repository was archived by the owner on Aug 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathreorder.js
88 lines (74 loc) · 2.53 KB
/
reorder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const MATCH_FILES = "_posts/*.md";
const START_DATE = new Date("2000-01-01T23:00:00.001Z");
const DATE_MONTHS_INTERVAL = 1;
const fs = require("fs");
const matter = require("gray-matter");
const glob = require("glob");
const { promisify } = require("util");
const yaml = require("js-yaml");
// promisify some fs functions
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);
const readdirAsync = promisify(fs.readdir);
const globAsync = promisify(glob);
const matterOptions = {
engines: {
yaml: {
parse(str) {
return yaml.safeLoad(str);
},
stringify(data) {
// not nice code, against YAML spec
let date = data.date,
title = data.title;
delete data.date;
delete data.title;
let rest = yaml.safeDump(data, {
noCompatMode: true
});
return `title: ${title}\ndate: ${date}\n${rest}`;
}
}
}
};
/**
* Reads a markdown file from the provided path and parses the front matter.
* @param {String} path
*/
async function readAndParseFile(path) {
let data = await readFileAsync(path, "utf8")
return matter(data, matterOptions);
}
/**
* Writes modified files back to disk;
* @param {Object} parsedFile
*/
async function writeFile(parsedFile) {
await writeFileAsync(parsedFile.originalFilename, matter.stringify(parsedFile.content, parsedFile.data, matterOptions));
}
/**
* Formats the date to YYYY-MM-DD
* @param {Date} date
*/
function formatDate(date) {
return date.toISOString().slice(0, 10); // this is good code
}
/**
* Reads, reorders and writes all files matched by MATCH_FILES.
*/
async function reorderFiles() {
let filenames = await globAsync(MATCH_FILES); // match all filenames
let parsedFiles = await Promise.all(filenames.map(readAndParseFile)); // read all files in paralell
parsedFiles.forEach((f, i) => {
f.originalFilename = filenames[i];
});
parsedFiles.sort((a, b) => a.data.date - b.data.date); // sort all files by date
let nextDate = new Date(START_DATE.getTime());
parsedFiles.forEach(parsedFile => {
parsedFile.data.date = formatDate(new Date(nextDate.getTime())); // copy next date and assign it
nextDate.setMonth(nextDate.getMonth() + DATE_MONTHS_INTERVAL);
});
parsedFiles.forEach(writeFile);
console.log("Reordered", parsedFiles.length, "files.")
}
reorderFiles().catch(console.error);