|
| 1 | +// cSpell:ignore refcache |
| 2 | + |
| 3 | +const gulp = require('gulp'); |
| 4 | +const fs = require('fs').promises; |
| 5 | +const { taskArgs } = require('./_util'); |
| 6 | + |
| 7 | +const refcacheFile = 'static/refcache.json'; |
| 8 | +const n_default = 25; |
| 9 | + |
| 10 | +// The refcacheFile is a JSON map with each map entry of the form, e.g.: |
| 11 | +// |
| 12 | +// "https://cncf.io": { |
| 13 | +// "StatusCode": 206, |
| 14 | +// "LastSeen": "2023-06-29T13:38:47.996793-04:00" |
| 15 | +// }, |
| 16 | + |
| 17 | +// Prune the oldest <n> entries from refcacheFile in a way that avoids |
| 18 | +// reordering entries (makes diffs easier to manage). |
| 19 | +async function pruneTask() { |
| 20 | + const argv = taskArgs().options({ |
| 21 | + num: { |
| 22 | + alias: 'n', |
| 23 | + type: 'number', |
| 24 | + description: 'Number of oldest refcache entries to drop.', |
| 25 | + default: n_default, |
| 26 | + }, |
| 27 | + }).argv; |
| 28 | + |
| 29 | + const n = argv.num > 0 ? argv.num : n_default; |
| 30 | + |
| 31 | + if (argv.info) return; // Info was already displayed |
| 32 | + |
| 33 | + try { |
| 34 | + const json = await fs.readFile(refcacheFile, 'utf8'); |
| 35 | + const entries = JSON.parse(json); |
| 36 | + |
| 37 | + // Create a sorted array of URL keys and `LastSeen` dates |
| 38 | + const sortedUrlsAndDates = Object.keys(entries) |
| 39 | + .map((url) => [url, entries[url].LastSeen]) |
| 40 | + .sort((a, b) => new Date(a[1]) - new Date(b[1])); |
| 41 | + |
| 42 | + // Get oldest argv.num keys |
| 43 | + const oldestKeys = sortedUrlsAndDates.slice(0, n).map((item) => item[0]); |
| 44 | + |
| 45 | + // Remove oldest entries |
| 46 | + oldestKeys.forEach((key) => delete entries[key]); |
| 47 | + |
| 48 | + const prettyJson = JSON.stringify(entries, null, 2) + '\n'; |
| 49 | + await fs.writeFile(refcacheFile, prettyJson, 'utf8'); |
| 50 | + } catch (err) { |
| 51 | + console.error(err); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +pruneTask.description = `Prune the oldest '--num <n>' entries from ${refcacheFile} file (default ${n_default}).`; |
| 56 | + |
| 57 | +gulp.task('prune', pruneTask); |
0 commit comments