forked from newrelic/docs-website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddFreshnessFrontmatter.mjs
More file actions
83 lines (70 loc) · 2.45 KB
/
Copy pathaddFreshnessFrontmatter.mjs
File metadata and controls
83 lines (70 loc) · 2.45 KB
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
#! /usr/bin/env node
import { execSync } from 'child_process';
import { glob } from 'glob10';
import { writeFile, readFileSync } from 'fs';
import cliProgress from 'cli-progress';
console.log('Reading git history...');
console.time('Freshness field added');
const allDocs = await glob('src/content/docs/**/*.mdx', {
ignore: [
'**/index.mdx',
'src/content/docs/release-notes/**/*.mdx',
'src/content/docs/style-guide/**/*.mdx',
'src/content/whats-new/**/*.mdx',
'src/content/docs/security/new-relic-security/security-bulletins/**/*.mdx',
],
});
/**
* Helper function that checks if a date is outside the freshness threshold of 180 days.
* @param {Date} date
* @returns {boolean} if date is stale
*/
const isDocStale = (date) => {
const days = 180;
const today = Date.now();
const staleDate = new Date(today - days * 24 * 60 * 60 * 1000);
return staleDate > date;
};
const freshnessFrontmatterKey = 'freshnessValidatedDate: ';
/**
* Reads an array of docs and writes a new freshnessValidatedDate field to frontmatter.
* Uses the last git rename date on that file to set the value.
* @param {Array} docs - Array of docs file paths
*/
const addFreshnessFrontmatter = (allDocs) => {
allDocs.map(async (doc, i) => {
// get rename date of file to get a 'created' date
const gitLogCreatedDate = execSync(
`git log --follow --pretty=format:%aI ${doc} | tail -1`
).toString();
const created = new Date(gitLogCreatedDate);
const fileData = readFileSync(doc, 'utf-8');
// split doc into sections using the frontmatter delimiter
const content = fileData.split('---');
// modify the frontmatter adding the freshness field if it does not have it already
if (!content[1]?.includes(freshnessFrontmatterKey)) {
content[1] = `${content[1]}${freshnessFrontmatterKey}${
isDocStale(created) ? 'never' : created.toISOString().slice(0, 10)
}\n`;
}
// put the doc back together
const newContent = content.join('---');
writeFile(doc, newContent, 'utf-8', function (err) {
if (err) {
console.log(
'\n',
'Some error occurred - file either not saved or corrupted file saved.'
);
}
});
progressBar.update(i + 1);
});
progressBar.stop();
console.timeEnd('Freshness field added');
};
const progressBar = new cliProgress.SingleBar(
{},
cliProgress.Presets.shades_classic
);
progressBar.start(allDocs.length, 0);
addFreshnessFrontmatter(allDocs);