1 | 'use strict'
|
---|
2 |
|
---|
3 | const fs = require('fs')
|
---|
4 | const util = require('util')
|
---|
5 | const chmod = util.promisify(fs.chmod)
|
---|
6 | const unlink = util.promisify(fs.unlink)
|
---|
7 | const stat = util.promisify(fs.stat)
|
---|
8 | const move = require('@npmcli/move-file')
|
---|
9 | const pinflight = require('promise-inflight')
|
---|
10 |
|
---|
11 | module.exports = moveFile
|
---|
12 |
|
---|
13 | function moveFile (src, dest) {
|
---|
14 | const isWindows = global.__CACACHE_TEST_FAKE_WINDOWS__ ||
|
---|
15 | process.platform === 'win32'
|
---|
16 |
|
---|
17 | // This isn't quite an fs.rename -- the assumption is that
|
---|
18 | // if `dest` already exists, and we get certain errors while
|
---|
19 | // trying to move it, we should just not bother.
|
---|
20 | //
|
---|
21 | // In the case of cache corruption, users will receive an
|
---|
22 | // EINTEGRITY error elsewhere, and can remove the offending
|
---|
23 | // content their own way.
|
---|
24 | //
|
---|
25 | // Note that, as the name suggests, this strictly only supports file moves.
|
---|
26 | return new Promise((resolve, reject) => {
|
---|
27 | fs.link(src, dest, (err) => {
|
---|
28 | if (err) {
|
---|
29 | if (isWindows && err.code === 'EPERM') {
|
---|
30 | // XXX This is a really weird way to handle this situation, as it
|
---|
31 | // results in the src file being deleted even though the dest
|
---|
32 | // might not exist. Since we pretty much always write files to
|
---|
33 | // deterministic locations based on content hash, this is likely
|
---|
34 | // ok (or at worst, just ends in a future cache miss). But it would
|
---|
35 | // be worth investigating at some time in the future if this is
|
---|
36 | // really what we want to do here.
|
---|
37 | return resolve()
|
---|
38 | } else if (err.code === 'EEXIST' || err.code === 'EBUSY') {
|
---|
39 | // file already exists, so whatever
|
---|
40 | return resolve()
|
---|
41 | } else
|
---|
42 | return reject(err)
|
---|
43 | } else
|
---|
44 | return resolve()
|
---|
45 | })
|
---|
46 | })
|
---|
47 | .then(() => {
|
---|
48 | // content should never change for any reason, so make it read-only
|
---|
49 | return Promise.all([
|
---|
50 | unlink(src),
|
---|
51 | !isWindows && chmod(dest, '0444'),
|
---|
52 | ])
|
---|
53 | })
|
---|
54 | .catch(() => {
|
---|
55 | return pinflight('cacache-move-file:' + dest, () => {
|
---|
56 | return stat(dest).catch((err) => {
|
---|
57 | if (err.code !== 'ENOENT') {
|
---|
58 | // Something else is wrong here. Bail bail bail
|
---|
59 | throw err
|
---|
60 | }
|
---|
61 | // file doesn't already exist! let's try a rename -> copy fallback
|
---|
62 | // only delete if it successfully copies
|
---|
63 | return move(src, dest)
|
---|
64 | })
|
---|
65 | })
|
---|
66 | })
|
---|
67 | }
|
---|