├── .commitlintrc.js
├── .eslintrc.js
├── .github
├── CODEOWNERS
├── ISSUE_TEMPLATE
│ ├── bug.yml
│ └── config.yml
├── actions
│ ├── create-check
│ │ └── action.yml
│ └── install-latest-npm
│ │ └── action.yml
├── dependabot.yml
├── matchers
│ └── tap.json
├── settings.yml
└── workflows
│ ├── audit.yml
│ ├── ci-release.yml
│ ├── ci.yml
│ ├── codeql-analysis.yml
│ ├── post-dependabot.yml
│ ├── pull-request.yml
│ ├── release-integration.yml
│ └── release.yml
├── .gitignore
├── .npmrc
├── .release-please-manifest.json
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── SECURITY.md
├── docs
└── changelog-pre-4.0.0.md
├── lib
└── index.js
├── package.json
├── release-please-config.json
└── test
├── basic.js
├── concurrency.js
└── integration.js
/.commitlintrc.js:
--------------------------------------------------------------------------------
1 | /* This file is automatically added by @npmcli/template-oss. Do not edit. */
2 |
3 | module.exports = {
4 | extends: ['@commitlint/config-conventional'],
5 | rules: {
6 | 'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'deps', 'chore']],
7 | 'header-max-length': [2, 'always', 80],
8 | 'subject-case': [0],
9 | 'body-max-line-length': [0],
10 | 'footer-max-line-length': [0],
11 | },
12 | }
13 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | /* This file is automatically added by @npmcli/template-oss. Do not edit. */
2 |
3 | 'use strict'
4 |
5 | const { readdirSync: readdir } = require('fs')
6 |
7 | const localConfigs = readdir(__dirname)
8 | .filter((file) => file.startsWith('.eslintrc.local.'))
9 | .map((file) => `./${file}`)
10 |
11 | module.exports = {
12 | root: true,
13 | ignorePatterns: [
14 | 'tap-testdir*/',
15 | ],
16 | extends: [
17 | '@npmcli',
18 | ...localConfigs,
19 | ],
20 | }
21 |
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | * @npm/cli-team
4 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: Bug
4 | description: File a bug/issue
5 | title: "[BUG]
"
6 | labels: [ Bug, Needs Triage ]
7 |
8 | body:
9 | - type: checkboxes
10 | attributes:
11 | label: Is there an existing issue for this?
12 | description: Please [search here](./issues) to see if an issue already exists for your problem.
13 | options:
14 | - label: I have searched the existing issues
15 | required: true
16 | - type: textarea
17 | attributes:
18 | label: Current Behavior
19 | description: A clear & concise description of what you're experiencing.
20 | validations:
21 | required: false
22 | - type: textarea
23 | attributes:
24 | label: Expected Behavior
25 | description: A clear & concise description of what you expected to happen.
26 | validations:
27 | required: false
28 | - type: textarea
29 | attributes:
30 | label: Steps To Reproduce
31 | description: Steps to reproduce the behavior.
32 | value: |
33 | 1. In this environment...
34 | 2. With this config...
35 | 3. Run '...'
36 | 4. See error...
37 | validations:
38 | required: false
39 | - type: textarea
40 | attributes:
41 | label: Environment
42 | description: |
43 | examples:
44 | - **npm**: 7.6.3
45 | - **Node**: 13.14.0
46 | - **OS**: Ubuntu 20.04
47 | - **platform**: Macbook Pro
48 | value: |
49 | - npm:
50 | - Node:
51 | - OS:
52 | - platform:
53 | validations:
54 | required: false
55 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | blank_issues_enabled: true
4 |
--------------------------------------------------------------------------------
/.github/actions/create-check/action.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: 'Create Check'
4 | inputs:
5 | name:
6 | required: true
7 | token:
8 | required: true
9 | sha:
10 | required: true
11 | check-name:
12 | default: ''
13 | outputs:
14 | check-id:
15 | value: ${{ steps.create-check.outputs.check_id }}
16 | runs:
17 | using: "composite"
18 | steps:
19 | - name: Get Workflow Job
20 | uses: actions/github-script@v7
21 | id: workflow
22 | env:
23 | JOB_NAME: "${{ inputs.name }}"
24 | SHA: "${{ inputs.sha }}"
25 | with:
26 | result-encoding: string
27 | script: |
28 | const { repo: { owner, repo}, runId, serverUrl } = context
29 | const { JOB_NAME, SHA } = process.env
30 |
31 | const job = await github.rest.actions.listJobsForWorkflowRun({
32 | owner,
33 | repo,
34 | run_id: runId,
35 | per_page: 100
36 | }).then(r => r.data.jobs.find(j => j.name.endsWith(JOB_NAME)))
37 |
38 | return [
39 | `This check is assosciated with ${serverUrl}/${owner}/${repo}/commit/${SHA}.`,
40 | 'Run logs:',
41 | job?.html_url || `could not be found for a job ending with: "${JOB_NAME}"`,
42 | ].join(' ')
43 | - name: Create Check
44 | uses: LouisBrunner/checks-action@v1.6.0
45 | id: create-check
46 | with:
47 | token: ${{ inputs.token }}
48 | sha: ${{ inputs.sha }}
49 | status: in_progress
50 | name: ${{ inputs.check-name || inputs.name }}
51 | output: |
52 | {"summary":"${{ steps.workflow.outputs.result }}"}
53 |
--------------------------------------------------------------------------------
/.github/actions/install-latest-npm/action.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: 'Install Latest npm'
4 | description: 'Install the latest version of npm compatible with the Node version'
5 | inputs:
6 | node:
7 | description: 'Current Node version'
8 | required: true
9 | runs:
10 | using: "composite"
11 | steps:
12 | # node 10/12/14 ship with npm@6, which is known to fail when updating itself in windows
13 | - name: Update Windows npm
14 | if: |
15 | runner.os == 'Windows' && (
16 | startsWith(inputs.node, 'v10.') ||
17 | startsWith(inputs.node, 'v12.') ||
18 | startsWith(inputs.node, 'v14.')
19 | )
20 | shell: cmd
21 | run: |
22 | curl -sO https://registry.npmjs.org/npm/-/npm-7.5.4.tgz
23 | tar xf npm-7.5.4.tgz
24 | cd package
25 | node lib/npm.js install --no-fund --no-audit -g ..\npm-7.5.4.tgz
26 | cd ..
27 | rmdir /s /q package
28 | - name: Install Latest npm
29 | shell: bash
30 | env:
31 | NODE_VERSION: ${{ inputs.node }}
32 | working-directory: ${{ runner.temp }}
33 | run: |
34 | MATCH=""
35 | SPECS=("latest" "next-10" "next-9" "next-8" "next-7" "next-6")
36 |
37 | echo "node@$NODE_VERSION"
38 |
39 | for SPEC in ${SPECS[@]}; do
40 | ENGINES=$(npm view npm@$SPEC --json | jq -r '.engines.node')
41 | echo "Checking if node@$NODE_VERSION satisfies npm@$SPEC ($ENGINES)"
42 |
43 | if npx semver -r "$ENGINES" "$NODE_VERSION" > /dev/null; then
44 | MATCH=$SPEC
45 | echo "Found compatible version: npm@$MATCH"
46 | break
47 | fi
48 | done
49 |
50 | if [ -z $MATCH ]; then
51 | echo "Could not find a compatible version of npm for node@$NODE_VERSION"
52 | exit 1
53 | fi
54 |
55 | npm i --prefer-online --no-fund --no-audit -g npm@$MATCH
56 | - name: npm Version
57 | shell: bash
58 | run: npm -v
59 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | version: 2
4 |
5 | updates:
6 | - package-ecosystem: npm
7 | directory: /
8 | schedule:
9 | interval: daily
10 | target-branch: "main"
11 | allow:
12 | - dependency-type: direct
13 | versioning-strategy: increase-if-necessary
14 | commit-message:
15 | prefix: deps
16 | prefix-development: chore
17 | labels:
18 | - "Dependencies"
19 | open-pull-requests-limit: 10
20 |
--------------------------------------------------------------------------------
/.github/matchers/tap.json:
--------------------------------------------------------------------------------
1 | {
2 | "//@npmcli/template-oss": "This file is automatically added by @npmcli/template-oss. Do not edit.",
3 | "problemMatcher": [
4 | {
5 | "owner": "tap",
6 | "pattern": [
7 | {
8 | "regexp": "^\\s*not ok \\d+ - (.*)",
9 | "message": 1
10 | },
11 | {
12 | "regexp": "^\\s*---"
13 | },
14 | {
15 | "regexp": "^\\s*at:"
16 | },
17 | {
18 | "regexp": "^\\s*line:\\s*(\\d+)",
19 | "line": 1
20 | },
21 | {
22 | "regexp": "^\\s*column:\\s*(\\d+)",
23 | "column": 1
24 | },
25 | {
26 | "regexp": "^\\s*file:\\s*(.*)",
27 | "file": 1
28 | }
29 | ]
30 | }
31 | ]
32 | }
33 |
--------------------------------------------------------------------------------
/.github/settings.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | repository:
4 | allow_merge_commit: false
5 | allow_rebase_merge: true
6 | allow_squash_merge: true
7 | squash_merge_commit_title: PR_TITLE
8 | squash_merge_commit_message: PR_BODY
9 | delete_branch_on_merge: true
10 | enable_automated_security_fixes: true
11 | enable_vulnerability_alerts: true
12 |
13 | branches:
14 | - name: main
15 | protection:
16 | required_status_checks: null
17 | enforce_admins: true
18 | block_creations: true
19 | required_pull_request_reviews:
20 | required_approving_review_count: 1
21 | require_code_owner_reviews: true
22 | require_last_push_approval: true
23 | dismiss_stale_reviews: true
24 | restrictions:
25 | apps: []
26 | users: []
27 | teams: [ "cli-team" ]
28 |
--------------------------------------------------------------------------------
/.github/workflows/audit.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: Audit
4 |
5 | on:
6 | workflow_dispatch:
7 | schedule:
8 | # "At 08:00 UTC (01:00 PT) on Monday" https://crontab.guru/#0_8_*_*_1
9 | - cron: "0 8 * * 1"
10 |
11 | permissions:
12 | contents: read
13 |
14 | jobs:
15 | audit:
16 | name: Audit Dependencies
17 | if: github.repository_owner == 'npm'
18 | runs-on: ubuntu-latest
19 | defaults:
20 | run:
21 | shell: bash
22 | steps:
23 | - name: Checkout
24 | uses: actions/checkout@v4
25 | - name: Setup Git User
26 | run: |
27 | git config --global user.email "npm-cli+bot@github.com"
28 | git config --global user.name "npm CLI robot"
29 | - name: Setup Node
30 | uses: actions/setup-node@v4
31 | id: node
32 | with:
33 | node-version: 22.x
34 | check-latest: contains('22.x', '.x')
35 | - name: Install Latest npm
36 | uses: ./.github/actions/install-latest-npm
37 | with:
38 | node: ${{ steps.node.outputs.node-version }}
39 | - name: Install Dependencies
40 | run: npm i --ignore-scripts --no-audit --no-fund --package-lock
41 | - name: Run Production Audit
42 | run: npm audit --omit=dev
43 | - name: Run Full Audit
44 | run: npm audit --audit-level=none
45 |
--------------------------------------------------------------------------------
/.github/workflows/ci-release.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: CI - Release
4 |
5 | on:
6 | workflow_dispatch:
7 | inputs:
8 | ref:
9 | required: true
10 | type: string
11 | default: main
12 | workflow_call:
13 | inputs:
14 | ref:
15 | required: true
16 | type: string
17 | check-sha:
18 | required: true
19 | type: string
20 |
21 | permissions:
22 | contents: read
23 | checks: write
24 |
25 | jobs:
26 | lint-all:
27 | name: Lint All
28 | if: github.repository_owner == 'npm'
29 | runs-on: ubuntu-latest
30 | defaults:
31 | run:
32 | shell: bash
33 | steps:
34 | - name: Checkout
35 | uses: actions/checkout@v4
36 | with:
37 | ref: ${{ inputs.ref }}
38 | - name: Setup Git User
39 | run: |
40 | git config --global user.email "npm-cli+bot@github.com"
41 | git config --global user.name "npm CLI robot"
42 | - name: Create Check
43 | id: create-check
44 | if: ${{ inputs.check-sha }}
45 | uses: ./.github/actions/create-check
46 | with:
47 | name: "Lint All"
48 | token: ${{ secrets.GITHUB_TOKEN }}
49 | sha: ${{ inputs.check-sha }}
50 | - name: Setup Node
51 | uses: actions/setup-node@v4
52 | id: node
53 | with:
54 | node-version: 22.x
55 | check-latest: contains('22.x', '.x')
56 | - name: Install Latest npm
57 | uses: ./.github/actions/install-latest-npm
58 | with:
59 | node: ${{ steps.node.outputs.node-version }}
60 | - name: Install Dependencies
61 | run: npm i --ignore-scripts --no-audit --no-fund
62 | - name: Lint
63 | run: npm run lint --ignore-scripts
64 | - name: Post Lint
65 | run: npm run postlint --ignore-scripts
66 | - name: Conclude Check
67 | uses: LouisBrunner/checks-action@v1.6.0
68 | if: steps.create-check.outputs.check-id && always()
69 | with:
70 | token: ${{ secrets.GITHUB_TOKEN }}
71 | conclusion: ${{ job.status }}
72 | check_id: ${{ steps.create-check.outputs.check-id }}
73 |
74 | test-all:
75 | name: Test All - ${{ matrix.platform.name }} - ${{ matrix.node-version }}
76 | if: github.repository_owner == 'npm'
77 | strategy:
78 | fail-fast: false
79 | matrix:
80 | platform:
81 | - name: Linux
82 | os: ubuntu-latest
83 | shell: bash
84 | - name: macOS
85 | os: macos-latest
86 | shell: bash
87 | - name: macOS
88 | os: macos-13
89 | shell: bash
90 | node-version:
91 | - 18.17.0
92 | - 18.x
93 | - 20.5.0
94 | - 20.x
95 | - 22.x
96 | exclude:
97 | - platform: { name: macOS, os: macos-13, shell: bash }
98 | node-version: 18.17.0
99 | - platform: { name: macOS, os: macos-13, shell: bash }
100 | node-version: 18.x
101 | - platform: { name: macOS, os: macos-13, shell: bash }
102 | node-version: 20.5.0
103 | - platform: { name: macOS, os: macos-13, shell: bash }
104 | node-version: 20.x
105 | - platform: { name: macOS, os: macos-13, shell: bash }
106 | node-version: 22.x
107 | runs-on: ${{ matrix.platform.os }}
108 | defaults:
109 | run:
110 | shell: ${{ matrix.platform.shell }}
111 | steps:
112 | - name: Checkout
113 | uses: actions/checkout@v4
114 | with:
115 | ref: ${{ inputs.ref }}
116 | - name: Setup Git User
117 | run: |
118 | git config --global user.email "npm-cli+bot@github.com"
119 | git config --global user.name "npm CLI robot"
120 | - name: Create Check
121 | id: create-check
122 | if: ${{ inputs.check-sha }}
123 | uses: ./.github/actions/create-check
124 | with:
125 | name: "Test All - ${{ matrix.platform.name }} - ${{ matrix.node-version }}"
126 | token: ${{ secrets.GITHUB_TOKEN }}
127 | sha: ${{ inputs.check-sha }}
128 | - name: Setup Node
129 | uses: actions/setup-node@v4
130 | id: node
131 | with:
132 | node-version: ${{ matrix.node-version }}
133 | check-latest: contains(matrix.node-version, '.x')
134 | - name: Install Latest npm
135 | uses: ./.github/actions/install-latest-npm
136 | with:
137 | node: ${{ steps.node.outputs.node-version }}
138 | - name: Install Dependencies
139 | run: npm i --ignore-scripts --no-audit --no-fund
140 | - name: Add Problem Matcher
141 | run: echo "::add-matcher::.github/matchers/tap.json"
142 | - name: Test
143 | run: npm test --ignore-scripts
144 | - name: Conclude Check
145 | uses: LouisBrunner/checks-action@v1.6.0
146 | if: steps.create-check.outputs.check-id && always()
147 | with:
148 | token: ${{ secrets.GITHUB_TOKEN }}
149 | conclusion: ${{ job.status }}
150 | check_id: ${{ steps.create-check.outputs.check-id }}
151 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: CI
4 |
5 | on:
6 | workflow_dispatch:
7 | pull_request:
8 | push:
9 | branches:
10 | - main
11 | schedule:
12 | # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1
13 | - cron: "0 9 * * 1"
14 |
15 | permissions:
16 | contents: read
17 |
18 | jobs:
19 | lint:
20 | name: Lint
21 | if: github.repository_owner == 'npm'
22 | runs-on: ubuntu-latest
23 | defaults:
24 | run:
25 | shell: bash
26 | steps:
27 | - name: Checkout
28 | uses: actions/checkout@v4
29 | - name: Setup Git User
30 | run: |
31 | git config --global user.email "npm-cli+bot@github.com"
32 | git config --global user.name "npm CLI robot"
33 | - name: Setup Node
34 | uses: actions/setup-node@v4
35 | id: node
36 | with:
37 | node-version: 22.x
38 | check-latest: contains('22.x', '.x')
39 | - name: Install Latest npm
40 | uses: ./.github/actions/install-latest-npm
41 | with:
42 | node: ${{ steps.node.outputs.node-version }}
43 | - name: Install Dependencies
44 | run: npm i --ignore-scripts --no-audit --no-fund
45 | - name: Lint
46 | run: npm run lint --ignore-scripts
47 | - name: Post Lint
48 | run: npm run postlint --ignore-scripts
49 |
50 | test:
51 | name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }}
52 | if: github.repository_owner == 'npm'
53 | strategy:
54 | fail-fast: false
55 | matrix:
56 | platform:
57 | - name: Linux
58 | os: ubuntu-latest
59 | shell: bash
60 | - name: macOS
61 | os: macos-latest
62 | shell: bash
63 | - name: macOS
64 | os: macos-13
65 | shell: bash
66 | node-version:
67 | - 18.17.0
68 | - 18.x
69 | - 20.5.0
70 | - 20.x
71 | - 22.x
72 | exclude:
73 | - platform: { name: macOS, os: macos-13, shell: bash }
74 | node-version: 18.17.0
75 | - platform: { name: macOS, os: macos-13, shell: bash }
76 | node-version: 18.x
77 | - platform: { name: macOS, os: macos-13, shell: bash }
78 | node-version: 20.5.0
79 | - platform: { name: macOS, os: macos-13, shell: bash }
80 | node-version: 20.x
81 | - platform: { name: macOS, os: macos-13, shell: bash }
82 | node-version: 22.x
83 | runs-on: ${{ matrix.platform.os }}
84 | defaults:
85 | run:
86 | shell: ${{ matrix.platform.shell }}
87 | steps:
88 | - name: Checkout
89 | uses: actions/checkout@v4
90 | - name: Setup Git User
91 | run: |
92 | git config --global user.email "npm-cli+bot@github.com"
93 | git config --global user.name "npm CLI robot"
94 | - name: Setup Node
95 | uses: actions/setup-node@v4
96 | id: node
97 | with:
98 | node-version: ${{ matrix.node-version }}
99 | check-latest: contains(matrix.node-version, '.x')
100 | - name: Install Latest npm
101 | uses: ./.github/actions/install-latest-npm
102 | with:
103 | node: ${{ steps.node.outputs.node-version }}
104 | - name: Install Dependencies
105 | run: npm i --ignore-scripts --no-audit --no-fund
106 | - name: Add Problem Matcher
107 | run: echo "::add-matcher::.github/matchers/tap.json"
108 | - name: Test
109 | run: npm test --ignore-scripts
110 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: CodeQL
4 |
5 | on:
6 | push:
7 | branches:
8 | - main
9 | pull_request:
10 | branches:
11 | - main
12 | schedule:
13 | # "At 10:00 UTC (03:00 PT) on Monday" https://crontab.guru/#0_10_*_*_1
14 | - cron: "0 10 * * 1"
15 |
16 | permissions:
17 | contents: read
18 |
19 | jobs:
20 | analyze:
21 | name: Analyze
22 | runs-on: ubuntu-latest
23 | permissions:
24 | actions: read
25 | contents: read
26 | security-events: write
27 | steps:
28 | - name: Checkout
29 | uses: actions/checkout@v4
30 | - name: Setup Git User
31 | run: |
32 | git config --global user.email "npm-cli+bot@github.com"
33 | git config --global user.name "npm CLI robot"
34 | - name: Initialize CodeQL
35 | uses: github/codeql-action/init@v3
36 | with:
37 | languages: javascript
38 | - name: Perform CodeQL Analysis
39 | uses: github/codeql-action/analyze@v3
40 |
--------------------------------------------------------------------------------
/.github/workflows/post-dependabot.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: Post Dependabot
4 |
5 | on: pull_request
6 |
7 | permissions:
8 | contents: write
9 |
10 | jobs:
11 | template-oss:
12 | name: template-oss
13 | if: github.repository_owner == 'npm' && github.actor == 'dependabot[bot]'
14 | runs-on: ubuntu-latest
15 | defaults:
16 | run:
17 | shell: bash
18 | steps:
19 | - name: Checkout
20 | uses: actions/checkout@v4
21 | with:
22 | ref: ${{ github.event.pull_request.head.ref }}
23 | - name: Setup Git User
24 | run: |
25 | git config --global user.email "npm-cli+bot@github.com"
26 | git config --global user.name "npm CLI robot"
27 | - name: Setup Node
28 | uses: actions/setup-node@v4
29 | id: node
30 | with:
31 | node-version: 22.x
32 | check-latest: contains('22.x', '.x')
33 | - name: Install Latest npm
34 | uses: ./.github/actions/install-latest-npm
35 | with:
36 | node: ${{ steps.node.outputs.node-version }}
37 | - name: Install Dependencies
38 | run: npm i --ignore-scripts --no-audit --no-fund
39 | - name: Fetch Dependabot Metadata
40 | id: metadata
41 | uses: dependabot/fetch-metadata@v1
42 | with:
43 | github-token: ${{ secrets.GITHUB_TOKEN }}
44 |
45 | # Dependabot can update multiple directories so we output which directory
46 | # it is acting on so we can run the command for the correct root or workspace
47 | - name: Get Dependabot Directory
48 | if: contains(steps.metadata.outputs.dependency-names, '@npmcli/template-oss')
49 | id: flags
50 | run: |
51 | dependabot_dir="${{ steps.metadata.outputs.directory }}"
52 | if [[ "$dependabot_dir" == "/" || "$dependabot_dir" == "/main" ]]; then
53 | echo "workspace=-iwr" >> $GITHUB_OUTPUT
54 | else
55 | # strip leading slash from directory so it works as a
56 | # a path to the workspace flag
57 | echo "workspace=-w ${dependabot_dir#/}" >> $GITHUB_OUTPUT
58 | fi
59 |
60 | - name: Apply Changes
61 | if: steps.flags.outputs.workspace
62 | id: apply
63 | run: |
64 | npm run template-oss-apply ${{ steps.flags.outputs.workspace }}
65 | if [[ `git status --porcelain` ]]; then
66 | echo "changes=true" >> $GITHUB_OUTPUT
67 | fi
68 | # This only sets the conventional commit prefix. This workflow can't reliably determine
69 | # what the breaking change is though. If a BREAKING CHANGE message is required then
70 | # this PR check will fail and the commit will be amended with stafftools
71 | if [[ "${{ steps.metadata.outputs.update-type }}" == "version-update:semver-major" ]]; then
72 | prefix='feat!'
73 | else
74 | prefix='chore'
75 | fi
76 | echo "message=$prefix: postinstall for dependabot template-oss PR" >> $GITHUB_OUTPUT
77 |
78 | # This step will fail if template-oss has made any workflow updates. It is impossible
79 | # for a workflow to update other workflows. In the case it does fail, we continue
80 | # and then try to apply only a portion of the changes in the next step
81 | - name: Push All Changes
82 | if: steps.apply.outputs.changes
83 | id: push
84 | continue-on-error: true
85 | env:
86 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
87 | run: |
88 | git commit -am "${{ steps.apply.outputs.message }}"
89 | git push
90 |
91 | # If the previous step failed, then reset the commit and remove any workflow changes
92 | # and attempt to commit and push again. This is helpful because we will have a commit
93 | # with the correct prefix that we can then --amend with @npmcli/stafftools later.
94 | - name: Push All Changes Except Workflows
95 | if: steps.apply.outputs.changes && steps.push.outcome == 'failure'
96 | env:
97 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
98 | run: |
99 | git reset HEAD~
100 | git checkout HEAD -- .github/workflows/
101 | git clean -fd .github/workflows/
102 | git commit -am "${{ steps.apply.outputs.message }}"
103 | git push
104 |
105 | # Check if all the necessary template-oss changes were applied. Since we continued
106 | # on errors in one of the previous steps, this check will fail if our follow up
107 | # only applied a portion of the changes and we need to followup manually.
108 | #
109 | # Note that this used to run `lint` and `postlint` but that will fail this action
110 | # if we've also shipped any linting changes separate from template-oss. We do
111 | # linting in another action, so we want to fail this one only if there are
112 | # template-oss changes that could not be applied.
113 | - name: Check Changes
114 | if: steps.apply.outputs.changes
115 | run: |
116 | npm exec --offline ${{ steps.flags.outputs.workspace }} -- template-oss-check
117 |
118 | - name: Fail on Breaking Change
119 | if: steps.apply.outputs.changes && startsWith(steps.apply.outputs.message, 'feat!')
120 | run: |
121 | echo "This PR has a breaking change. Run 'npx -p @npmcli/stafftools gh template-oss-fix'"
122 | echo "for more information on how to fix this with a BREAKING CHANGE footer."
123 | exit 1
124 |
--------------------------------------------------------------------------------
/.github/workflows/pull-request.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: Pull Request
4 |
5 | on:
6 | pull_request:
7 | types:
8 | - opened
9 | - reopened
10 | - edited
11 | - synchronize
12 |
13 | permissions:
14 | contents: read
15 |
16 | jobs:
17 | commitlint:
18 | name: Lint Commits
19 | if: github.repository_owner == 'npm'
20 | runs-on: ubuntu-latest
21 | defaults:
22 | run:
23 | shell: bash
24 | steps:
25 | - name: Checkout
26 | uses: actions/checkout@v4
27 | with:
28 | fetch-depth: 0
29 | - name: Setup Git User
30 | run: |
31 | git config --global user.email "npm-cli+bot@github.com"
32 | git config --global user.name "npm CLI robot"
33 | - name: Setup Node
34 | uses: actions/setup-node@v4
35 | id: node
36 | with:
37 | node-version: 22.x
38 | check-latest: contains('22.x', '.x')
39 | - name: Install Latest npm
40 | uses: ./.github/actions/install-latest-npm
41 | with:
42 | node: ${{ steps.node.outputs.node-version }}
43 | - name: Install Dependencies
44 | run: npm i --ignore-scripts --no-audit --no-fund
45 | - name: Run Commitlint on Commits
46 | id: commit
47 | continue-on-error: true
48 | run: npx --offline commitlint -V --from 'origin/${{ github.base_ref }}' --to ${{ github.event.pull_request.head.sha }}
49 | - name: Run Commitlint on PR Title
50 | if: steps.commit.outcome == 'failure'
51 | env:
52 | PR_TITLE: ${{ github.event.pull_request.title }}
53 | run: echo "$PR_TITLE" | npx --offline commitlint -V
54 |
--------------------------------------------------------------------------------
/.github/workflows/release-integration.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: Release Integration
4 |
5 | on:
6 | workflow_dispatch:
7 | inputs:
8 | releases:
9 | required: true
10 | type: string
11 | description: 'A json array of releases. Required fields: publish: tagName, publishTag. publish check: pkgName, version'
12 | workflow_call:
13 | inputs:
14 | releases:
15 | required: true
16 | type: string
17 | description: 'A json array of releases. Required fields: publish: tagName, publishTag. publish check: pkgName, version'
18 | secrets:
19 | PUBLISH_TOKEN:
20 | required: true
21 |
22 | permissions:
23 | contents: read
24 | id-token: write
25 |
26 | jobs:
27 | publish:
28 | name: Publish
29 | runs-on: ubuntu-latest
30 | defaults:
31 | run:
32 | shell: bash
33 | permissions:
34 | id-token: write
35 | steps:
36 | - name: Checkout
37 | uses: actions/checkout@v4
38 | with:
39 | ref: ${{ fromJSON(inputs.releases)[0].tagName }}
40 | - name: Setup Git User
41 | run: |
42 | git config --global user.email "npm-cli+bot@github.com"
43 | git config --global user.name "npm CLI robot"
44 | - name: Setup Node
45 | uses: actions/setup-node@v4
46 | id: node
47 | with:
48 | node-version: 22.x
49 | check-latest: contains('22.x', '.x')
50 | - name: Install Latest npm
51 | uses: ./.github/actions/install-latest-npm
52 | with:
53 | node: ${{ steps.node.outputs.node-version }}
54 | - name: Install Dependencies
55 | run: npm i --ignore-scripts --no-audit --no-fund
56 | - name: Set npm authToken
57 | run: npm config set '//registry.npmjs.org/:_authToken'=\${PUBLISH_TOKEN}
58 | - name: Publish
59 | env:
60 | PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }}
61 | RELEASES: ${{ inputs.releases }}
62 | run: |
63 | EXIT_CODE=0
64 |
65 | for release in $(echo $RELEASES | jq -r '.[] | @base64'); do
66 | PUBLISH_TAG=$(echo "$release" | base64 --decode | jq -r .publishTag)
67 | npm publish --provenance --tag="$PUBLISH_TAG"
68 | STATUS=$?
69 | if [[ "$STATUS" -eq 1 ]]; then
70 | EXIT_CODE=$STATUS
71 | fi
72 | done
73 |
74 | exit $EXIT_CODE
75 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | name: Release
4 |
5 | on:
6 | push:
7 | branches:
8 | - main
9 |
10 | permissions:
11 | contents: write
12 | pull-requests: write
13 | checks: write
14 |
15 | jobs:
16 | release:
17 | outputs:
18 | pr: ${{ steps.release.outputs.pr }}
19 | pr-branch: ${{ steps.release.outputs.pr-branch }}
20 | pr-number: ${{ steps.release.outputs.pr-number }}
21 | pr-sha: ${{ steps.release.outputs.pr-sha }}
22 | releases: ${{ steps.release.outputs.releases }}
23 | comment-id: ${{ steps.create-comment.outputs.comment-id || steps.update-comment.outputs.comment-id }}
24 | check-id: ${{ steps.create-check.outputs.check-id }}
25 | name: Release
26 | if: github.repository_owner == 'npm'
27 | runs-on: ubuntu-latest
28 | defaults:
29 | run:
30 | shell: bash
31 | steps:
32 | - name: Checkout
33 | uses: actions/checkout@v4
34 | - name: Setup Git User
35 | run: |
36 | git config --global user.email "npm-cli+bot@github.com"
37 | git config --global user.name "npm CLI robot"
38 | - name: Setup Node
39 | uses: actions/setup-node@v4
40 | id: node
41 | with:
42 | node-version: 22.x
43 | check-latest: contains('22.x', '.x')
44 | - name: Install Latest npm
45 | uses: ./.github/actions/install-latest-npm
46 | with:
47 | node: ${{ steps.node.outputs.node-version }}
48 | - name: Install Dependencies
49 | run: npm i --ignore-scripts --no-audit --no-fund
50 | - name: Release Please
51 | id: release
52 | env:
53 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
54 | run: npx --offline template-oss-release-please --branch="${{ github.ref_name }}" --backport="" --defaultTag="latest"
55 | - name: Create Release Manager Comment Text
56 | if: steps.release.outputs.pr-number
57 | uses: actions/github-script@v7
58 | id: comment-text
59 | with:
60 | result-encoding: string
61 | script: |
62 | const { runId, repo: { owner, repo } } = context
63 | const { data: workflow } = await github.rest.actions.getWorkflowRun({ owner, repo, run_id: runId })
64 | return['## Release Manager', `Release workflow run: ${workflow.html_url}`].join('\n\n')
65 | - name: Find Release Manager Comment
66 | uses: peter-evans/find-comment@v2
67 | if: steps.release.outputs.pr-number
68 | id: found-comment
69 | with:
70 | issue-number: ${{ steps.release.outputs.pr-number }}
71 | comment-author: 'github-actions[bot]'
72 | body-includes: '## Release Manager'
73 | - name: Create Release Manager Comment
74 | id: create-comment
75 | if: steps.release.outputs.pr-number && !steps.found-comment.outputs.comment-id
76 | uses: peter-evans/create-or-update-comment@v3
77 | with:
78 | issue-number: ${{ steps.release.outputs.pr-number }}
79 | body: ${{ steps.comment-text.outputs.result }}
80 | - name: Update Release Manager Comment
81 | id: update-comment
82 | if: steps.release.outputs.pr-number && steps.found-comment.outputs.comment-id
83 | uses: peter-evans/create-or-update-comment@v3
84 | with:
85 | comment-id: ${{ steps.found-comment.outputs.comment-id }}
86 | body: ${{ steps.comment-text.outputs.result }}
87 | edit-mode: 'replace'
88 | - name: Create Check
89 | id: create-check
90 | uses: ./.github/actions/create-check
91 | if: steps.release.outputs.pr-sha
92 | with:
93 | name: "Release"
94 | token: ${{ secrets.GITHUB_TOKEN }}
95 | sha: ${{ steps.release.outputs.pr-sha }}
96 |
97 | update:
98 | needs: release
99 | outputs:
100 | sha: ${{ steps.commit.outputs.sha }}
101 | check-id: ${{ steps.create-check.outputs.check-id }}
102 | name: Update - Release
103 | if: github.repository_owner == 'npm' && needs.release.outputs.pr
104 | runs-on: ubuntu-latest
105 | defaults:
106 | run:
107 | shell: bash
108 | steps:
109 | - name: Checkout
110 | uses: actions/checkout@v4
111 | with:
112 | fetch-depth: 0
113 | ref: ${{ needs.release.outputs.pr-branch }}
114 | - name: Setup Git User
115 | run: |
116 | git config --global user.email "npm-cli+bot@github.com"
117 | git config --global user.name "npm CLI robot"
118 | - name: Setup Node
119 | uses: actions/setup-node@v4
120 | id: node
121 | with:
122 | node-version: 22.x
123 | check-latest: contains('22.x', '.x')
124 | - name: Install Latest npm
125 | uses: ./.github/actions/install-latest-npm
126 | with:
127 | node: ${{ steps.node.outputs.node-version }}
128 | - name: Install Dependencies
129 | run: npm i --ignore-scripts --no-audit --no-fund
130 | - name: Create Release Manager Checklist Text
131 | id: comment-text
132 | env:
133 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
134 | run: npm exec --offline -- template-oss-release-manager --pr="${{ needs.release.outputs.pr-number }}" --backport="" --defaultTag="latest" --publish
135 | - name: Append Release Manager Comment
136 | uses: peter-evans/create-or-update-comment@v3
137 | with:
138 | comment-id: ${{ needs.release.outputs.comment-id }}
139 | body: ${{ steps.comment-text.outputs.result }}
140 | edit-mode: 'append'
141 | - name: Run Post Pull Request Actions
142 | env:
143 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
144 | run: npm run rp-pull-request --ignore-scripts --if-present -- --pr="${{ needs.release.outputs.pr-number }}" --commentId="${{ needs.release.outputs.comment-id }}"
145 | - name: Commit
146 | id: commit
147 | env:
148 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
149 | run: |
150 | git commit --all --amend --no-edit || true
151 | git push --force-with-lease
152 | echo "sha=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
153 | - name: Create Check
154 | id: create-check
155 | uses: ./.github/actions/create-check
156 | with:
157 | name: "Update - Release"
158 | check-name: "Release"
159 | token: ${{ secrets.GITHUB_TOKEN }}
160 | sha: ${{ steps.commit.outputs.sha }}
161 | - name: Conclude Check
162 | uses: LouisBrunner/checks-action@v1.6.0
163 | with:
164 | token: ${{ secrets.GITHUB_TOKEN }}
165 | conclusion: ${{ job.status }}
166 | check_id: ${{ needs.release.outputs.check-id }}
167 |
168 | ci:
169 | name: CI - Release
170 | needs: [ release, update ]
171 | if: needs.release.outputs.pr
172 | uses: ./.github/workflows/ci-release.yml
173 | with:
174 | ref: ${{ needs.release.outputs.pr-branch }}
175 | check-sha: ${{ needs.update.outputs.sha }}
176 |
177 | post-ci:
178 | needs: [ release, update, ci ]
179 | name: Post CI - Release
180 | if: github.repository_owner == 'npm' && needs.release.outputs.pr && always()
181 | runs-on: ubuntu-latest
182 | defaults:
183 | run:
184 | shell: bash
185 | steps:
186 | - name: Get CI Conclusion
187 | id: conclusion
188 | run: |
189 | result=""
190 | if [[ "${{ contains(needs.*.result, 'failure') }}" == "true" ]]; then
191 | result="failure"
192 | elif [[ "${{ contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
193 | result="cancelled"
194 | else
195 | result="success"
196 | fi
197 | echo "result=$result" >> $GITHUB_OUTPUT
198 | - name: Conclude Check
199 | uses: LouisBrunner/checks-action@v1.6.0
200 | with:
201 | token: ${{ secrets.GITHUB_TOKEN }}
202 | conclusion: ${{ steps.conclusion.outputs.result }}
203 | check_id: ${{ needs.update.outputs.check-id }}
204 |
205 | post-release:
206 | needs: release
207 | outputs:
208 | comment-id: ${{ steps.create-comment.outputs.comment-id }}
209 | name: Post Release - Release
210 | if: github.repository_owner == 'npm' && needs.release.outputs.releases
211 | runs-on: ubuntu-latest
212 | defaults:
213 | run:
214 | shell: bash
215 | steps:
216 | - name: Create Release PR Comment Text
217 | id: comment-text
218 | uses: actions/github-script@v7
219 | env:
220 | RELEASES: ${{ needs.release.outputs.releases }}
221 | with:
222 | result-encoding: string
223 | script: |
224 | const releases = JSON.parse(process.env.RELEASES)
225 | const { runId, repo: { owner, repo } } = context
226 | const issue_number = releases[0].prNumber
227 | const runUrl = `https://github.com/${owner}/${repo}/actions/runs/${runId}`
228 |
229 | return [
230 | '## Release Workflow\n',
231 | ...releases.map(r => `- \`${r.pkgName}@${r.version}\` ${r.url}`),
232 | `- Workflow run: :arrows_counterclockwise: ${runUrl}`,
233 | ].join('\n')
234 | - name: Create Release PR Comment
235 | id: create-comment
236 | uses: peter-evans/create-or-update-comment@v3
237 | with:
238 | issue-number: ${{ fromJSON(needs.release.outputs.releases)[0].prNumber }}
239 | body: ${{ steps.comment-text.outputs.result }}
240 |
241 | release-integration:
242 | needs: release
243 | name: Release Integration
244 | if: needs.release.outputs.releases
245 | uses: ./.github/workflows/release-integration.yml
246 | permissions:
247 | contents: read
248 | id-token: write
249 | secrets:
250 | PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }}
251 | with:
252 | releases: ${{ needs.release.outputs.releases }}
253 |
254 | post-release-integration:
255 | needs: [ release, release-integration, post-release ]
256 | name: Post Release Integration - Release
257 | if: github.repository_owner == 'npm' && needs.release.outputs.releases && always()
258 | runs-on: ubuntu-latest
259 | defaults:
260 | run:
261 | shell: bash
262 | steps:
263 | - name: Get Post Release Conclusion
264 | id: conclusion
265 | run: |
266 | if [[ "${{ contains(needs.*.result, 'failure') }}" == "true" ]]; then
267 | result="x"
268 | elif [[ "${{ contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
269 | result="heavy_multiplication_x"
270 | else
271 | result="white_check_mark"
272 | fi
273 | echo "result=$result" >> $GITHUB_OUTPUT
274 | - name: Find Release PR Comment
275 | uses: peter-evans/find-comment@v2
276 | id: found-comment
277 | with:
278 | issue-number: ${{ fromJSON(needs.release.outputs.releases)[0].prNumber }}
279 | comment-author: 'github-actions[bot]'
280 | body-includes: '## Release Workflow'
281 | - name: Create Release PR Comment Text
282 | id: comment-text
283 | if: steps.found-comment.outputs.comment-id
284 | uses: actions/github-script@v7
285 | env:
286 | RESULT: ${{ steps.conclusion.outputs.result }}
287 | BODY: ${{ steps.found-comment.outputs.comment-body }}
288 | with:
289 | result-encoding: string
290 | script: |
291 | const { RESULT, BODY } = process.env
292 | const body = [BODY.replace(/(Workflow run: :)[a-z_]+(:)/, `$1${RESULT}$2`)]
293 | if (RESULT !== 'white_check_mark') {
294 | body.push(':rotating_light::rotating_light::rotating_light:')
295 | body.push([
296 | '@npm/cli-team: The post-release workflow failed for this release.',
297 | 'Manual steps may need to be taken after examining the workflow output.'
298 | ].join(' '))
299 | body.push(':rotating_light::rotating_light::rotating_light:')
300 | }
301 | return body.join('\n\n').trim()
302 | - name: Update Release PR Comment
303 | if: steps.comment-text.outputs.result
304 | uses: peter-evans/create-or-update-comment@v3
305 | with:
306 | comment-id: ${{ steps.found-comment.outputs.comment-id }}
307 | body: ${{ steps.comment-text.outputs.result }}
308 | edit-mode: 'replace'
309 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | # ignore everything in the root
4 | /*
5 |
6 | !**/.gitignore
7 | !/.commitlintrc.js
8 | !/.eslint.config.js
9 | !/.eslintrc.js
10 | !/.eslintrc.local.*
11 | !/.git-blame-ignore-revs
12 | !/.github/
13 | !/.gitignore
14 | !/.npmrc
15 | !/.prettierignore
16 | !/.prettierrc.js
17 | !/.release-please-manifest.json
18 | !/bin/
19 | !/CHANGELOG*
20 | !/CODE_OF_CONDUCT.md
21 | !/CONTRIBUTING.md
22 | !/docs/
23 | !/lib/
24 | !/LICENSE*
25 | !/map.js
26 | !/package.json
27 | !/README*
28 | !/release-please-config.json
29 | !/scripts/
30 | !/SECURITY.md
31 | !/tap-snapshots/
32 | !/test/
33 | !/tsconfig.json
34 | tap-testdir*/
35 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | ; This file is automatically added by @npmcli/template-oss. Do not edit.
2 |
3 | package-lock=false
4 |
--------------------------------------------------------------------------------
/.release-please-manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | ".": "6.0.0"
3 | }
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## [6.0.0](https://github.com/npm/write-file-atomic/compare/v5.0.1...v6.0.0) (2024-09-24)
4 | ### ⚠️ BREAKING CHANGES
5 | * `write-file-atomic` now supports node `^18.17.0 || >=20.5.0`
6 | ### Bug Fixes
7 | * [`e4db381`](https://github.com/npm/write-file-atomic/commit/e4db381db11ad66e2eba47a801b5fe279923057f) [#208](https://github.com/npm/write-file-atomic/pull/208) align to npm 10 node engine range (@hashtagchris)
8 | ### Chores
9 | * [`384ec4c`](https://github.com/npm/write-file-atomic/commit/384ec4c4008cf66b9863999c7b4e0554109968bc) [#208](https://github.com/npm/write-file-atomic/pull/208) run template-oss-apply (@hashtagchris)
10 | * [`1a8883d`](https://github.com/npm/write-file-atomic/commit/1a8883d94a97bef3addf7d77300720f3aacfabbe) [#206](https://github.com/npm/write-file-atomic/pull/206) bump @npmcli/eslint-config from 4.0.5 to 5.0.0 (@dependabot[bot])
11 | * [`73bddd9`](https://github.com/npm/write-file-atomic/commit/73bddd9db182f7a9ec1475a311c57844b4b3f05f) [#194](https://github.com/npm/write-file-atomic/pull/194) linting: no-unused-vars (@lukekarrys)
12 | * [`4a16903`](https://github.com/npm/write-file-atomic/commit/4a169033af04227a898ac14cd90b3358a8d4d37e) [#194](https://github.com/npm/write-file-atomic/pull/194) bump @npmcli/template-oss to 4.22.0 (@lukekarrys)
13 | * [`944e6c2`](https://github.com/npm/write-file-atomic/commit/944e6c2e9d01389514b540e4effa4cc1d786510a) [#207](https://github.com/npm/write-file-atomic/pull/207) postinstall for dependabot template-oss PR (@hashtagchris)
14 | * [`c2c17b7`](https://github.com/npm/write-file-atomic/commit/c2c17b7a9297215cde6bb3c80691563193b986d3) [#207](https://github.com/npm/write-file-atomic/pull/207) bump @npmcli/template-oss from 4.23.1 to 4.23.3 (@dependabot[bot])
15 |
16 | ## [5.0.1](https://github.com/npm/write-file-atomic/compare/v5.0.0...v5.0.1) (2023-04-26)
17 |
18 | ### Dependencies
19 |
20 | * [`a0daf64`](https://github.com/npm/write-file-atomic/commit/a0daf642b441f3026de36f8d10dae24e46b34f01) [#157](https://github.com/npm/write-file-atomic/pull/157) bump signal-exit from 3.0.7 to 4.0.1 (#157)
21 |
22 | ## [5.0.0](https://github.com/npm/write-file-atomic/compare/v4.0.2...v5.0.0) (2022-10-10)
23 |
24 | ### ⚠️ BREAKING CHANGES
25 |
26 | * `write-file-atomic` is now compatible with the following semver range for node: `^14.17.0 || ^16.13.0 || >=18.0.0`
27 |
28 | ### Features
29 |
30 | * [`5506c07`](https://github.com/npm/write-file-atomic/commit/5506c076c0421ef2e4ddfc4ee5ed2be5adc809e7) [#122](https://github.com/npm/write-file-atomic/pull/122) postinstall for dependabot template-oss PR (@lukekarrys)
31 |
32 | ## [4.0.2](https://github.com/npm/write-file-atomic/compare/v4.0.1...v4.0.2) (2022-08-16)
33 |
34 |
35 | ### Bug Fixes
36 |
37 | * linting ([#111](https://github.com/npm/write-file-atomic/issues/111)) ([c8ef004](https://github.com/npm/write-file-atomic/commit/c8ef00406ff21056adae06a9b8186d37031d8a95))
38 |
39 | ### [4.0.1](https://www.github.com/npm/write-file-atomic/compare/v4.0.0...v4.0.1) (2022-02-09)
40 |
41 |
42 | ### Bug Fixes
43 |
44 | * 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))
45 | * remove is-typedarray and typedarray-to-buffer ([625526e](https://www.github.com/npm/write-file-atomic/commit/625526e1f190d2599a267839e995b768cf3f69b6))
46 |
47 |
48 | ### Dependencies
49 |
50 | * update signal-exit requirement from ^3.0.2 to ^3.0.7 ([0b3ffdb](https://www.github.com/npm/write-file-atomic/commit/0b3ffdb4534b254ac5de8acf02e5b4591e2d92b4))
51 |
52 | ## [4.0.0](https://www.github.com/npm/write-file-atomic/compare/v3.0.3...v4.0.0) (2022-01-18)
53 |
54 |
55 | ### ⚠ BREAKING CHANGES
56 |
57 | * This drops support for node10 and non-LTS versions of node12 and node14
58 |
59 | ### Bug Fixes
60 |
61 | * move to template-oss ([266833d](https://www.github.com/npm/write-file-atomic/commit/266833d868b7626227d25dfbfa694798770bc811))
62 |
63 |
64 | ### dependencies
65 |
66 | * typedarray-to-buffer@4.0.0 ([f36ff4f](https://www.github.com/npm/write-file-atomic/commit/f36ff4f5bc21178885f53768268fd9d8b0ba0729))
67 |
68 |
69 | ### Documentation
70 |
71 | * **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))
72 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | All interactions in this repo are covered by the [npm Code of
4 | Conduct](https://docs.npmjs.com/policies/conduct)
5 |
6 | The npm cli team may, at its own discretion, moderate, remove, or edit
7 | any interactions such as pull requests, issues, and comments.
8 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Contributing
4 |
5 | ## Code of Conduct
6 |
7 | All interactions in the **npm** organization on GitHub are considered to be covered by our standard [Code of Conduct](https://docs.npmjs.com/policies/conduct).
8 |
9 | ## Reporting Bugs
10 |
11 | Before submitting a new bug report please search for an existing or similar report.
12 |
13 | Use one of our existing issue templates if you believe you've come across a unique problem.
14 |
15 | Duplicate issues, or issues that don't use one of our templates may get closed without a response.
16 |
17 | ## Pull Request Conventions
18 |
19 | ### Commits
20 |
21 | We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).
22 |
23 | When opening a pull request please be sure that either the pull request title, or each commit in the pull request, has one of the following prefixes:
24 |
25 | - `feat`: For when introducing a new feature. The result will be a new semver minor version of the package when it is next published.
26 | - `fix`: For bug fixes. The result will be a new semver patch version of the package when it is next published.
27 | - `docs`: For documentation updates. The result will be a new semver patch version of the package when it is next published.
28 | - `chore`: For changes that do not affect the published module. Often these are changes to tests. The result will be *no* change to the version of the package when it is next published (as the commit does not affect the published version).
29 |
30 | ### Test Coverage
31 |
32 | Pull requests made against this repo will run `npm test` automatically. Please make sure tests pass locally before submitting a PR.
33 |
34 | Every new feature or bug fix should come with a corresponding test or tests that validate the solutions. Testing also reports on code coverage and will fail if code coverage drops.
35 |
36 | ### Linting
37 |
38 | Linting is also done automatically once tests pass. `npm run lintfix` will fix most linting errors automatically.
39 |
40 | Please make sure linting passes before submitting a PR.
41 |
42 | ## What _not_ to contribute?
43 |
44 | ### Dependencies
45 |
46 | It should be noted that our team does not accept third-party dependency updates/PRs. If you submit a PR trying to update our dependencies we will close it with or without a reference to these contribution guidelines.
47 |
48 | ### Tools/Automation
49 |
50 | Our core team is responsible for the maintenance of the tooling/automation in this project and we ask contributors to not make changes to these when contributing (e.g. `.github/*`, `.eslintrc.json`, `.licensee.json`). Most of those files also have a header at the top to remind folks they are automatically generated. Pull requests that alter these will not be accepted.
51 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015, Rebecca Turner
2 |
3 | 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.
4 |
5 | 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.
6 |
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | write-file-atomic
2 | -----------------
3 |
4 | This is an extension for node's `fs.writeFile` that makes its operation
5 | atomic and allows you set ownership (uid/gid of the file).
6 |
7 | ### `writeFileAtomic(filename, data, [options], [callback])`
8 |
9 | #### Description:
10 |
11 | Atomically and asynchronously writes data to a file, replacing the file if it already
12 | exists. data can be a string or a buffer.
13 |
14 | #### Options:
15 | * filename **String**
16 | * data **String** | **Buffer**
17 | * options **Object** | **String**
18 | * chown **Object** default, uid & gid of existing file, if any
19 | * uid **Number**
20 | * gid **Number**
21 | * encoding **String** | **Null** default = 'utf8'
22 | * fsync **Boolean** default = true
23 | * mode **Number** default, from existing file, if any
24 | * tmpfileCreated **Function** called when the tmpfile is created
25 | * callback **Function**
26 |
27 | #### Usage:
28 |
29 | ```js
30 | var writeFileAtomic = require('write-file-atomic')
31 | writeFileAtomic(filename, data, [options], [callback])
32 | ```
33 |
34 | The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`.
35 | Note that `require('worker_threads').threadId` is used in addition to `process.pid` if running inside of a worker thread.
36 | If writeFile completes successfully then, if passed the **chown** option it will change
37 | the ownership of the file. Finally it renames the file back to the filename you specified. If
38 | it encounters errors at any of these steps it will attempt to unlink the temporary file and then
39 | pass the error back to the caller.
40 | 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.
41 |
42 | If provided, the **chown** option requires both **uid** and **gid** properties or else
43 | you'll get an error. If **chown** is not specified it will default to using
44 | the owner of the previous file. To prevent chown from being ran you can
45 | also pass `false`, in which case the file will be created with the current user's credentials.
46 |
47 | If **mode** is not specified, it will default to using the permissions from
48 | an existing file, if any. Expicitly setting this to `false` remove this default, resulting
49 | in a file created with the system default permissions.
50 |
51 | 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'.
52 |
53 | If the **fsync** option is **false**, writeFile will skip the final fsync call.
54 |
55 | If the **tmpfileCreated** option is specified it will be called with the name of the tmpfile when created.
56 |
57 | Example:
58 |
59 | ```javascript
60 | writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}, function (err) {
61 | if (err) throw err;
62 | console.log('It\'s saved!');
63 | });
64 | ```
65 |
66 | This function also supports async/await:
67 |
68 | ```javascript
69 | (async () => {
70 | try {
71 | await writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}});
72 | console.log('It\'s saved!');
73 | } catch (err) {
74 | console.error(err);
75 | process.exit(1);
76 | }
77 | })();
78 | ```
79 |
80 | ### `writeFileAtomicSync(filename, data, [options])`
81 |
82 | #### Description:
83 |
84 | The synchronous version of **writeFileAtomic**.
85 |
86 | #### Usage:
87 | ```js
88 | var writeFileAtomicSync = require('write-file-atomic').sync
89 | writeFileAtomicSync(filename, data, [options])
90 | ```
91 |
92 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | GitHub takes the security of our software products and services seriously, including the open source code repositories managed through our GitHub organizations, such as [GitHub](https://github.com/GitHub).
4 |
5 | If you believe you have found a security vulnerability in this GitHub-owned open source repository, you can report it to us in one of two ways.
6 |
7 | If the vulnerability you have found is *not* [in scope for the GitHub Bug Bounty Program](https://bounty.github.com/#scope) or if you do not wish to be considered for a bounty reward, please report the issue to us directly through [opensource-security@github.com](mailto:opensource-security@github.com).
8 |
9 | If the vulnerability you have found is [in scope for the GitHub Bug Bounty Program](https://bounty.github.com/#scope) and you would like for your finding to be considered for a bounty reward, please submit the vulnerability to us through [HackerOne](https://hackerone.com/github) in order to be eligible to receive a bounty award.
10 |
11 | **Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**
12 |
13 | Thanks for helping make GitHub safe for everyone.
14 |
--------------------------------------------------------------------------------
/docs/changelog-pre-4.0.0.md:
--------------------------------------------------------------------------------
1 | # 3.0.0
2 |
3 | * Implement options.tmpfileCreated callback.
4 | * Drop Node.js 6, modernize code, return Promise from async function.
5 | * Support write TypedArray's like in node fs.writeFile.
6 | * Remove graceful-fs dependency.
7 |
8 | # 2.4.3
9 |
10 | * Ignore errors raised by `fs.closeSync` when cleaning up after a write
11 | error.
12 |
13 | # 2.4.2
14 |
15 | * A pair of patches to fix some fd leaks. We would leak fds with sync use
16 | when errors occured and with async use any time fsync was not in use. (#34)
17 |
18 | # 2.4.1
19 |
20 | * Fix a bug where `signal-exit` instances would be leaked. This was fixed when addressing #35.
21 |
22 | # 2.4.0
23 |
24 | ## Features
25 |
26 | * Allow chown and mode options to be set to false to disable the defaulting behavior. (#20)
27 | * Support passing encoding strings in options slot for compat with Node.js API. (#31)
28 | * Add support for running inside of worker threads (#37)
29 |
30 | ## Fixes
31 |
32 | * Remove unneeded call when returning success (#36)
33 |
--------------------------------------------------------------------------------
/lib/index.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | module.exports = writeFile
3 | module.exports.sync = writeFileSync
4 | module.exports._getTmpname = getTmpname // for testing
5 | module.exports._cleanupOnExit = cleanupOnExit
6 |
7 | const fs = require('fs')
8 | const MurmurHash3 = require('imurmurhash')
9 | const { onExit } = require('signal-exit')
10 | const path = require('path')
11 | const { promisify } = require('util')
12 | const activeFiles = {}
13 |
14 | // if we run inside of a worker_thread, `process.pid` is not unique
15 | /* istanbul ignore next */
16 | const threadId = (function getId () {
17 | try {
18 | const workerThreads = require('worker_threads')
19 |
20 | /// if we are in main thread, this is set to `0`
21 | return workerThreads.threadId
22 | } catch (e) {
23 | // worker_threads are not available, fallback to 0
24 | return 0
25 | }
26 | })()
27 |
28 | let invocations = 0
29 | function getTmpname (filename) {
30 | return filename + '.' +
31 | MurmurHash3(__filename)
32 | .hash(String(process.pid))
33 | .hash(String(threadId))
34 | .hash(String(++invocations))
35 | .result()
36 | }
37 |
38 | function cleanupOnExit (tmpfile) {
39 | return () => {
40 | try {
41 | fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile)
42 | } catch {
43 | // ignore errors
44 | }
45 | }
46 | }
47 |
48 | function serializeActiveFile (absoluteName) {
49 | return new Promise(resolve => {
50 | // make a queue if it doesn't already exist
51 | if (!activeFiles[absoluteName]) {
52 | activeFiles[absoluteName] = []
53 | }
54 |
55 | activeFiles[absoluteName].push(resolve) // add this job to the queue
56 | if (activeFiles[absoluteName].length === 1) {
57 | resolve()
58 | } // kick off the first one
59 | })
60 | }
61 |
62 | // https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342
63 | function isChownErrOk (err) {
64 | if (err.code === 'ENOSYS') {
65 | return true
66 | }
67 |
68 | const nonroot = !process.getuid || process.getuid() !== 0
69 | if (nonroot) {
70 | if (err.code === 'EINVAL' || err.code === 'EPERM') {
71 | return true
72 | }
73 | }
74 |
75 | return false
76 | }
77 |
78 | async function writeFileAsync (filename, data, options = {}) {
79 | if (typeof options === 'string') {
80 | options = { encoding: options }
81 | }
82 |
83 | let fd
84 | let tmpfile
85 | /* istanbul ignore next -- The closure only gets called when onExit triggers */
86 | const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile))
87 | const absoluteName = path.resolve(filename)
88 |
89 | try {
90 | await serializeActiveFile(absoluteName)
91 | const truename = await promisify(fs.realpath)(filename).catch(() => filename)
92 | tmpfile = getTmpname(truename)
93 |
94 | if (!options.mode || !options.chown) {
95 | // Either mode or chown is not explicitly set
96 | // Default behavior is to copy it from original file
97 | const stats = await promisify(fs.stat)(truename).catch(() => {})
98 | if (stats) {
99 | if (options.mode == null) {
100 | options.mode = stats.mode
101 | }
102 |
103 | if (options.chown == null && process.getuid) {
104 | options.chown = { uid: stats.uid, gid: stats.gid }
105 | }
106 | }
107 | }
108 |
109 | fd = await promisify(fs.open)(tmpfile, 'w', options.mode)
110 | if (options.tmpfileCreated) {
111 | await options.tmpfileCreated(tmpfile)
112 | }
113 | if (ArrayBuffer.isView(data)) {
114 | await promisify(fs.write)(fd, data, 0, data.length, 0)
115 | } else if (data != null) {
116 | await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8'))
117 | }
118 |
119 | if (options.fsync !== false) {
120 | await promisify(fs.fsync)(fd)
121 | }
122 |
123 | await promisify(fs.close)(fd)
124 | fd = null
125 |
126 | if (options.chown) {
127 | await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => {
128 | if (!isChownErrOk(err)) {
129 | throw err
130 | }
131 | })
132 | }
133 |
134 | if (options.mode) {
135 | await promisify(fs.chmod)(tmpfile, options.mode).catch(err => {
136 | if (!isChownErrOk(err)) {
137 | throw err
138 | }
139 | })
140 | }
141 |
142 | await promisify(fs.rename)(tmpfile, truename)
143 | } finally {
144 | if (fd) {
145 | await promisify(fs.close)(fd).catch(
146 | /* istanbul ignore next */
147 | () => {}
148 | )
149 | }
150 | removeOnExitHandler()
151 | await promisify(fs.unlink)(tmpfile).catch(() => {})
152 | activeFiles[absoluteName].shift() // remove the element added by serializeSameFile
153 | if (activeFiles[absoluteName].length > 0) {
154 | activeFiles[absoluteName][0]() // start next job if one is pending
155 | } else {
156 | delete activeFiles[absoluteName]
157 | }
158 | }
159 | }
160 |
161 | async function writeFile (filename, data, options, callback) {
162 | if (options instanceof Function) {
163 | callback = options
164 | options = {}
165 | }
166 |
167 | const promise = writeFileAsync(filename, data, options)
168 | if (callback) {
169 | try {
170 | const result = await promise
171 | return callback(result)
172 | } catch (err) {
173 | return callback(err)
174 | }
175 | }
176 |
177 | return promise
178 | }
179 |
180 | function writeFileSync (filename, data, options) {
181 | if (typeof options === 'string') {
182 | options = { encoding: options }
183 | } else if (!options) {
184 | options = {}
185 | }
186 | try {
187 | filename = fs.realpathSync(filename)
188 | } catch (ex) {
189 | // it's ok, it'll happen on a not yet existing file
190 | }
191 | const tmpfile = getTmpname(filename)
192 |
193 | if (!options.mode || !options.chown) {
194 | // Either mode or chown is not explicitly set
195 | // Default behavior is to copy it from original file
196 | try {
197 | const stats = fs.statSync(filename)
198 | options = Object.assign({}, options)
199 | if (!options.mode) {
200 | options.mode = stats.mode
201 | }
202 | if (!options.chown && process.getuid) {
203 | options.chown = { uid: stats.uid, gid: stats.gid }
204 | }
205 | } catch (ex) {
206 | // ignore stat errors
207 | }
208 | }
209 |
210 | let fd
211 | const cleanup = cleanupOnExit(tmpfile)
212 | const removeOnExitHandler = onExit(cleanup)
213 |
214 | let threw = true
215 | try {
216 | fd = fs.openSync(tmpfile, 'w', options.mode || 0o666)
217 | if (options.tmpfileCreated) {
218 | options.tmpfileCreated(tmpfile)
219 | }
220 | if (ArrayBuffer.isView(data)) {
221 | fs.writeSync(fd, data, 0, data.length, 0)
222 | } else if (data != null) {
223 | fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'))
224 | }
225 | if (options.fsync !== false) {
226 | fs.fsyncSync(fd)
227 | }
228 |
229 | fs.closeSync(fd)
230 | fd = null
231 |
232 | if (options.chown) {
233 | try {
234 | fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
235 | } catch (err) {
236 | if (!isChownErrOk(err)) {
237 | throw err
238 | }
239 | }
240 | }
241 |
242 | if (options.mode) {
243 | try {
244 | fs.chmodSync(tmpfile, options.mode)
245 | } catch (err) {
246 | if (!isChownErrOk(err)) {
247 | throw err
248 | }
249 | }
250 | }
251 |
252 | fs.renameSync(tmpfile, filename)
253 | threw = false
254 | } finally {
255 | if (fd) {
256 | try {
257 | fs.closeSync(fd)
258 | } catch (ex) {
259 | // ignore close errors at this stage, error may have closed fd already.
260 | }
261 | }
262 | removeOnExitHandler()
263 | if (threw) {
264 | cleanup()
265 | }
266 | }
267 | }
268 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "write-file-atomic",
3 | "version": "6.0.0",
4 | "description": "Write files in an atomic fashion w/configurable ownership",
5 | "main": "./lib/index.js",
6 | "scripts": {
7 | "test": "tap",
8 | "posttest": "npm run lint",
9 | "lint": "npm run eslint",
10 | "postlint": "template-oss-check",
11 | "lintfix": "npm run eslint -- --fix",
12 | "snap": "tap",
13 | "template-oss-apply": "template-oss-apply --force",
14 | "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
15 | },
16 | "repository": {
17 | "type": "git",
18 | "url": "git+https://github.com/npm/write-file-atomic.git"
19 | },
20 | "keywords": [
21 | "writeFile",
22 | "atomic"
23 | ],
24 | "author": "GitHub Inc.",
25 | "license": "ISC",
26 | "bugs": {
27 | "url": "https://github.com/npm/write-file-atomic/issues"
28 | },
29 | "homepage": "https://github.com/npm/write-file-atomic",
30 | "dependencies": {
31 | "imurmurhash": "^0.1.4",
32 | "signal-exit": "^4.0.1"
33 | },
34 | "devDependencies": {
35 | "@npmcli/eslint-config": "^5.0.0",
36 | "@npmcli/template-oss": "4.24.3",
37 | "tap": "^16.0.1"
38 | },
39 | "files": [
40 | "bin/",
41 | "lib/"
42 | ],
43 | "engines": {
44 | "node": "^18.17.0 || >=20.5.0"
45 | },
46 | "templateOSS": {
47 | "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
48 | "windowsCI": false,
49 | "version": "4.24.3",
50 | "publish": "true"
51 | },
52 | "tap": {
53 | "nyc-arg": [
54 | "--exclude",
55 | "tap-snapshots/**"
56 | ]
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/release-please-config.json:
--------------------------------------------------------------------------------
1 | {
2 | "group-pull-request-title-pattern": "chore: release ${version}",
3 | "pull-request-title-pattern": "chore: release${component} ${version}",
4 | "changelog-sections": [
5 | {
6 | "type": "feat",
7 | "section": "Features",
8 | "hidden": false
9 | },
10 | {
11 | "type": "fix",
12 | "section": "Bug Fixes",
13 | "hidden": false
14 | },
15 | {
16 | "type": "docs",
17 | "section": "Documentation",
18 | "hidden": false
19 | },
20 | {
21 | "type": "deps",
22 | "section": "Dependencies",
23 | "hidden": false
24 | },
25 | {
26 | "type": "chore",
27 | "section": "Chores",
28 | "hidden": true
29 | }
30 | ],
31 | "packages": {
32 | ".": {
33 | "package-name": ""
34 | }
35 | },
36 | "prerelease-type": "pre.0"
37 | }
38 |
--------------------------------------------------------------------------------
/test/basic.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const t = require('tap')
3 |
4 | let expectClose = 0
5 | let closeCalled = 0
6 | let expectCloseSync = 0
7 | let closeSyncCalled = 0
8 | const createErr = code => Object.assign(new Error(code), { code })
9 |
10 | let unlinked = []
11 | const writeFileAtomic = t.mock('..', {
12 | fs: {
13 | realpath (filename, cb) {
14 | return cb(null, filename)
15 | },
16 | open (tmpfile, options, mode, cb) {
17 | if (/noopen/.test(tmpfile)) {
18 | return cb(createErr('ENOOPEN'))
19 | }
20 | expectClose++
21 | cb(null, tmpfile)
22 | },
23 | write (fd) {
24 | const cb = arguments[arguments.length - 1]
25 | if (/nowrite/.test(fd)) {
26 | return cb(createErr('ENOWRITE'))
27 | }
28 | cb()
29 | },
30 | fsync (fd, cb) {
31 | if (/nofsync/.test(fd)) {
32 | return cb(createErr('ENOFSYNC'))
33 | }
34 | cb()
35 | },
36 | close (fd, cb) {
37 | closeCalled++
38 | cb()
39 | },
40 | chown (tmpfile, uid, gid, cb) {
41 | if (/nochown/.test(tmpfile)) {
42 | return cb(createErr('ENOCHOWN'))
43 | }
44 | if (/enosys/.test(tmpfile)) {
45 | return cb(createErr('ENOSYS'))
46 | }
47 | if (/einval/.test(tmpfile)) {
48 | return cb(createErr('EINVAL'))
49 | }
50 | if (/eperm/.test(tmpfile)) {
51 | return cb(createErr('EPERM'))
52 | }
53 | cb()
54 | },
55 | chmod (tmpfile, mode, cb) {
56 | if (/nochmod/.test(tmpfile)) {
57 | return cb(createErr('ENOCHMOD'))
58 | }
59 | if (/enosys/.test(tmpfile)) {
60 | return cb(createErr('ENOSYS'))
61 | }
62 | if (/eperm/.test(tmpfile)) {
63 | return cb(createErr('EPERM'))
64 | }
65 | if (/einval/.test(tmpfile)) {
66 | return cb(createErr('EINVAL'))
67 | }
68 | cb()
69 | },
70 | rename (tmpfile, filename, cb) {
71 | if (/norename/.test(tmpfile)) {
72 | return cb(createErr('ENORENAME'))
73 | }
74 | cb()
75 | },
76 | unlink (tmpfile, cb) {
77 | if (/nounlink/.test(tmpfile)) {
78 | return cb(createErr('ENOUNLINK'))
79 | }
80 | cb()
81 | },
82 | stat (tmpfile, cb) {
83 | if (/nostat/.test(tmpfile)) {
84 | return cb(createErr('ENOSTAT'))
85 | }
86 | cb()
87 | },
88 | realpathSync (filename) {
89 | return filename
90 | },
91 | openSync (tmpfile) {
92 | if (/noopen/.test(tmpfile)) {
93 | throw createErr('ENOOPEN')
94 | }
95 | expectCloseSync++
96 | return tmpfile
97 | },
98 | writeSync (fd) {
99 | if (/nowrite/.test(fd)) {
100 | throw createErr('ENOWRITE')
101 | }
102 | },
103 | fsyncSync (fd) {
104 | if (/nofsync/.test(fd)) {
105 | throw createErr('ENOFSYNC')
106 | }
107 | },
108 | closeSync () {
109 | closeSyncCalled++
110 | },
111 | chownSync (tmpfile) {
112 | if (/nochown/.test(tmpfile)) {
113 | throw createErr('ENOCHOWN')
114 | }
115 | if (/enosys/.test(tmpfile)) {
116 | throw createErr('ENOSYS')
117 | }
118 | if (/einval/.test(tmpfile)) {
119 | throw createErr('EINVAL')
120 | }
121 | if (/eperm/.test(tmpfile)) {
122 | throw createErr('EPERM')
123 | }
124 | },
125 | chmodSync (tmpfile) {
126 | if (/nochmod/.test(tmpfile)) {
127 | throw createErr('ENOCHMOD')
128 | }
129 | if (/enosys/.test(tmpfile)) {
130 | throw createErr('ENOSYS')
131 | }
132 | if (/einval/.test(tmpfile)) {
133 | throw createErr('EINVAL')
134 | }
135 | if (/eperm/.test(tmpfile)) {
136 | throw createErr('EPERM')
137 | }
138 | },
139 | renameSync (tmpfile) {
140 | if (/norename/.test(tmpfile)) {
141 | throw createErr('ENORENAME')
142 | }
143 | },
144 | unlinkSync (tmpfile) {
145 | if (/nounlink/.test(tmpfile)) {
146 | throw createErr('ENOUNLINK')
147 | }
148 | unlinked.push(tmpfile)
149 | },
150 | statSync (tmpfile) {
151 | if (/nostat/.test(tmpfile)) {
152 | throw createErr('ENOSTAT')
153 | }
154 | },
155 | },
156 | })
157 | const writeFileAtomicSync = writeFileAtomic.sync
158 |
159 | t.test('getTmpname', t => {
160 | const getTmpname = writeFileAtomic._getTmpname
161 | const a = getTmpname('abc.def')
162 | const b = getTmpname('abc.def')
163 | t.not(a, b, 'different invocations of getTmpname get different results')
164 | t.end()
165 | })
166 |
167 | t.test('cleanupOnExit', t => {
168 | const file = 'tmpname'
169 | unlinked = []
170 | const cleanup = writeFileAtomic._cleanupOnExit(() => file)
171 | cleanup()
172 | t.strictSame(unlinked, [file], 'cleanup code unlinks')
173 | const cleanup2 = writeFileAtomic._cleanupOnExit('nounlink')
174 | t.doesNotThrow(cleanup2, 'exceptions are caught')
175 | unlinked = []
176 | t.end()
177 | })
178 |
179 | t.test('async tests', t => {
180 | t.plan(2)
181 |
182 | expectClose = 0
183 | closeCalled = 0
184 | t.teardown(() => {
185 | t.parent.equal(closeCalled, expectClose, 'async tests closed all files')
186 | expectClose = 0
187 | closeCalled = 0
188 | })
189 |
190 | t.test('non-root tests', t => {
191 | t.plan(19)
192 |
193 | writeFileAtomic('good', 'test', { mode: '0777' }, err => {
194 | t.notOk(err, 'No errors occur when passing in options')
195 | })
196 | writeFileAtomic('good', 'test', 'utf8', err => {
197 | t.notOk(err, 'No errors occur when passing in options as string')
198 | })
199 | writeFileAtomic('good', 'test', undefined, err => {
200 | t.notOk(err, 'No errors occur when NOT passing in options')
201 | })
202 | writeFileAtomic('good', 'test', err => {
203 | t.notOk(err)
204 | })
205 | writeFileAtomic('noopen', 'test', err => {
206 | t.equal(err && err.message, 'ENOOPEN', 'fs.open failures propagate')
207 | })
208 | writeFileAtomic('nowrite', 'test', err => {
209 | t.equal(err && err.message, 'ENOWRITE', 'fs.writewrite failures propagate')
210 | })
211 | writeFileAtomic('nowrite', Buffer.from('test', 'utf8'), err => {
212 | t.equal(err && err.message, 'ENOWRITE', 'fs.writewrite failures propagate for buffers')
213 | })
214 | writeFileAtomic('nochown', 'test', { chown: { uid: 100, gid: 100 } }, err => {
215 | t.equal(err && err.message, 'ENOCHOWN', 'Chown failures propagate')
216 | })
217 | writeFileAtomic('nochown', 'test', err => {
218 | t.notOk(err, 'No attempt to chown when no uid/gid passed in')
219 | })
220 | writeFileAtomic('nochmod', 'test', { mode: parseInt('741', 8) }, err => {
221 | t.equal(err && err.message, 'ENOCHMOD', 'Chmod failures propagate')
222 | })
223 | writeFileAtomic('nofsyncopt', 'test', { fsync: false }, err => {
224 | t.notOk(err, 'fsync skipped if options.fsync is false')
225 | })
226 | writeFileAtomic('norename', 'test', err => {
227 | t.equal(err && err.message, 'ENORENAME', 'Rename errors propagate')
228 | })
229 | writeFileAtomic('norename nounlink', 'test', err => {
230 | t.equal(err && err.message, 'ENORENAME',
231 | 'Failure to unlink the temp file does not clobber the original error')
232 | })
233 | writeFileAtomic('nofsync', 'test', err => {
234 | t.equal(err && err.message, 'ENOFSYNC', 'Fsync failures propagate')
235 | })
236 | writeFileAtomic('enosys', 'test', err => {
237 | t.notOk(err, 'No errors on ENOSYS')
238 | })
239 | writeFileAtomic('einval', 'test', { mode: 0o741 }, err => {
240 | t.notOk(err, 'No errors on EINVAL for non root')
241 | })
242 | writeFileAtomic('eperm', 'test', { mode: 0o741 }, err => {
243 | t.notOk(err, 'No errors on EPERM for non root')
244 | })
245 | writeFileAtomic('einval', 'test', { chown: { uid: 100, gid: 100 } }, err => {
246 | t.notOk(err, 'No errors on EINVAL for non root')
247 | })
248 | writeFileAtomic('eperm', 'test', { chown: { uid: 100, gid: 100 } }, err => {
249 | t.notOk(err, 'No errors on EPERM for non root')
250 | })
251 | })
252 |
253 | t.test('errors for root', t => {
254 | const { getuid } = process
255 | process.getuid = () => 0
256 | t.teardown(() => {
257 | process.getuid = getuid
258 | })
259 | t.plan(2)
260 | writeFileAtomic('einval', 'test', { chown: { uid: 100, gid: 100 } }, err => {
261 | t.match(err, { code: 'EINVAL' })
262 | })
263 | writeFileAtomic('einval', 'test', { mode: 0o741 }, err => {
264 | t.match(err, { code: 'EINVAL' })
265 | })
266 | })
267 | })
268 |
269 | t.test('sync tests', t => {
270 | t.plan(2)
271 | closeSyncCalled = 0
272 | expectCloseSync = 0
273 | t.teardown(() => {
274 | t.parent.equal(closeSyncCalled, expectCloseSync, 'sync closed all files')
275 | expectCloseSync = 0
276 | closeSyncCalled = 0
277 | })
278 |
279 | const throws = function (t, shouldthrow, msg, todo) {
280 | let err
281 | try {
282 | todo()
283 | } catch (e) {
284 | err = e
285 | }
286 | t.equal(shouldthrow, err && err.message, msg)
287 | }
288 | const noexception = function (t, msg, todo) {
289 | let err
290 | try {
291 | todo()
292 | } catch (e) {
293 | err = e
294 | }
295 | t.error(err, msg)
296 | }
297 | let tmpfile
298 |
299 | t.test('non-root', t => {
300 | t.plan(22)
301 | noexception(t, 'No errors occur when passing in options', () => {
302 | writeFileAtomicSync('good', 'test', { mode: '0777' })
303 | })
304 | noexception(t, 'No errors occur when passing in options as string', () => {
305 | writeFileAtomicSync('good', 'test', 'utf8')
306 | })
307 | noexception(t, 'No errors occur when NOT passing in options', () => {
308 | writeFileAtomicSync('good', 'test')
309 | })
310 | noexception(t, 'fsync never called if options.fsync is falsy', () => {
311 | writeFileAtomicSync('good', 'test', { fsync: false })
312 | })
313 | noexception(t, 'tmpfileCreated is called on success', () => {
314 | writeFileAtomicSync('good', 'test', {
315 | tmpfileCreated (gottmpfile) {
316 | tmpfile = gottmpfile
317 | },
318 | })
319 | t.match(tmpfile, /^good\.\d+$/, 'tmpfileCreated called for success')
320 | })
321 |
322 | tmpfile = undefined
323 | throws(t, 'ENOOPEN', 'fs.openSync failures propagate', () => {
324 | writeFileAtomicSync('noopen', 'test', {
325 | tmpfileCreated (gottmpfile) {
326 | tmpfile = gottmpfile
327 | },
328 | })
329 | })
330 | t.equal(tmpfile, undefined, 'tmpfileCreated not called for open failure')
331 |
332 | throws(t, 'ENOWRITE', 'fs.writeSync failures propagate', () => {
333 | writeFileAtomicSync('nowrite', 'test', {
334 | tmpfileCreated (gottmpfile) {
335 | tmpfile = gottmpfile
336 | },
337 | })
338 | })
339 | t.match(tmpfile, /^nowrite\.\d+$/, 'tmpfileCreated called for failure after open')
340 |
341 | throws(t, 'ENOCHOWN', 'Chown failures propagate', () => {
342 | writeFileAtomicSync('nochown', 'test', { chown: { uid: 100, gid: 100 } })
343 | })
344 | noexception(t, 'No attempt to chown when false passed in', () => {
345 | writeFileAtomicSync('nochown', 'test', { chown: false })
346 | })
347 | noexception(t, 'No errors occured when chown is undefined and original file owner used', () => {
348 | writeFileAtomicSync('chowncopy', 'test', { chown: undefined })
349 | })
350 | throws(t, 'ENORENAME', 'Rename errors propagate', () => {
351 | writeFileAtomicSync('norename', 'test')
352 | })
353 | throws(t, 'ENORENAME',
354 | 'Failure to unlink the temp file does not clobber the original error', () => {
355 | writeFileAtomicSync('norename nounlink', 'test')
356 | })
357 | throws(t, 'ENOFSYNC', 'Fsync errors propagate', () => {
358 | writeFileAtomicSync('nofsync', 'test')
359 | })
360 | noexception(t, 'No errors on ENOSYS', () => {
361 | writeFileAtomicSync('enosys', 'test', { chown: { uid: 100, gid: 100 } })
362 | })
363 | noexception(t, 'No errors on EINVAL for non root', () => {
364 | writeFileAtomicSync('einval', 'test', { chown: { uid: 100, gid: 100 } })
365 | })
366 | noexception(t, 'No errors on EPERM for non root', () => {
367 | writeFileAtomicSync('eperm', 'test', { chown: { uid: 100, gid: 100 } })
368 | })
369 |
370 | throws(t, 'ENOCHMOD', 'Chmod failures propagate', () => {
371 | writeFileAtomicSync('nochmod', 'test', { mode: 0o741 })
372 | })
373 | noexception(t, 'No errors on EPERM for non root', () => {
374 | writeFileAtomicSync('eperm', 'test', { mode: 0o741 })
375 | })
376 | noexception(t, 'No attempt to chmod when no mode provided', () => {
377 | writeFileAtomicSync('nochmod', 'test', { mode: false })
378 | })
379 | })
380 |
381 | t.test('errors for root', t => {
382 | const { getuid } = process
383 | process.getuid = () => 0
384 | t.teardown(() => {
385 | process.getuid = getuid
386 | })
387 | t.plan(2)
388 | throws(t, 'EINVAL', 'Chown error as root user', () => {
389 | writeFileAtomicSync('einval', 'test', { chown: { uid: 100, gid: 100 } })
390 | })
391 | throws(t, 'EINVAL', 'Chmod error as root user', () => {
392 | writeFileAtomicSync('einval', 'test', { mode: 0o741 })
393 | })
394 | })
395 | })
396 |
397 | t.test('promises', async t => {
398 | let tmpfile
399 | closeCalled = 0
400 | expectClose = 0
401 | t.teardown(() => {
402 | t.parent.equal(closeCalled, expectClose, 'promises closed all files')
403 | closeCalled = 0
404 | expectClose = 0
405 | })
406 |
407 | await writeFileAtomic('good', 'test', {
408 | tmpfileCreated (gottmpfile) {
409 | tmpfile = gottmpfile
410 | },
411 | })
412 | t.match(tmpfile, /^good\.\d+$/, 'tmpfileCreated is called for success')
413 |
414 | await writeFileAtomic('good', 'test', {
415 | tmpfileCreated () {
416 | return Promise.resolve()
417 | },
418 | })
419 |
420 | await t.rejects(writeFileAtomic('good', 'test', {
421 | tmpfileCreated () {
422 | return Promise.reject(new Error('reject from tmpfileCreated'))
423 | },
424 | }))
425 |
426 | await t.rejects(writeFileAtomic('good', 'test', {
427 | tmpfileCreated () {
428 | throw new Error('throw from tmpfileCreated')
429 | },
430 | }))
431 |
432 | tmpfile = undefined
433 | await t.rejects(writeFileAtomic('noopen', 'test', {
434 | tmpfileCreated (gottmpfile) {
435 | tmpfile = gottmpfile
436 | },
437 | }))
438 | t.equal(tmpfile, undefined, 'tmpfileCreated is not called on open failure')
439 |
440 | await t.rejects(writeFileAtomic('nowrite', 'test', {
441 | tmpfileCreated (gottmpfile) {
442 | tmpfile = gottmpfile
443 | },
444 | }))
445 | t.match(tmpfile, /^nowrite\.\d+$/, 'tmpfileCreated is called if failure is after open')
446 | })
447 |
--------------------------------------------------------------------------------
/test/concurrency.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const t = require('tap')
3 | // defining mock for fs so its functions can be modified
4 | const fs = {
5 | realpath (filename, cb) {
6 | return cb(null, filename)
7 | },
8 | open (tmpfile, options, mode, cb) {
9 | if (/noopen/.test(tmpfile)) {
10 | return cb(new Error('ENOOPEN'))
11 | }
12 | cb(null, tmpfile)
13 | },
14 | write (fd) {
15 | const cb = arguments[arguments.length - 1]
16 | if (/nowrite/.test(fd)) {
17 | return cb(new Error('ENOWRITE'))
18 | }
19 | cb()
20 | },
21 | fsync (fd, cb) {
22 | if (/nofsync/.test(fd)) {
23 | return cb(new Error('ENOFSYNC'))
24 | }
25 | cb()
26 | },
27 | close (fd, cb) {
28 | cb()
29 | },
30 | chown (tmpfile, uid, gid, cb) {
31 | if (/nochown/.test(tmpfile)) {
32 | return cb(new Error('ENOCHOWN'))
33 | }
34 | cb()
35 | },
36 | chmod (tmpfile, mode, cb) {
37 | if (/nochmod/.test(tmpfile)) {
38 | return cb(new Error('ENOCHMOD'))
39 | }
40 | cb()
41 | },
42 | rename (tmpfile, filename, cb) {
43 | if (/norename/.test(tmpfile)) {
44 | return cb(new Error('ENORENAME'))
45 | }
46 | cb()
47 | },
48 | unlink (tmpfile, cb) {
49 | if (/nounlink/.test(tmpfile)) {
50 | return cb(new Error('ENOUNLINK'))
51 | }
52 | cb()
53 | },
54 | stat (tmpfile, cb) {
55 | if (/nostat/.test(tmpfile)) {
56 | return cb(new Error('ENOSTAT'))
57 | }
58 | cb()
59 | },
60 | realpathSync (filename) {
61 | return filename
62 | },
63 | openSync (tmpfile) {
64 | if (/noopen/.test(tmpfile)) {
65 | throw new Error('ENOOPEN')
66 | }
67 | return tmpfile
68 | },
69 | writeSync (fd) {
70 | if (/nowrite/.test(fd)) {
71 | throw new Error('ENOWRITE')
72 | }
73 | },
74 | fsyncSync (fd) {
75 | if (/nofsync/.test(fd)) {
76 | throw new Error('ENOFSYNC')
77 | }
78 | },
79 | closeSync () { },
80 | chownSync (tmpfile) {
81 | if (/nochown/.test(tmpfile)) {
82 | throw new Error('ENOCHOWN')
83 | }
84 | },
85 | chmodSync (tmpfile) {
86 | if (/nochmod/.test(tmpfile)) {
87 | throw new Error('ENOCHMOD')
88 | }
89 | },
90 | renameSync (tmpfile) {
91 | if (/norename/.test(tmpfile)) {
92 | throw new Error('ENORENAME')
93 | }
94 | },
95 | unlinkSync (tmpfile) {
96 | if (/nounlink/.test(tmpfile)) {
97 | throw new Error('ENOUNLINK')
98 | }
99 | },
100 | statSync (tmpfile) {
101 | if (/nostat/.test(tmpfile)) {
102 | throw new Error('ENOSTAT')
103 | }
104 | },
105 | }
106 |
107 | const writeFileAtomic = t.mock('..', {
108 | fs: fs,
109 | })
110 |
111 | // preserve original functions
112 | const oldRealPath = fs.realpath
113 | const oldRename = fs.rename
114 |
115 | t.test('ensure writes to the same file are serial', t => {
116 | let fileInUse = false
117 | const ops = 5 // count for how many concurrent write ops to request
118 | t.plan(ops * 3 + 3)
119 | fs.realpath = (...args) => {
120 | t.notOk(fileInUse, 'file not in use')
121 | fileInUse = true
122 | oldRealPath(...args)
123 | }
124 | fs.rename = (...args) => {
125 | t.ok(fileInUse, 'file in use')
126 | fileInUse = false
127 | oldRename(...args)
128 | }
129 | for (let i = 0; i < ops; i++) {
130 | writeFileAtomic('test', 'test', err => {
131 | if (err) {
132 | t.fail(err)
133 | } else {
134 | t.pass('wrote without error')
135 | }
136 | })
137 | }
138 | setTimeout(() => {
139 | writeFileAtomic('test', 'test', err => {
140 | if (err) {
141 | t.fail(err)
142 | } else {
143 | t.pass('successive writes after delay')
144 | }
145 | })
146 | }, 500)
147 | })
148 |
149 | t.test('allow write to multiple files in parallel, but same file writes are serial', t => {
150 | const filesInUse = []
151 | const ops = 5
152 | let wasParallel = false
153 | fs.realpath = (filename, ...args) => {
154 | filesInUse.push(filename)
155 | const firstOccurence = filesInUse.indexOf(filename)
156 | // check for another occurence after the first
157 | t.equal(filesInUse.indexOf(filename, firstOccurence + 1), -1, 'serial writes')
158 | if (filesInUse.length > 1) {
159 | wasParallel = true
160 | } // remember that a parallel operation took place
161 | oldRealPath(filename, ...args)
162 | }
163 | fs.rename = (filename, ...args) => {
164 | filesInUse.splice(filesInUse.indexOf(filename), 1)
165 | oldRename(filename, ...args)
166 | }
167 | t.plan(ops * 2 * 2 + 1)
168 | let opCount = 0
169 | for (let i = 0; i < ops; i++) {
170 | writeFileAtomic('test', 'test', err => {
171 | if (err) {
172 | t.fail(err, 'wrote without error')
173 | } else {
174 | t.pass('wrote without error')
175 | }
176 | })
177 | writeFileAtomic('test2', 'test', err => {
178 | opCount++
179 | if (opCount === ops) {
180 | t.ok(wasParallel, 'parallel writes')
181 | }
182 |
183 | if (err) {
184 | t.fail(err, 'wrote without error')
185 | } else {
186 | t.pass('wrote without error')
187 | }
188 | })
189 | }
190 | })
191 |
--------------------------------------------------------------------------------
/test/integration.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const fs = require('fs')
3 | const path = require('path')
4 | const t = require('tap')
5 |
6 | const workdir = path.join(__dirname, path.basename(__filename, '.js'))
7 | let testfiles = 0
8 | function tmpFile () {
9 | return path.join(workdir, 'test-' + (++testfiles))
10 | }
11 |
12 | function readFile (p) {
13 | return fs.readFileSync(p).toString()
14 | }
15 |
16 | function didWriteFileAtomic (t, expected, filename, data, options, callback) {
17 | if (options instanceof Function) {
18 | callback = options
19 | options = null
20 | }
21 | if (!options) {
22 | options = {}
23 | }
24 | const actual = {}
25 | const writeFileAtomic = t.mock('..', {
26 | fs: Object.assign({}, fs, {
27 | chown (chownFilename, uid, gid, cb) {
28 | actual.uid = uid
29 | actual.gid = gid
30 | process.nextTick(cb)
31 | },
32 | stat (statFilename, cb) {
33 | fs.stat(statFilename, (err, stats) => {
34 | if (err) {
35 | return cb(err)
36 | }
37 | cb(null, Object.assign(stats, expected || {}))
38 | })
39 | },
40 | }),
41 | })
42 | return writeFileAtomic(filename, data, options, err => {
43 | t.strictSame(actual, expected, 'ownership is as expected')
44 | callback(err)
45 | })
46 | }
47 |
48 | function didWriteFileAtomicSync (t, expected, filename, data, options) {
49 | const actual = {}
50 | const writeFileAtomic = t.mock('..', {
51 | fs: Object.assign({}, fs, {
52 | chownSync (chownFilename, uid, gid) {
53 | actual.uid = uid
54 | actual.gid = gid
55 | },
56 | statSync (statFilename) {
57 | const stats = fs.statSync(statFilename)
58 | return Object.assign(stats, expected || {})
59 | },
60 | }),
61 | })
62 | writeFileAtomic.sync(filename, data, options)
63 | t.strictSame(actual, expected)
64 | }
65 |
66 | function currentUser () {
67 | return {
68 | uid: process.getuid(),
69 | gid: process.getgid(),
70 | }
71 | }
72 |
73 | t.test('setup', t => {
74 | fs.rmSync(workdir, { recursive: true, force: true })
75 | fs.mkdirSync(workdir, { recursive: true })
76 | t.end()
77 | })
78 |
79 | t.test('writes simple file (async)', t => {
80 | t.plan(3)
81 | const file = tmpFile()
82 | didWriteFileAtomic(t, {}, file, '42', err => {
83 | t.error(err, 'no error')
84 | t.equal(readFile(file), '42', 'content ok')
85 | })
86 | })
87 |
88 | t.test('writes simple file with encoding (async)', t => {
89 | t.plan(3)
90 | const file = tmpFile()
91 | didWriteFileAtomic(t, {}, file, 'foo', 'utf16le', err => {
92 | t.error(err, 'no error')
93 | t.equal(readFile(file), 'f\u0000o\u0000o\u0000', 'content ok')
94 | })
95 | })
96 |
97 | t.test('writes buffers to simple file (async)', t => {
98 | t.plan(3)
99 | const file = tmpFile()
100 | didWriteFileAtomic(t, {}, file, Buffer.from('42'), err => {
101 | t.error(err, 'no error')
102 | t.equal(readFile(file), '42', 'content ok')
103 | })
104 | })
105 |
106 | t.test('writes TypedArray to simple file (async)', t => {
107 | t.plan(3)
108 | const file = tmpFile()
109 | didWriteFileAtomic(t, {}, file, new Uint8Array([0x34, 0x32]), err => {
110 | t.error(err, 'no error')
111 | t.equal(readFile(file), '42', 'content ok')
112 | })
113 | })
114 |
115 | t.test('writes undefined to simple file (async)', t => {
116 | t.plan(3)
117 | const file = tmpFile()
118 | didWriteFileAtomic(t, {}, file, undefined, err => {
119 | t.error(err, 'no error')
120 | t.equal(readFile(file), '', 'content ok')
121 | })
122 | })
123 |
124 | t.test('writes to symlinks without clobbering (async)', t => {
125 | t.plan(5)
126 | const file = tmpFile()
127 | const link = tmpFile()
128 | fs.writeFileSync(file, '42')
129 | fs.symlinkSync(file, link)
130 | didWriteFileAtomic(t, currentUser(), link, '43', err => {
131 | t.error(err, 'no error')
132 | t.equal(readFile(file), '43', 'target content ok')
133 | t.equal(readFile(link), '43', 'link content ok')
134 | t.ok(fs.lstatSync(link).isSymbolicLink(), 'link is link')
135 | })
136 | })
137 |
138 | t.test('runs chown on given file (async)', t => {
139 | const file = tmpFile()
140 | didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } }, err => {
141 | t.error(err, 'no error')
142 | t.equal(readFile(file), '42', 'content ok')
143 | t.end()
144 | })
145 | })
146 |
147 | t.test('writes simple file with no chown (async)', t => {
148 | t.plan(3)
149 | const file = tmpFile()
150 | didWriteFileAtomic(t, {}, file, '42', { chown: false }, err => {
151 | t.error(err, 'no error')
152 | t.equal(readFile(file), '42', 'content ok')
153 | t.end()
154 | })
155 | })
156 |
157 | t.test('runs chmod on given file (async)', t => {
158 | t.plan(5)
159 | const file = tmpFile()
160 | didWriteFileAtomic(t, {}, file, '42', { mode: parseInt('741', 8) }, err => {
161 | t.error(err, 'no error')
162 | const stat = fs.statSync(file)
163 | t.equal(stat.mode, parseInt('100741', 8))
164 | didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '23',
165 | { chown: { uid: 42, gid: 43 } }, chownErr => {
166 | t.error(chownErr, 'no error')
167 | })
168 | })
169 | })
170 |
171 | t.test('run chmod AND chown (async)', t => {
172 | t.plan(3)
173 | const file = tmpFile()
174 | didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42',
175 | { mode: parseInt('741', 8), chown: { uid: 42, gid: 43 } }, err => {
176 | t.error(err, 'no error')
177 | const stat = fs.statSync(file)
178 | t.equal(stat.mode, parseInt('100741', 8))
179 | })
180 | })
181 |
182 | t.test('does not change chmod by default (async)', t => {
183 | t.plan(5)
184 | const file = tmpFile()
185 | didWriteFileAtomic(t, {}, file, '42', { mode: parseInt('741', 8) }, err => {
186 | t.error(err, 'no error')
187 |
188 | didWriteFileAtomic(t, currentUser(), file, '43', writeFileError => {
189 | t.error(writeFileError, 'no error')
190 | const stat = fs.statSync(file)
191 | t.equal(stat.mode, parseInt('100741', 8))
192 | })
193 | })
194 | })
195 |
196 | t.test('does not change chown by default (async)', t => {
197 | t.plan(6)
198 | const file = tmpFile()
199 | didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42',
200 | { chown: { uid: 42, gid: 43 } }, _setModeOnly)
201 |
202 | function _setModeOnly (err) {
203 | t.error(err, 'no error')
204 |
205 | didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '43',
206 | { mode: parseInt('741', 8) }, _allDefault)
207 | }
208 |
209 | function _allDefault (err) {
210 | t.error(err, 'no error')
211 |
212 | didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '43', _noError)
213 | }
214 |
215 | function _noError (err) {
216 | t.error(err, 'no error')
217 | }
218 | })
219 |
220 | t.test('writes simple file (sync)', t => {
221 | t.plan(2)
222 | const file = tmpFile()
223 | didWriteFileAtomicSync(t, {}, file, '42')
224 | t.equal(readFile(file), '42')
225 | })
226 |
227 | t.test('writes simple file with encoding (sync)', t => {
228 | t.plan(2)
229 | const file = tmpFile()
230 | didWriteFileAtomicSync(t, {}, file, 'foo', 'utf16le')
231 | t.equal(readFile(file), 'f\u0000o\u0000o\u0000')
232 | })
233 |
234 | t.test('writes simple buffer file (sync)', t => {
235 | t.plan(2)
236 | const file = tmpFile()
237 | didWriteFileAtomicSync(t, {}, file, Buffer.from('42'))
238 | t.equal(readFile(file), '42')
239 | })
240 |
241 | t.test('writes simple TypedArray file (sync)', t => {
242 | t.plan(2)
243 | const file = tmpFile()
244 | didWriteFileAtomicSync(t, {}, file, new Uint8Array([0x34, 0x32]))
245 | t.equal(readFile(file), '42')
246 | })
247 |
248 | t.test('writes undefined file (sync)', t => {
249 | t.plan(2)
250 | const file = tmpFile()
251 | didWriteFileAtomicSync(t, {}, file, undefined)
252 | t.equal(readFile(file), '')
253 | })
254 |
255 | t.test('writes to symlinks without clobbering (sync)', t => {
256 | t.plan(4)
257 | const file = tmpFile()
258 | const link = tmpFile()
259 | fs.writeFileSync(file, '42')
260 | fs.symlinkSync(file, link)
261 | didWriteFileAtomicSync(t, currentUser(), link, '43')
262 | t.equal(readFile(file), '43', 'target content ok')
263 | t.equal(readFile(link), '43', 'link content ok')
264 | t.ok(fs.lstatSync(link).isSymbolicLink(), 'link is link')
265 | })
266 |
267 | t.test('runs chown on given file (sync)', t => {
268 | t.plan(1)
269 | const file = tmpFile()
270 | didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } })
271 | })
272 |
273 | t.test('runs chmod on given file (sync)', t => {
274 | t.plan(3)
275 | const file = tmpFile()
276 | didWriteFileAtomicSync(t, {}, file, '42', { mode: parseInt('741', 8) })
277 | const stat = fs.statSync(file)
278 | t.equal(stat.mode, parseInt('100741', 8))
279 | didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '23', { chown: { uid: 42, gid: 43 } })
280 | })
281 |
282 | t.test('runs chown and chmod (sync)', t => {
283 | t.plan(2)
284 | const file = tmpFile()
285 | didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42',
286 | { mode: parseInt('741', 8), chown: { uid: 42, gid: 43 } })
287 | const stat = fs.statSync(file)
288 | t.equal(stat.mode, parseInt('100741', 8))
289 | })
290 |
291 | t.test('does not change chmod by default (sync)', t => {
292 | t.plan(3)
293 | const file = tmpFile()
294 | didWriteFileAtomicSync(t, {}, file, '42', { mode: parseInt('741', 8) })
295 | didWriteFileAtomicSync(t, currentUser(), file, '43')
296 | const stat = fs.statSync(file)
297 | t.equal(stat.mode, parseInt('100741', 8))
298 | })
299 |
300 | t.test('does not change chown by default (sync)', t => {
301 | t.plan(3)
302 | const file = tmpFile()
303 | didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } })
304 | didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '43', { mode: parseInt('741', 8) })
305 | didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '44')
306 | })
307 |
308 | t.test('cleanup', t => {
309 | fs.rmSync(workdir, { recursive: true, force: true })
310 | t.end()
311 | })
312 |
--------------------------------------------------------------------------------