pax_global_header 0000666 0000000 0000000 00000000064 14276747703 0014533 g ustar 00root root 0000000 0000000 52 comment=9688d63c4013595dd6a2b2128273b67544be3ca4
write-file-atomic-4.0.2/ 0000775 0000000 0000000 00000000000 14276747703 0015057 5 ustar 00root root 0000000 0000000 write-file-atomic-4.0.2/.commitlintrc.js 0000664 0000000 0000000 00000000553 14276747703 0020202 0 ustar 00root root 0000000 0000000 /* This file is automatically added by @npmcli/template-oss. Do not edit. */
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'deps', 'chore']],
'header-max-length': [2, 'always', 80],
'subject-case': [0, 'always', ['lower-case', 'sentence-case', 'start-case']],
},
}
write-file-atomic-4.0.2/.eslintrc.js 0000664 0000000 0000000 00000000545 14276747703 0017322 0 ustar 00root root 0000000 0000000 /* This file is automatically added by @npmcli/template-oss. Do not edit. */
'use strict'
const { readdirSync: readdir } = require('fs')
const localConfigs = readdir(__dirname)
.filter((file) => file.startsWith('.eslintrc.local.'))
.map((file) => `./${file}`)
module.exports = {
root: true,
extends: [
'@npmcli',
...localConfigs,
],
}
write-file-atomic-4.0.2/.github/ 0000775 0000000 0000000 00000000000 14276747703 0016417 5 ustar 00root root 0000000 0000000 write-file-atomic-4.0.2/.github/CODEOWNERS 0000664 0000000 0000000 00000000132 14276747703 0020006 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
* @npm/cli-team
write-file-atomic-4.0.2/.github/ISSUE_TEMPLATE/ 0000775 0000000 0000000 00000000000 14276747703 0020602 5 ustar 00root root 0000000 0000000 write-file-atomic-4.0.2/.github/ISSUE_TEMPLATE/bug.yml 0000664 0000000 0000000 00000002655 14276747703 0022112 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Bug
description: File a bug/issue
title: "[BUG]
"
labels: [ Bug, Needs Triage ]
body:
- type: checkboxes
attributes:
label: Is there an existing issue for this?
description: Please [search here](./issues) to see if an issue already exists for your problem.
options:
- label: I have searched the existing issues
required: true
- type: textarea
attributes:
label: Current Behavior
description: A clear & concise description of what you're experiencing.
validations:
required: false
- type: textarea
attributes:
label: Expected Behavior
description: A clear & concise description of what you expected to happen.
validations:
required: false
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
value: |
1. In this environment...
2. With this config...
3. Run '...'
4. See error...
validations:
required: false
- type: textarea
attributes:
label: Environment
description: |
examples:
- **npm**: 7.6.3
- **Node**: 13.14.0
- **OS**: Ubuntu 20.04
- **platform**: Macbook Pro
value: |
- npm:
- Node:
- OS:
- platform:
validations:
required: false
write-file-atomic-4.0.2/.github/ISSUE_TEMPLATE/config.yml 0000664 0000000 0000000 00000000145 14276747703 0022572 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
blank_issues_enabled: true
write-file-atomic-4.0.2/.github/dependabot.yml 0000664 0000000 0000000 00000000565 14276747703 0021255 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
allow:
- dependency-type: direct
versioning-strategy: increase-if-necessary
commit-message:
prefix: deps
prefix-development: chore
labels:
- "Dependencies"
write-file-atomic-4.0.2/.github/settings.yml 0000664 0000000 0000000 00000000055 14276747703 0021002 0 ustar 00root root 0000000 0000000 ---
_extends: '.github:npm-cli/settings.yml'
write-file-atomic-4.0.2/.github/workflows/ 0000775 0000000 0000000 00000000000 14276747703 0020454 5 ustar 00root root 0000000 0000000 write-file-atomic-4.0.2/.github/workflows/audit.yml 0000664 0000000 0000000 00000001370 14276747703 0022306 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Audit
on:
workflow_dispatch:
schedule:
# "At 01:00 on Monday" https://crontab.guru/#0_1_*_*_1
- cron: "0 1 * * 1"
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup git user
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- uses: actions/setup-node@v3
with:
node-version: 16.x
- name: Update npm to latest
run: npm i --prefer-online --no-fund --no-audit -g npm@latest
- run: npm -v
- run: npm i --ignore-scripts --no-audit --no-fund --package-lock
- run: npm audit
write-file-atomic-4.0.2/.github/workflows/ci.yml 0000664 0000000 0000000 00000005026 14276747703 0021575 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: CI
on:
workflow_dispatch:
pull_request:
branches:
- '*'
push:
branches:
- main
- latest
schedule:
# "At 02:00 on Monday" https://crontab.guru/#0_2_*_*_1
- cron: "0 2 * * 1"
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup git user
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- uses: actions/setup-node@v3
with:
node-version: 16.x
- name: Update npm to latest
run: npm i --prefer-online --no-fund --no-audit -g npm@latest
- run: npm -v
- run: npm i --ignore-scripts --no-audit --no-fund
- run: npm run lint
test:
strategy:
fail-fast: false
matrix:
node-version:
- 12.13.0
- 12.x
- 14.15.0
- 14.x
- 16.0.0
- 16.x
platform:
- os: ubuntu-latest
shell: bash
- os: macos-latest
shell: bash
runs-on: ${{ matrix.platform.os }}
defaults:
run:
shell: ${{ matrix.platform.shell }}
steps:
- uses: actions/checkout@v3
- name: Setup git user
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Update to workable npm (windows)
# node 12 and 14 ship with npm@6, which is known to fail when updating itself in windows
if: matrix.platform.os == 'windows-latest' && (startsWith(matrix.node-version, '12.') || startsWith(matrix.node-version, '14.'))
run: |
curl -sO https://registry.npmjs.org/npm/-/npm-7.5.4.tgz
tar xf npm-7.5.4.tgz
cd package
node lib/npm.js install --no-fund --no-audit -g ..\npm-7.5.4.tgz
cd ..
rmdir /s /q package
- name: Update npm to 7
# If we do test on npm 10 it needs npm7
if: startsWith(matrix.node-version, '10.')
run: npm i --prefer-online --no-fund --no-audit -g npm@7
- name: Update npm to latest
if: ${{ !startsWith(matrix.node-version, '10.') }}
run: npm i --prefer-online --no-fund --no-audit -g npm@latest
- run: npm -v
- run: npm i --ignore-scripts --no-audit --no-fund
- run: npm test --ignore-scripts
write-file-atomic-4.0.2/.github/workflows/codeql-analysis.yml 0000664 0000000 0000000 00000002001 14276747703 0024260 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: "CodeQL"
on:
push:
branches:
- main
- latest
pull_request:
# The branches below must be a subset of the branches above
branches:
- main
- latest
schedule:
# "At 03:00 on Monday" https://crontab.guru/#0_3_*_*_1
- cron: "0 3 * * 1"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ javascript ]
steps:
- uses: actions/checkout@v3
- name: Setup git user
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
write-file-atomic-4.0.2/.github/workflows/post-dependabot.yml 0000664 0000000 0000000 00000002641 14276747703 0024272 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Post Dependabot Actions
on: pull_request
# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: write
jobs:
template-oss-apply:
runs-on: ubuntu-latest
if: github.actor == 'dependabot[bot]'
steps:
- uses: actions/checkout@v3
- name: Setup git user
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- uses: actions/setup-node@v3
with:
node-version: 16.x
- name: Update npm to latest
run: npm i --prefer-online --no-fund --no-audit -g npm@latest
- run: npm -v
- name: Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@v1.1.1
with:
github-token: "${{ secrets.GITHUB_TOKEN }}"
- name: npm install and commit
if: contains(steps.metadata.outputs.dependency-names, '@npmcli/template-oss')
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh pr checkout ${{ github.event.pull_request.number }}
npm install --ignore-scripts --no-audit --no-fund
npm run template-oss-apply
git add .
git commit -am "chore: postinstall for dependabot template-oss PR"
git push
npm run lint
write-file-atomic-4.0.2/.github/workflows/pull-request.yml 0000664 0000000 0000000 00000002143 14276747703 0023641 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Pull Request Linting
on:
pull_request:
types:
- opened
- reopened
- edited
- synchronize
jobs:
check:
name: Check PR Title or Commits
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup git user
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- uses: actions/setup-node@v3
with:
node-version: 16.x
- name: Update npm to latest
run: npm i --prefer-online --no-fund --no-audit -g npm@latest
- run: npm -v
- name: Install deps
run: npm i -D @commitlint/cli @commitlint/config-conventional
- name: Check commits OR PR title
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
npx --offline commitlint -V --from origin/main --to ${{ github.event.pull_request.head.sha }} \
|| echo $PR_TITLE | npx --offline commitlint -V
write-file-atomic-4.0.2/.github/workflows/release-please.yml 0000664 0000000 0000000 00000001314 14276747703 0024065 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Release Please
on:
push:
branches:
- main
- latest
jobs:
release-please:
runs-on: ubuntu-latest
steps:
- uses: google-github-actions/release-please-action@v3
id: release
with:
release-type: node
changelog-types: >
[
{"type":"feat","section":"Features","hidden":false},
{"type":"fix","section":"Bug Fixes","hidden":false},
{"type":"docs","section":"Documentation","hidden":false},
{"type":"deps","section":"Dependencies","hidden":false},
{"type":"chore","hidden":true}
]
write-file-atomic-4.0.2/.gitignore 0000664 0000000 0000000 00000000570 14276747703 0017051 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
# ignore everything in the root
/*
# keep these
!/.eslintrc.local.*
!**/.gitignore
!/docs/
!/tap-snapshots/
!/test/
!/map.js
!/scripts/
!/README*
!/LICENSE*
!/CHANGELOG*
!/.commitlintrc.js
!/.eslintrc.js
!/.github/
!/.gitignore
!/.npmrc
!/CODE_OF_CONDUCT.md
!/SECURITY.md
!/bin/
!/lib/
!/package.json
write-file-atomic-4.0.2/.npmrc 0000664 0000000 0000000 00000000135 14276747703 0016176 0 ustar 00root root 0000000 0000000 ; This file is automatically added by @npmcli/template-oss. Do not edit.
package-lock=false
write-file-atomic-4.0.2/CHANGELOG.md 0000664 0000000 0000000 00000003215 14276747703 0016671 0 ustar 00root root 0000000 0000000 # Changelog
## [4.0.2](https://github.com/npm/write-file-atomic/compare/v4.0.1...v4.0.2) (2022-08-16)
### Bug Fixes
* linting ([#111](https://github.com/npm/write-file-atomic/issues/111)) ([c8ef004](https://github.com/npm/write-file-atomic/commit/c8ef00406ff21056adae06a9b8186d37031d8a95))
### [4.0.1](https://www.github.com/npm/write-file-atomic/compare/v4.0.0...v4.0.1) (2022-02-09)
### Bug Fixes
* remove dupl check for typed arrays ([#96](https://www.github.com/npm/write-file-atomic/issues/96)) ([81a296d](https://www.github.com/npm/write-file-atomic/commit/81a296df8cbed750bc8b41d2b0d725a6a16361f7))
* remove is-typedarray and typedarray-to-buffer ([625526e](https://www.github.com/npm/write-file-atomic/commit/625526e1f190d2599a267839e995b768cf3f69b6))
### Dependencies
* update signal-exit requirement from ^3.0.2 to ^3.0.7 ([0b3ffdb](https://www.github.com/npm/write-file-atomic/commit/0b3ffdb4534b254ac5de8acf02e5b4591e2d92b4))
## [4.0.0](https://www.github.com/npm/write-file-atomic/compare/v3.0.3...v4.0.0) (2022-01-18)
### ⚠ BREAKING CHANGES
* This drops support for node10 and non-LTS versions of node12 and node14
### Bug Fixes
* move to template-oss ([266833d](https://www.github.com/npm/write-file-atomic/commit/266833d868b7626227d25dfbfa694798770bc811))
### dependencies
* typedarray-to-buffer@4.0.0 ([f36ff4f](https://www.github.com/npm/write-file-atomic/commit/f36ff4f5bc21178885f53768268fd9d8b0ba0729))
### Documentation
* **readme:** clean up API/usage syntax ([#90](https://www.github.com/npm/write-file-atomic/issues/90)) ([22c6990](https://www.github.com/npm/write-file-atomic/commit/22c6990a4ce08ddb3cd7e18837997c0acd81daac))
write-file-atomic-4.0.2/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000000507 14276747703 0017660 0 ustar 00root root 0000000 0000000
All interactions in this repo are covered by the [npm Code of
Conduct](https://docs.npmjs.com/policies/conduct)
The npm cli team may, at its own discretion, moderate, remove, or edit
any interactions such as pull requests, issues, and comments.
write-file-atomic-4.0.2/LICENSE.md 0000664 0000000 0000000 00000001336 14276747703 0016466 0 ustar 00root root 0000000 0000000 Copyright (c) 2015, Rebecca Turner
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
write-file-atomic-4.0.2/README.md 0000664 0000000 0000000 00000006355 14276747703 0016347 0 ustar 00root root 0000000 0000000 write-file-atomic
-----------------
This is an extension for node's `fs.writeFile` that makes its operation
atomic and allows you set ownership (uid/gid of the file).
### `writeFileAtomic(filename, data, [options], [callback])`
#### Description:
Atomically and asynchronously writes data to a file, replacing the file if it already
exists. data can be a string or a buffer.
#### Options:
* filename **String**
* data **String** | **Buffer**
* options **Object** | **String**
* chown **Object** default, uid & gid of existing file, if any
* uid **Number**
* gid **Number**
* encoding **String** | **Null** default = 'utf8'
* fsync **Boolean** default = true
* mode **Number** default, from existing file, if any
* tmpfileCreated **Function** called when the tmpfile is created
* callback **Function**
#### Usage:
```js
var writeFileAtomic = require('write-file-atomic')
writeFileAtomic(filename, data, [options], [callback])
```
The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`.
Note that `require('worker_threads').threadId` is used in addition to `process.pid` if running inside of a worker thread.
If writeFile completes successfully then, if passed the **chown** option it will change
the ownership of the file. Finally it renames the file back to the filename you specified. If
it encounters errors at any of these steps it will attempt to unlink the temporary file and then
pass the error back to the caller.
If multiple writes are concurrently issued to the same file, the write operations are put into a queue and serialized in the order they were called, using Promises. Writes to different files are still executed in parallel.
If provided, the **chown** option requires both **uid** and **gid** properties or else
you'll get an error. If **chown** is not specified it will default to using
the owner of the previous file. To prevent chown from being ran you can
also pass `false`, in which case the file will be created with the current user's credentials.
If **mode** is not specified, it will default to using the permissions from
an existing file, if any. Expicitly setting this to `false` remove this default, resulting
in a file created with the system default permissions.
If options is a String, it's assumed to be the **encoding** option. The **encoding** option is ignored if **data** is a buffer. It defaults to 'utf8'.
If the **fsync** option is **false**, writeFile will skip the final fsync call.
If the **tmpfileCreated** option is specified it will be called with the name of the tmpfile when created.
Example:
```javascript
writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
```
This function also supports async/await:
```javascript
(async () => {
try {
await writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}});
console.log('It\'s saved!');
} catch (err) {
console.error(err);
process.exit(1);
}
})();
```
### `writeFileAtomicSync(filename, data, [options])`
#### Description:
The synchronous version of **writeFileAtomic**.
#### Usage:
```js
var writeFileAtomicSync = require('write-file-atomic').sync
writeFileAtomicSync(filename, data, [options])
```
write-file-atomic-4.0.2/SECURITY.md 0000664 0000000 0000000 00000000246 14276747703 0016652 0 ustar 00root root 0000000 0000000
Please send vulnerability reports through [hackerone](https://hackerone.com/github).
write-file-atomic-4.0.2/docs/ 0000775 0000000 0000000 00000000000 14276747703 0016007 5 ustar 00root root 0000000 0000000 write-file-atomic-4.0.2/docs/changelog-pre-4.0.0.md 0000664 0000000 0000000 00000001575 14276747703 0021511 0 ustar 00root root 0000000 0000000 # 3.0.0
* Implement options.tmpfileCreated callback.
* Drop Node.js 6, modernize code, return Promise from async function.
* Support write TypedArray's like in node fs.writeFile.
* Remove graceful-fs dependency.
# 2.4.3
* Ignore errors raised by `fs.closeSync` when cleaning up after a write
error.
# 2.4.2
* A pair of patches to fix some fd leaks. We would leak fds with sync use
when errors occured and with async use any time fsync was not in use. (#34)
# 2.4.1
* Fix a bug where `signal-exit` instances would be leaked. This was fixed when addressing #35.
# 2.4.0
## Features
* Allow chown and mode options to be set to false to disable the defaulting behavior. (#20)
* Support passing encoding strings in options slot for compat with Node.js API. (#31)
* Add support for running inside of worker threads (#37)
## Fixes
* Remove unneeded call when returning success (#36)
write-file-atomic-4.0.2/lib/ 0000775 0000000 0000000 00000000000 14276747703 0015625 5 ustar 00root root 0000000 0000000 write-file-atomic-4.0.2/lib/index.js 0000664 0000000 0000000 00000015132 14276747703 0017274 0 ustar 00root root 0000000 0000000 'use strict'
module.exports = writeFile
module.exports.sync = writeFileSync
module.exports._getTmpname = getTmpname // for testing
module.exports._cleanupOnExit = cleanupOnExit
const fs = require('fs')
const MurmurHash3 = require('imurmurhash')
const onExit = require('signal-exit')
const path = require('path')
const { promisify } = require('util')
const activeFiles = {}
// if we run inside of a worker_thread, `process.pid` is not unique
/* istanbul ignore next */
const threadId = (function getId () {
try {
const workerThreads = require('worker_threads')
/// if we are in main thread, this is set to `0`
return workerThreads.threadId
} catch (e) {
// worker_threads are not available, fallback to 0
return 0
}
})()
let invocations = 0
function getTmpname (filename) {
return filename + '.' +
MurmurHash3(__filename)
.hash(String(process.pid))
.hash(String(threadId))
.hash(String(++invocations))
.result()
}
function cleanupOnExit (tmpfile) {
return () => {
try {
fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile)
} catch {
// ignore errors
}
}
}
function serializeActiveFile (absoluteName) {
return new Promise(resolve => {
// make a queue if it doesn't already exist
if (!activeFiles[absoluteName]) {
activeFiles[absoluteName] = []
}
activeFiles[absoluteName].push(resolve) // add this job to the queue
if (activeFiles[absoluteName].length === 1) {
resolve()
} // kick off the first one
})
}
// 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 }
}
let fd
let tmpfile
/* istanbul ignore next -- The closure only gets called when onExit triggers */
const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile))
const absoluteName = path.resolve(filename)
try {
await serializeActiveFile(absoluteName)
const truename = await promisify(fs.realpath)(filename).catch(() => filename)
tmpfile = getTmpname(truename)
if (!options.mode || !options.chown) {
// Either mode or chown is not explicitly set
// Default behavior is to copy it from original file
const stats = await promisify(fs.stat)(truename).catch(() => {})
if (stats) {
if (options.mode == null) {
options.mode = stats.mode
}
if (options.chown == null && process.getuid) {
options.chown = { uid: stats.uid, gid: stats.gid }
}
}
}
fd = await promisify(fs.open)(tmpfile, 'w', options.mode)
if (options.tmpfileCreated) {
await options.tmpfileCreated(tmpfile)
}
if (ArrayBuffer.isView(data)) {
await promisify(fs.write)(fd, data, 0, data.length, 0)
} else if (data != null) {
await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8'))
}
if (options.fsync !== false) {
await promisify(fs.fsync)(fd)
}
await promisify(fs.close)(fd)
fd = null
if (options.chown) {
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).catch(err => {
if (!isChownErrOk(err)) {
throw err
}
})
}
await promisify(fs.rename)(tmpfile, truename)
} finally {
if (fd) {
await promisify(fs.close)(fd).catch(
/* istanbul ignore next */
() => {}
)
}
removeOnExitHandler()
await promisify(fs.unlink)(tmpfile).catch(() => {})
activeFiles[absoluteName].shift() // remove the element added by serializeSameFile
if (activeFiles[absoluteName].length > 0) {
activeFiles[absoluteName][0]() // start next job if one is pending
} else {
delete activeFiles[absoluteName]
}
}
}
async function writeFile (filename, data, options, callback) {
if (options instanceof Function) {
callback = options
options = {}
}
const promise = writeFileAsync(filename, data, options)
if (callback) {
try {
const result = await promise
return callback(result)
} catch (err) {
return callback(err)
}
}
return promise
}
function writeFileSync (filename, data, options) {
if (typeof options === 'string') {
options = { encoding: options }
} else if (!options) {
options = {}
}
try {
filename = fs.realpathSync(filename)
} catch (ex) {
// it's ok, it'll happen on a not yet existing file
}
const tmpfile = getTmpname(filename)
if (!options.mode || !options.chown) {
// Either mode or chown is not explicitly set
// Default behavior is to copy it from original file
try {
const stats = fs.statSync(filename)
options = Object.assign({}, options)
if (!options.mode) {
options.mode = stats.mode
}
if (!options.chown && process.getuid) {
options.chown = { uid: stats.uid, gid: stats.gid }
}
} catch (ex) {
// ignore stat errors
}
}
let fd
const cleanup = cleanupOnExit(tmpfile)
const removeOnExitHandler = onExit(cleanup)
let threw = true
try {
fd = fs.openSync(tmpfile, 'w', options.mode || 0o666)
if (options.tmpfileCreated) {
options.tmpfileCreated(tmpfile)
}
if (ArrayBuffer.isView(data)) {
fs.writeSync(fd, data, 0, data.length, 0)
} else if (data != null) {
fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'))
}
if (options.fsync !== false) {
fs.fsyncSync(fd)
}
fs.closeSync(fd)
fd = null
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 {
if (fd) {
try {
fs.closeSync(fd)
} catch (ex) {
// ignore close errors at this stage, error may have closed fd already.
}
}
removeOnExitHandler()
if (threw) {
cleanup()
}
}
}
write-file-atomic-4.0.2/package.json 0000664 0000000 0000000 00000002615 14276747703 0017351 0 ustar 00root root 0000000 0000000 {
"name": "write-file-atomic",
"version": "4.0.2",
"description": "Write files in an atomic fashion w/configurable ownership",
"main": "./lib/index.js",
"scripts": {
"test": "tap",
"posttest": "npm run lint",
"lint": "eslint \"**/*.js\"",
"postlint": "template-oss-check",
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"lintfix": "npm run lint -- --fix",
"snap": "tap",
"template-oss-apply": "template-oss-apply --force"
},
"repository": {
"type": "git",
"url": "https://github.com/npm/write-file-atomic.git"
},
"keywords": [
"writeFile",
"atomic"
],
"author": "GitHub Inc.",
"license": "ISC",
"bugs": {
"url": "https://github.com/npm/write-file-atomic/issues"
},
"homepage": "https://github.com/npm/write-file-atomic",
"dependencies": {
"imurmurhash": "^0.1.4",
"signal-exit": "^3.0.7"
},
"devDependencies": {
"@npmcli/eslint-config": "^3.0.1",
"@npmcli/template-oss": "3.5.0",
"mkdirp": "^1.0.4",
"rimraf": "^3.0.2",
"tap": "^16.0.1"
},
"files": [
"bin/",
"lib/"
],
"engines": {
"node": "^12.13.0 || ^14.15.0 || >=16.0.0"
},
"templateOSS": {
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
"windowsCI": false,
"version": "3.5.0"
}
}
write-file-atomic-4.0.2/test/ 0000775 0000000 0000000 00000000000 14276747703 0016036 5 ustar 00root root 0000000 0000000 write-file-atomic-4.0.2/test/basic.js 0000664 0000000 0000000 00000031315 14276747703 0017460 0 ustar 00root root 0000000 0000000 'use strict'
const t = require('tap')
let expectClose = 0
let closeCalled = 0
let expectCloseSync = 0
let closeSyncCalled = 0
const createErr = code => Object.assign(new Error(code), { code })
let unlinked = []
const writeFileAtomic = t.mock('..', {
fs: {
realpath (filename, cb) {
return cb(null, filename)
},
open (tmpfile, options, mode, cb) {
if (/noopen/.test(tmpfile)) {
return cb(createErr('ENOOPEN'))
}
expectClose++
cb(null, tmpfile)
},
write (fd) {
const cb = arguments[arguments.length - 1]
if (/nowrite/.test(fd)) {
return cb(createErr('ENOWRITE'))
}
cb()
},
fsync (fd, cb) {
if (/nofsync/.test(fd)) {
return cb(createErr('ENOFSYNC'))
}
cb()
},
close (fd, cb) {
closeCalled++
cb()
},
chown (tmpfile, uid, gid, cb) {
if (/nochown/.test(tmpfile)) {
return cb(createErr('ENOCHOWN'))
}
if (/enosys/.test(tmpfile)) {
return cb(createErr('ENOSYS'))
}
if (/einval/.test(tmpfile)) {
return cb(createErr('EINVAL'))
}
if (/eperm/.test(tmpfile)) {
return cb(createErr('EPERM'))
}
cb()
},
chmod (tmpfile, mode, cb) {
if (/nochmod/.test(tmpfile)) {
return cb(createErr('ENOCHMOD'))
}
if (/enosys/.test(tmpfile)) {
return cb(createErr('ENOSYS'))
}
if (/eperm/.test(tmpfile)) {
return cb(createErr('EPERM'))
}
if (/einval/.test(tmpfile)) {
return cb(createErr('EINVAL'))
}
cb()
},
rename (tmpfile, filename, cb) {
if (/norename/.test(tmpfile)) {
return cb(createErr('ENORENAME'))
}
cb()
},
unlink (tmpfile, cb) {
if (/nounlink/.test(tmpfile)) {
return cb(createErr('ENOUNLINK'))
}
cb()
},
stat (tmpfile, cb) {
if (/nostat/.test(tmpfile)) {
return cb(createErr('ENOSTAT'))
}
cb()
},
realpathSync (filename, cb) {
return filename
},
openSync (tmpfile, options) {
if (/noopen/.test(tmpfile)) {
throw createErr('ENOOPEN')
}
expectCloseSync++
return tmpfile
},
writeSync (fd) {
if (/nowrite/.test(fd)) {
throw createErr('ENOWRITE')
}
},
fsyncSync (fd) {
if (/nofsync/.test(fd)) {
throw createErr('ENOFSYNC')
}
},
closeSync (fd) {
closeSyncCalled++
},
chownSync (tmpfile, uid, gid) {
if (/nochown/.test(tmpfile)) {
throw createErr('ENOCHOWN')
}
if (/enosys/.test(tmpfile)) {
throw createErr('ENOSYS')
}
if (/einval/.test(tmpfile)) {
throw createErr('EINVAL')
}
if (/eperm/.test(tmpfile)) {
throw createErr('EPERM')
}
},
chmodSync (tmpfile, mode) {
if (/nochmod/.test(tmpfile)) {
throw createErr('ENOCHMOD')
}
if (/enosys/.test(tmpfile)) {
throw createErr('ENOSYS')
}
if (/einval/.test(tmpfile)) {
throw createErr('EINVAL')
}
if (/eperm/.test(tmpfile)) {
throw createErr('EPERM')
}
},
renameSync (tmpfile, filename) {
if (/norename/.test(tmpfile)) {
throw createErr('ENORENAME')
}
},
unlinkSync (tmpfile) {
if (/nounlink/.test(tmpfile)) {
throw createErr('ENOUNLINK')
}
unlinked.push(tmpfile)
},
statSync (tmpfile) {
if (/nostat/.test(tmpfile)) {
throw createErr('ENOSTAT')
}
},
},
})
const writeFileAtomicSync = writeFileAtomic.sync
t.test('getTmpname', t => {
const getTmpname = writeFileAtomic._getTmpname
const a = getTmpname('abc.def')
const b = getTmpname('abc.def')
t.not(a, b, 'different invocations of getTmpname get different results')
t.end()
})
t.test('cleanupOnExit', t => {
const file = 'tmpname'
unlinked = []
const cleanup = writeFileAtomic._cleanupOnExit(() => file)
cleanup()
t.strictSame(unlinked, [file], 'cleanup code unlinks')
const cleanup2 = writeFileAtomic._cleanupOnExit('nounlink')
t.doesNotThrow(cleanup2, 'exceptions are caught')
unlinked = []
t.end()
})
t.test('async tests', t => {
t.plan(2)
expectClose = 0
closeCalled = 0
t.teardown(() => {
t.parent.equal(closeCalled, expectClose, 'async tests closed all files')
expectClose = 0
closeCalled = 0
})
t.test('non-root tests', t => {
t.plan(19)
writeFileAtomic('good', 'test', { mode: '0777' }, err => {
t.notOk(err, 'No errors occur when passing in options')
})
writeFileAtomic('good', 'test', 'utf8', err => {
t.notOk(err, 'No errors occur when passing in options as string')
})
writeFileAtomic('good', 'test', undefined, err => {
t.notOk(err, 'No errors occur when NOT passing in options')
})
writeFileAtomic('good', 'test', err => {
t.notOk(err)
})
writeFileAtomic('noopen', 'test', err => {
t.equal(err && err.message, 'ENOOPEN', 'fs.open failures propagate')
})
writeFileAtomic('nowrite', 'test', err => {
t.equal(err && err.message, 'ENOWRITE', 'fs.writewrite failures propagate')
})
writeFileAtomic('nowrite', Buffer.from('test', 'utf8'), err => {
t.equal(err && err.message, 'ENOWRITE', 'fs.writewrite failures propagate for buffers')
})
writeFileAtomic('nochown', 'test', { chown: { uid: 100, gid: 100 } }, err => {
t.equal(err && err.message, 'ENOCHOWN', 'Chown failures propagate')
})
writeFileAtomic('nochown', 'test', err => {
t.notOk(err, 'No attempt to chown when no uid/gid passed in')
})
writeFileAtomic('nochmod', 'test', { mode: parseInt('741', 8) }, err => {
t.equal(err && err.message, 'ENOCHMOD', 'Chmod failures propagate')
})
writeFileAtomic('nofsyncopt', 'test', { fsync: false }, err => {
t.notOk(err, 'fsync skipped if options.fsync is false')
})
writeFileAtomic('norename', 'test', err => {
t.equal(err && err.message, 'ENORENAME', 'Rename errors propagate')
})
writeFileAtomic('norename nounlink', 'test', err => {
t.equal(err && err.message, 'ENORENAME',
'Failure to unlink the temp file does not clobber the original error')
})
writeFileAtomic('nofsync', 'test', err => {
t.equal(err && err.message, 'ENOFSYNC', 'Fsync failures propagate')
})
writeFileAtomic('enosys', 'test', err => {
t.notOk(err, 'No errors on ENOSYS')
})
writeFileAtomic('einval', 'test', { mode: 0o741 }, err => {
t.notOk(err, 'No errors on EINVAL for non root')
})
writeFileAtomic('eperm', 'test', { mode: 0o741 }, err => {
t.notOk(err, 'No errors on EPERM for non root')
})
writeFileAtomic('einval', 'test', { chown: { uid: 100, gid: 100 } }, err => {
t.notOk(err, 'No errors on EINVAL for non root')
})
writeFileAtomic('eperm', 'test', { chown: { uid: 100, gid: 100 } }, err => {
t.notOk(err, 'No errors on EPERM for non root')
})
})
t.test('errors for root', t => {
const { getuid } = process
process.getuid = () => 0
t.teardown(() => {
process.getuid = getuid
})
t.plan(2)
writeFileAtomic('einval', 'test', { chown: { uid: 100, gid: 100 } }, err => {
t.match(err, { code: 'EINVAL' })
})
writeFileAtomic('einval', 'test', { mode: 0o741 }, err => {
t.match(err, { code: 'EINVAL' })
})
})
})
t.test('sync tests', t => {
t.plan(2)
closeSyncCalled = 0
expectCloseSync = 0
t.teardown(() => {
t.parent.equal(closeSyncCalled, expectCloseSync, 'sync closed all files')
expectCloseSync = 0
closeSyncCalled = 0
})
const throws = function (t, shouldthrow, msg, todo) {
let err
try {
todo()
} catch (e) {
err = e
}
t.equal(shouldthrow, err && err.message, msg)
}
const noexception = function (t, msg, todo) {
let err
try {
todo()
} catch (e) {
err = e
}
t.error(err, msg)
}
let tmpfile
t.test('non-root', t => {
t.plan(22)
noexception(t, 'No errors occur when passing in options', () => {
writeFileAtomicSync('good', 'test', { mode: '0777' })
})
noexception(t, 'No errors occur when passing in options as string', () => {
writeFileAtomicSync('good', 'test', 'utf8')
})
noexception(t, 'No errors occur when NOT passing in options', () => {
writeFileAtomicSync('good', 'test')
})
noexception(t, 'fsync never called if options.fsync is falsy', () => {
writeFileAtomicSync('good', 'test', { fsync: false })
})
noexception(t, 'tmpfileCreated is called on success', () => {
writeFileAtomicSync('good', 'test', {
tmpfileCreated (gottmpfile) {
tmpfile = gottmpfile
},
})
t.match(tmpfile, /^good\.\d+$/, 'tmpfileCreated called for success')
})
tmpfile = undefined
throws(t, 'ENOOPEN', 'fs.openSync failures propagate', () => {
writeFileAtomicSync('noopen', 'test', {
tmpfileCreated (gottmpfile) {
tmpfile = gottmpfile
},
})
})
t.equal(tmpfile, undefined, 'tmpfileCreated not called for open failure')
throws(t, 'ENOWRITE', 'fs.writeSync failures propagate', () => {
writeFileAtomicSync('nowrite', 'test', {
tmpfileCreated (gottmpfile) {
tmpfile = gottmpfile
},
})
})
t.match(tmpfile, /^nowrite\.\d+$/, 'tmpfileCreated called for failure after open')
throws(t, 'ENOCHOWN', 'Chown failures propagate', () => {
writeFileAtomicSync('nochown', 'test', { chown: { uid: 100, gid: 100 } })
})
noexception(t, 'No attempt to chown when false passed in', () => {
writeFileAtomicSync('nochown', 'test', { chown: false })
})
noexception(t, 'No errors occured when chown is undefined and original file owner used', () => {
writeFileAtomicSync('chowncopy', 'test', { chown: undefined })
})
throws(t, 'ENORENAME', 'Rename errors propagate', () => {
writeFileAtomicSync('norename', 'test')
})
throws(t, 'ENORENAME',
'Failure to unlink the temp file does not clobber the original error', () => {
writeFileAtomicSync('norename nounlink', 'test')
})
throws(t, 'ENOFSYNC', 'Fsync errors propagate', () => {
writeFileAtomicSync('nofsync', 'test')
})
noexception(t, 'No errors on ENOSYS', () => {
writeFileAtomicSync('enosys', 'test', { chown: { uid: 100, gid: 100 } })
})
noexception(t, 'No errors on EINVAL for non root', () => {
writeFileAtomicSync('einval', 'test', { chown: { uid: 100, gid: 100 } })
})
noexception(t, 'No errors on EPERM for non root', () => {
writeFileAtomicSync('eperm', 'test', { chown: { uid: 100, gid: 100 } })
})
throws(t, 'ENOCHMOD', 'Chmod failures propagate', () => {
writeFileAtomicSync('nochmod', 'test', { mode: 0o741 })
})
noexception(t, 'No errors on EPERM for non root', () => {
writeFileAtomicSync('eperm', 'test', { mode: 0o741 })
})
noexception(t, 'No attempt to chmod when no mode provided', () => {
writeFileAtomicSync('nochmod', 'test', { mode: false })
})
})
t.test('errors for root', t => {
const { getuid } = process
process.getuid = () => 0
t.teardown(() => {
process.getuid = getuid
})
t.plan(2)
throws(t, 'EINVAL', 'Chown error as root user', () => {
writeFileAtomicSync('einval', 'test', { chown: { uid: 100, gid: 100 } })
})
throws(t, 'EINVAL', 'Chmod error as root user', () => {
writeFileAtomicSync('einval', 'test', { mode: 0o741 })
})
})
})
t.test('promises', async t => {
let tmpfile
closeCalled = 0
expectClose = 0
t.teardown(() => {
t.parent.equal(closeCalled, expectClose, 'promises closed all files')
closeCalled = 0
expectClose = 0
})
await writeFileAtomic('good', 'test', {
tmpfileCreated (gottmpfile) {
tmpfile = gottmpfile
},
})
t.match(tmpfile, /^good\.\d+$/, 'tmpfileCreated is called for success')
await writeFileAtomic('good', 'test', {
tmpfileCreated (gottmpfile) {
return Promise.resolve()
},
})
await t.rejects(writeFileAtomic('good', 'test', {
tmpfileCreated () {
return Promise.reject(new Error('reject from tmpfileCreated'))
},
}))
await t.rejects(writeFileAtomic('good', 'test', {
tmpfileCreated () {
throw new Error('throw from tmpfileCreated')
},
}))
tmpfile = undefined
await t.rejects(writeFileAtomic('noopen', 'test', {
tmpfileCreated (gottmpfile) {
tmpfile = gottmpfile
},
}))
t.equal(tmpfile, undefined, 'tmpfileCreated is not called on open failure')
await t.rejects(writeFileAtomic('nowrite', 'test', {
tmpfileCreated (gottmpfile) {
tmpfile = gottmpfile
},
}))
t.match(tmpfile, /^nowrite\.\d+$/, 'tmpfileCreated is called if failure is after open')
})
write-file-atomic-4.0.2/test/concurrency.js 0000664 0000000 0000000 00000010367 14276747703 0020735 0 ustar 00root root 0000000 0000000 'use strict'
const t = require('tap')
// defining mock for fs so its functions can be modified
const fs = {
realpath (filename, cb) {
return cb(null, filename)
},
open (tmpfile, options, mode, cb) {
if (/noopen/.test(tmpfile)) {
return cb(new Error('ENOOPEN'))
}
cb(null, tmpfile)
},
write (fd) {
const cb = arguments[arguments.length - 1]
if (/nowrite/.test(fd)) {
return cb(new Error('ENOWRITE'))
}
cb()
},
fsync (fd, cb) {
if (/nofsync/.test(fd)) {
return cb(new Error('ENOFSYNC'))
}
cb()
},
close (fd, cb) {
cb()
},
chown (tmpfile, uid, gid, cb) {
if (/nochown/.test(tmpfile)) {
return cb(new Error('ENOCHOWN'))
}
cb()
},
chmod (tmpfile, mode, cb) {
if (/nochmod/.test(tmpfile)) {
return cb(new Error('ENOCHMOD'))
}
cb()
},
rename (tmpfile, filename, cb) {
if (/norename/.test(tmpfile)) {
return cb(new Error('ENORENAME'))
}
cb()
},
unlink (tmpfile, cb) {
if (/nounlink/.test(tmpfile)) {
return cb(new Error('ENOUNLINK'))
}
cb()
},
stat (tmpfile, cb) {
if (/nostat/.test(tmpfile)) {
return cb(new Error('ENOSTAT'))
}
cb()
},
realpathSync (filename, cb) {
return filename
},
openSync (tmpfile, options) {
if (/noopen/.test(tmpfile)) {
throw new Error('ENOOPEN')
}
return tmpfile
},
writeSync (fd) {
if (/nowrite/.test(fd)) {
throw new Error('ENOWRITE')
}
},
fsyncSync (fd) {
if (/nofsync/.test(fd)) {
throw new Error('ENOFSYNC')
}
},
closeSync () { },
chownSync (tmpfile, uid, gid) {
if (/nochown/.test(tmpfile)) {
throw new Error('ENOCHOWN')
}
},
chmodSync (tmpfile, mode) {
if (/nochmod/.test(tmpfile)) {
throw new Error('ENOCHMOD')
}
},
renameSync (tmpfile, filename) {
if (/norename/.test(tmpfile)) {
throw new Error('ENORENAME')
}
},
unlinkSync (tmpfile) {
if (/nounlink/.test(tmpfile)) {
throw new Error('ENOUNLINK')
}
},
statSync (tmpfile) {
if (/nostat/.test(tmpfile)) {
throw new Error('ENOSTAT')
}
},
}
const writeFileAtomic = t.mock('..', {
fs: fs,
})
// preserve original functions
const oldRealPath = fs.realpath
const oldRename = fs.rename
t.test('ensure writes to the same file are serial', t => {
let fileInUse = false
const ops = 5 // count for how many concurrent write ops to request
t.plan(ops * 3 + 3)
fs.realpath = (...args) => {
t.notOk(fileInUse, 'file not in use')
fileInUse = true
oldRealPath(...args)
}
fs.rename = (...args) => {
t.ok(fileInUse, 'file in use')
fileInUse = false
oldRename(...args)
}
for (let i = 0; i < ops; i++) {
writeFileAtomic('test', 'test', err => {
if (err) {
t.fail(err)
} else {
t.pass('wrote without error')
}
})
}
setTimeout(() => {
writeFileAtomic('test', 'test', err => {
if (err) {
t.fail(err)
} else {
t.pass('successive writes after delay')
}
})
}, 500)
})
t.test('allow write to multiple files in parallel, but same file writes are serial', t => {
const filesInUse = []
const ops = 5
let wasParallel = false
fs.realpath = (filename, ...args) => {
filesInUse.push(filename)
const firstOccurence = filesInUse.indexOf(filename)
// check for another occurence after the first
t.equal(filesInUse.indexOf(filename, firstOccurence + 1), -1, 'serial writes')
if (filesInUse.length > 1) {
wasParallel = true
} // remember that a parallel operation took place
oldRealPath(filename, ...args)
}
fs.rename = (filename, ...args) => {
filesInUse.splice(filesInUse.indexOf(filename), 1)
oldRename(filename, ...args)
}
t.plan(ops * 2 * 2 + 1)
let opCount = 0
for (let i = 0; i < ops; i++) {
writeFileAtomic('test', 'test', err => {
if (err) {
t.fail(err, 'wrote without error')
} else {
t.pass('wrote without error')
}
})
writeFileAtomic('test2', 'test', err => {
opCount++
if (opCount === ops) {
t.ok(wasParallel, 'parallel writes')
}
if (err) {
t.fail(err, 'wrote without error')
} else {
t.pass('wrote without error')
}
})
}
})
write-file-atomic-4.0.2/test/integration.js 0000664 0000000 0000000 00000020765 14276747703 0020731 0 ustar 00root root 0000000 0000000 'use strict'
const fs = require('fs')
const path = require('path')
const t = require('tap')
const mkdirp = require('mkdirp')
const rimraf = require('rimraf')
const workdir = path.join(__dirname, path.basename(__filename, '.js'))
let testfiles = 0
function tmpFile () {
return path.join(workdir, 'test-' + (++testfiles))
}
function readFile (p) {
return fs.readFileSync(p).toString()
}
function didWriteFileAtomic (t, expected, filename, data, options, callback) {
if (options instanceof Function) {
callback = options
options = null
}
if (!options) {
options = {}
}
const actual = {}
const writeFileAtomic = t.mock('..', {
fs: Object.assign({}, fs, {
chown (chownFilename, uid, gid, cb) {
actual.uid = uid
actual.gid = gid
process.nextTick(cb)
},
stat (statFilename, cb) {
fs.stat(statFilename, (err, stats) => {
if (err) {
return cb(err)
}
cb(null, Object.assign(stats, expected || {}))
})
},
}),
})
return writeFileAtomic(filename, data, options, err => {
t.strictSame(actual, expected, 'ownership is as expected')
callback(err)
})
}
function didWriteFileAtomicSync (t, expected, filename, data, options) {
const actual = {}
const writeFileAtomic = t.mock('..', {
fs: Object.assign({}, fs, {
chownSync (chownFilename, uid, gid) {
actual.uid = uid
actual.gid = gid
},
statSync (statFilename) {
const stats = fs.statSync(statFilename)
return Object.assign(stats, expected || {})
},
}),
})
writeFileAtomic.sync(filename, data, options)
t.strictSame(actual, expected)
}
function currentUser () {
return {
uid: process.getuid(),
gid: process.getgid(),
}
}
t.test('setup', t => {
rimraf.sync(workdir)
mkdirp.sync(workdir)
t.end()
})
t.test('writes simple file (async)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, '42', err => {
t.error(err, 'no error')
t.equal(readFile(file), '42', 'content ok')
})
})
t.test('writes simple file with encoding (async)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, 'foo', 'utf16le', err => {
t.error(err, 'no error')
t.equal(readFile(file), 'f\u0000o\u0000o\u0000', 'content ok')
})
})
t.test('writes buffers to simple file (async)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, Buffer.from('42'), err => {
t.error(err, 'no error')
t.equal(readFile(file), '42', 'content ok')
})
})
t.test('writes TypedArray to simple file (async)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, new Uint8Array([0x34, 0x32]), err => {
t.error(err, 'no error')
t.equal(readFile(file), '42', 'content ok')
})
})
t.test('writes undefined to simple file (async)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, undefined, err => {
t.error(err, 'no error')
t.equal(readFile(file), '', 'content ok')
})
})
t.test('writes to symlinks without clobbering (async)', t => {
t.plan(5)
const file = tmpFile()
const link = tmpFile()
fs.writeFileSync(file, '42')
fs.symlinkSync(file, link)
didWriteFileAtomic(t, currentUser(), link, '43', err => {
t.error(err, 'no error')
t.equal(readFile(file), '43', 'target content ok')
t.equal(readFile(link), '43', 'link content ok')
t.ok(fs.lstatSync(link).isSymbolicLink(), 'link is link')
})
})
t.test('runs chown on given file (async)', t => {
const file = tmpFile()
didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } }, err => {
t.error(err, 'no error')
t.equal(readFile(file), '42', 'content ok')
t.end()
})
})
t.test('writes simple file with no chown (async)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, '42', { chown: false }, err => {
t.error(err, 'no error')
t.equal(readFile(file), '42', 'content ok')
t.end()
})
})
t.test('runs chmod on given file (async)', t => {
t.plan(5)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, '42', { mode: parseInt('741', 8) }, err => {
t.error(err, 'no error')
const stat = fs.statSync(file)
t.equal(stat.mode, parseInt('100741', 8))
didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '23',
{ chown: { uid: 42, gid: 43 } }, chownErr => {
t.error(chownErr, 'no error')
})
})
})
t.test('run chmod AND chown (async)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42',
{ mode: parseInt('741', 8), chown: { uid: 42, gid: 43 } }, err => {
t.error(err, 'no error')
const stat = fs.statSync(file)
t.equal(stat.mode, parseInt('100741', 8))
})
})
t.test('does not change chmod by default (async)', t => {
t.plan(5)
const file = tmpFile()
didWriteFileAtomic(t, {}, file, '42', { mode: parseInt('741', 8) }, err => {
t.error(err, 'no error')
didWriteFileAtomic(t, currentUser(), file, '43', writeFileError => {
t.error(writeFileError, 'no error')
const stat = fs.statSync(file)
t.equal(stat.mode, parseInt('100741', 8))
})
})
})
t.test('does not change chown by default (async)', t => {
t.plan(6)
const file = tmpFile()
didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42',
{ chown: { uid: 42, gid: 43 } }, _setModeOnly)
function _setModeOnly (err) {
t.error(err, 'no error')
didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '43',
{ mode: parseInt('741', 8) }, _allDefault)
}
function _allDefault (err) {
t.error(err, 'no error')
didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '43', _noError)
}
function _noError (err) {
t.error(err, 'no error')
}
})
t.test('writes simple file (sync)', t => {
t.plan(2)
const file = tmpFile()
didWriteFileAtomicSync(t, {}, file, '42')
t.equal(readFile(file), '42')
})
t.test('writes simple file with encoding (sync)', t => {
t.plan(2)
const file = tmpFile()
didWriteFileAtomicSync(t, {}, file, 'foo', 'utf16le')
t.equal(readFile(file), 'f\u0000o\u0000o\u0000')
})
t.test('writes simple buffer file (sync)', t => {
t.plan(2)
const file = tmpFile()
didWriteFileAtomicSync(t, {}, file, Buffer.from('42'))
t.equal(readFile(file), '42')
})
t.test('writes simple TypedArray file (sync)', t => {
t.plan(2)
const file = tmpFile()
didWriteFileAtomicSync(t, {}, file, new Uint8Array([0x34, 0x32]))
t.equal(readFile(file), '42')
})
t.test('writes undefined file (sync)', t => {
t.plan(2)
const file = tmpFile()
didWriteFileAtomicSync(t, {}, file, undefined)
t.equal(readFile(file), '')
})
t.test('writes to symlinks without clobbering (sync)', t => {
t.plan(4)
const file = tmpFile()
const link = tmpFile()
fs.writeFileSync(file, '42')
fs.symlinkSync(file, link)
didWriteFileAtomicSync(t, currentUser(), link, '43')
t.equal(readFile(file), '43', 'target content ok')
t.equal(readFile(link), '43', 'link content ok')
t.ok(fs.lstatSync(link).isSymbolicLink(), 'link is link')
})
t.test('runs chown on given file (sync)', t => {
t.plan(1)
const file = tmpFile()
didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } })
})
t.test('runs chmod on given file (sync)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomicSync(t, {}, file, '42', { mode: parseInt('741', 8) })
const stat = fs.statSync(file)
t.equal(stat.mode, parseInt('100741', 8))
didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '23', { chown: { uid: 42, gid: 43 } })
})
t.test('runs chown and chmod (sync)', t => {
t.plan(2)
const file = tmpFile()
didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42',
{ mode: parseInt('741', 8), chown: { uid: 42, gid: 43 } })
const stat = fs.statSync(file)
t.equal(stat.mode, parseInt('100741', 8))
})
t.test('does not change chmod by default (sync)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomicSync(t, {}, file, '42', { mode: parseInt('741', 8) })
didWriteFileAtomicSync(t, currentUser(), file, '43')
const stat = fs.statSync(file)
t.equal(stat.mode, parseInt('100741', 8))
})
t.test('does not change chown by default (sync)', t => {
t.plan(3)
const file = tmpFile()
didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } })
didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '43', { mode: parseInt('741', 8) })
didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '44')
})
t.test('cleanup', t => {
rimraf.sync(workdir)
t.end()
})