Skip to content

Commit

Permalink
Don't error on ENOSYS, EINVAL or EPERM when changing ownership …
Browse files Browse the repository at this point in the history
…or mode

Fixes #49.

EDIT(isaacs): Rebased latest, added tests to get back to 100% coverage.

PR-URL: #55
Credit: @kevva
Close: #55
Reviewed-by: @isaacs
  • Loading branch information
kevva authored and isaacs committed Feb 24, 2020
1 parent e322288 commit 2159ad2
Show file tree
Hide file tree
Showing 2 changed files with 243 additions and 114 deletions.
52 changes: 48 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,22 @@ function serializeActiveFile (absoluteName) {
})
}

// https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342
function isChownErrOk (err) {
if (err.code === 'ENOSYS') {
return true
}

const nonroot = !process.getuid || process.getuid() !== 0
if (nonroot) {
if (err.code === 'EINVAL' || err.code === 'EPERM') {
return true
}
}

return false
}

async function writeFileAsync (filename, data, options = {}) {
if (typeof options === 'string') {
options = { encoding: options }
Expand Down Expand Up @@ -107,11 +123,19 @@ async function writeFileAsync (filename, data, options = {}) {
fd = null

if (options.chown) {
await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid)
await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => {
if (!isChownErrOk(err)) {
throw err
}
})
}

if (options.mode) {
await promisify(fs.chmod)(tmpfile, options.mode)
await promisify(fs.chmod)(tmpfile, options.mode).catch(err => {
if (!isChownErrOk(err)) {
throw err
}
})
}

await promisify(fs.rename)(tmpfile, truename)
Expand Down Expand Up @@ -193,10 +217,30 @@ function writeFileSync (filename, data, options) {
if (options.fsync !== false) {
fs.fsyncSync(fd)
}

fs.closeSync(fd)
fd = null
if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
if (options.mode) fs.chmodSync(tmpfile, options.mode)

if (options.chown) {
try {
fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
} catch (err) {
if (!isChownErrOk(err)) {
throw err
}
}
}

if (options.mode) {
try {
fs.chmodSync(tmpfile, options.mode)
} catch (err) {
if (!isChownErrOk(err)) {
throw err
}
}
}

fs.renameSync(tmpfile, filename)
threw = false
} finally {
Expand Down
Loading

0 comments on commit 2159ad2

Please sign in to comment.