-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnavigator.js
94 lines (71 loc) · 2.3 KB
/
navigator.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
89
90
91
92
93
94
const fs = require("fs");
const path = require("path");
const NAV_MARK = ">:sailboat:";
const pathToDate = str => str && str.match(/(\d\d\d\d)\./)[1];
const makeBar = (date, prev, next) => {
const content = fs.readFileSync(date, "utf-8");
let lines = content.split("\n").map(line => line.replace("\r", ""));
const ibar = lines.findIndex(line => line.startsWith(NAV_MARK));
if (ibar >= 0) {
const urls = lines[ibar].match(/\([^()]+\)/g);
if (urls) {
const [defaultPrev, defaultNext] = urls.map(url => url.replace(/^\(|\)$/g, "")).concat([null]);
prev = prev || defaultPrev;
next = next || defaultNext;
}
}
const bar = [
`${NAV_MARK}  `,
prev && `[*${pathToDate(prev)}* **⇦**](${prev})`,
`  ${date.substring(0, 4)}/**${pathToDate(date)}**  `,
next && `[**⇨** *${pathToDate(next)}*](${next})`,
].filter(Boolean).join(" ");
if (ibar >= 0)
lines.splice(ibar, 1, bar);
else
lines.unshift("", bar, "");
const newContent = lines.join("\n");
fs.writeFileSync(date, newContent);
};
const relativeTo = (p1, p2) => path.relative(path.dirname(p1), p2);
const buildNavigator = (processAll = false) => {
const now = new Date();
const year = now.getFullYear().toString();
if (processAll) {
let lastDate = null;
for (let y = 2023; y <= year; ++y) {
const dates = fs.readdirSync(y.toString())
.filter(name => name.endsWith(".md"))
.sort();
for (const d of dates) {
const date = path.join(y.toString(), d);
if (lastDate) {
makeBar(date, relativeTo(date, lastDate), null);
makeBar(lastDate, null, relativeTo(lastDate, date));
}
lastDate = date;
}
}
}
else {
const dates = fs.readdirSync(year)
.filter(name => name.endsWith(".md"))
.sort();
const lastDate = path.join(year, dates.pop());
let date2 = dates.pop();
let yestodayYear = year;
if (!date2) { // crossing years
yestodayYear = (now.getFullYear() - 1).toString();
const dates2 = fs.readdirSync(yestodayYear)
.filter(name => name.endsWith(".md"))
.sort();
date2 = dates2.pop();
}
const lastDate2 = date2 && path.join(yestodayYear, date2);
if (lastDate && lastDate2) {
makeBar(lastDate, relativeTo(lastDate, lastDate2), null);
makeBar(lastDate2, null, relativeTo(lastDate2, lastDate));
}
}
};
module.exports = {buildNavigator};