-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
build.js
87 lines (71 loc) · 2.06 KB
/
build.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
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const { titleCase } = require('title-case');
const linksUrl = 'https://protect.earth/links.json';
const readmeFile = path.resolve(`./README.md`);
const replaceBetween = (origin, startIndex, endIndex, insertion) => {
return (
origin.substring(0, startIndex) + insertion + origin.substring(endIndex)
);
};
const formatAsMarkdown = links => {
const categorizedData = {};
links.forEach(link => {
link.categories.forEach(catKey => {
if (categorizedData[catKey] === undefined) {
categorizedData[catKey] = {
title: titleCase(catKey).replace('-', ' '),
key: catKey,
links: [],
};
}
categorizedData[catKey].links.push(link);
});
});
const sortedKeys = Object.keys(categorizedData).sort();
let outputArr = [];
// Output Table of Contents
outputArr = outputArr.concat(
sortedKeys.map(category => {
const { title, key } = categorizedData[category];
return `- [${title}](#${key})`;
})
);
// Add the links for each category
outputArr = outputArr.concat(
sortedKeys.flatMap(category => {
const { title, links } = categorizedData[category];
return (
[`## ${title}\n`] +
links
.map(link => {
const { title, url, description } = link;
return `- [${title}](${url}) - ${description}`;
})
.sort()
.join('\n')
);
})
);
return outputArr.join('\n');
};
const startCursor = '<!-- links:start -->';
const endCursor = '<!-- links:end -->';
const str = fs.readFileSync(readmeFile, 'utf8');
fetch(linksUrl).then(function(response) {
response.json().then(links => {
console.log(`Found ${links.length} links.`);
const markdownLines = formatAsMarkdown(links);
fs.writeFileSync(
readmeFile,
replaceBetween(
str,
str.indexOf(startCursor) + startCursor.length + 1,
str.indexOf(endCursor),
markdownLines
),
'utf8'
);
});
})