-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
cleanupCache.ts
42 lines (38 loc) · 1.14 KB
/
cleanupCache.ts
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
import Debug from '@prisma/debug'
import fs from 'fs'
import pMap from 'p-map'
import path from 'path'
import rimraf from 'rimraf'
import { promisify } from 'util'
import { getRootCacheDir } from './utils'
const debug = Debug('cleanupCache')
const del = promisify(rimraf)
const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)
export async function cleanupCache(n = 5): Promise<void> {
try {
const rootCacheDir = await getRootCacheDir()
if (!rootCacheDir) {
debug('no rootCacheDir found')
return
}
const channel = 'master'
const cacheDir = path.join(rootCacheDir, channel)
const dirs = await readdir(cacheDir)
const dirsWithMeta = await Promise.all(
dirs.map(async (dirName) => {
const dir = path.join(cacheDir, dirName)
const statResult = await stat(dir)
return {
dir,
created: statResult.birthtime,
}
}),
)
dirsWithMeta.sort((a, b) => (a.created < b.created ? 1 : -1))
const dirsToRemove = dirsWithMeta.slice(n)
await pMap(dirsToRemove, (dir) => del(dir.dir), { concurrency: 20 })
} catch (e) {
// fail silently
}
}