1 const fs = require('fs/promises')
2
3 /** cache npm cli version shas to NOT pull down changes we already have */
4 class CacheVersionSha {
5 shouldVoid = false
6
7 constructor(cache, path) {
8 this.cache = cache
9 this.path = path
10 }
11
12 static async load(path) {
13 return new CacheVersionSha(JSON.parse(await fs.readFile(path, 'utf-8')), path)
14 }
15
16 get keys() {
17 return Object.keys(this.cache)
18 }
19
20 voidOnNewKey(keys) {
21 if (keys.length !== this.keys.length || !keys.every(key => this.keys.includes(key))) {
22 this.shouldVoid = true
23 }
24 }
25
26 async save() {
27 const sortedCache = {}
28 Object.keys(this.cache)
29 .sort((a, b) => {
30 const numA = parseInt(a.replace('v', ''), 10)
31 const numB = parseInt(b.replace('v', ''), 10)
32 return numA - numB
33 })
34 .forEach(key => {
35 sortedCache[key] = this.cache[key]
36 })
37 this.cache = sortedCache
38 await fs.writeFile(this.path, JSON.stringify(this.cache, null, 2))
39 return this
40 }
41
42 set(id, sha) {
43 this.cache[id] = sha
44 return this
45 }
46
47 same(id, value) {
48 if (this.shouldVoid) return false
49 return this.cache[id] === value
50 }
51 }
52
53 module.exports = {
54 CacheVersionSha,
55 }