forked from nuxt/nuxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocking.js
More file actions
102 lines (82 loc) · 2.61 KB
/
locking.js
File metadata and controls
102 lines (82 loc) · 2.61 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import path from 'path'
import consola from 'consola'
import hash from 'hash-sum'
import fs from 'fs-extra'
import properlock from 'proper-lockfile'
import onExit from 'signal-exit'
export const lockPaths = new Set()
export const defaultLockOptions = {
stale: 30000,
onCompromised: err => consola.warn(err)
}
export function getLockOptions (options) {
return Object.assign({}, defaultLockOptions, options)
}
export function createLockPath ({ id = 'nuxt', dir, root }) {
const sum = hash(`${root}-${dir}`)
return path.resolve(root, 'node_modules/.cache/nuxt', `${id}-lock-${sum}`)
}
export async function getLockPath (config) {
const lockPath = createLockPath(config)
// the lock is created for the lockPath as ${lockPath}.lock
// so the (temporary) lockPath needs to exist
await fs.ensureDir(lockPath)
return lockPath
}
export async function lock ({ id, dir, root, options }) {
const lockPath = await getLockPath({ id, dir, root })
try {
const locked = await properlock.check(lockPath)
if (locked) {
consola.fatal(`A lock with id '${id}' already exists on ${dir}`)
}
} catch (e) {
consola.debug(`Check for an existing lock with id '${id}' on ${dir} failed`, e)
}
let lockWasCompromised = false
let release
try {
options = getLockOptions(options)
const onCompromised = options.onCompromised
options.onCompromised = (err) => {
onCompromised(err)
lockWasCompromised = true
}
release = await properlock.lock(lockPath, options)
} catch (e) {}
if (!release) {
consola.warn(`Unable to get a lock with id '${id}' on ${dir} (but will continue)`)
return false
}
if (!lockPaths.size) {
// make sure to always cleanup our temporary lockPaths
onExit(() => {
for (const lockPath of lockPaths) {
fs.removeSync(lockPath)
}
})
}
lockPaths.add(lockPath)
return async function lockRelease () {
try {
await fs.remove(lockPath)
lockPaths.delete(lockPath)
// release as last so the lockPath is still removed
// when it fails on a compromised lock
await release()
} catch (e) {
if (!lockWasCompromised || !e.message.includes('already released')) {
consola.debug(e)
return
}
// proper-lockfile doesnt remove lockDir when lock is compromised
// removing it here could cause the 'other' process to throw an error
// as well, but in our case its much more likely the lock was
// compromised due to mtime update timeouts
const lockDir = `${lockPath}.lock`
if (await fs.exists(lockDir)) {
await fs.remove(lockDir)
}
}
}
}