1 | require('./utils/polyfills')
|
2 |
|
3 | const pathExists = require('path-exists')
|
4 | const del = require('del')
|
5 |
|
6 | const { parsePath } = require('./path')
|
7 | const { getManifestInfo, writeManifest, removeManifest, isExpired } = require('./manifest')
|
8 | const { moveCacheFile } = require('./fs')
|
9 | const { getCacheDir } = require('./dir')
|
10 | const { list } = require('./list')
|
11 |
|
12 |
|
13 | const saveOne = async function(path, { move = DEFAULT_MOVE, ttl = DEFAULT_TTL, digests = [], cacheDir } = {}) {
|
14 | const { srcPath, cachePath } = await parsePath(path, cacheDir)
|
15 |
|
16 | if (!(await pathExists(srcPath))) {
|
17 | return false
|
18 | }
|
19 |
|
20 | const { manifestInfo, identical } = await getManifestInfo({ cachePath, move, ttl, digests })
|
21 | if (identical) {
|
22 | return false
|
23 | }
|
24 |
|
25 | await del(cachePath, { force: true })
|
26 | await moveCacheFile(srcPath, cachePath, move)
|
27 | await writeManifest(manifestInfo)
|
28 |
|
29 | return true
|
30 | }
|
31 |
|
32 |
|
33 | const restoreOne = async function(path, { move = DEFAULT_MOVE, cacheDir } = {}) {
|
34 | const { srcPath, cachePath } = await parsePath(path, cacheDir)
|
35 |
|
36 | if (!(await pathExists(cachePath))) {
|
37 | return false
|
38 | }
|
39 |
|
40 | if (await isExpired(cachePath)) {
|
41 | return false
|
42 | }
|
43 |
|
44 | await del(srcPath, { force: true })
|
45 | await moveCacheFile(cachePath, srcPath, move)
|
46 |
|
47 | return true
|
48 | }
|
49 |
|
50 |
|
51 | const removeOne = async function(path, { cacheDir } = {}) {
|
52 | const { cachePath } = await parsePath(path, cacheDir)
|
53 |
|
54 | if (!(await pathExists(cachePath))) {
|
55 | return false
|
56 | }
|
57 |
|
58 | await del(cachePath, { force: true })
|
59 | await removeManifest(cachePath)
|
60 |
|
61 | return true
|
62 | }
|
63 |
|
64 |
|
65 | const hasOne = async function(path, { cacheDir } = {}) {
|
66 | const { cachePath } = await parsePath(path, cacheDir)
|
67 |
|
68 | return (await pathExists(cachePath)) && !(await isExpired(cachePath))
|
69 | }
|
70 |
|
71 | const DEFAULT_MOVE = false
|
72 | const DEFAULT_TTL = undefined
|
73 |
|
74 |
|
75 |
|
76 | const allowMany = async function(func, paths, ...args) {
|
77 | if (!Array.isArray(paths)) {
|
78 | return func(paths, ...args)
|
79 | }
|
80 |
|
81 | const results = await Promise.all(paths.map(path => func(path, ...args)))
|
82 | return results.some(Boolean)
|
83 | }
|
84 |
|
85 | const save = allowMany.bind(null, saveOne)
|
86 | const restore = allowMany.bind(null, restoreOne)
|
87 | const remove = allowMany.bind(null, removeOne)
|
88 | const has = allowMany.bind(null, hasOne)
|
89 |
|
90 | module.exports = { save, restore, remove, has, list, getCacheDir }
|