pax_global_header 0000666 0000000 0000000 00000000064 15076173424 0014523 g ustar 00root root 0000000 0000000 52 comment=9d8161aae17d52fce9f5122fd706856ded294940
nopt-9.0.0/ 0000775 0000000 0000000 00000000000 15076173424 0012511 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.commitlintrc.js 0000664 0000000 0000000 00000000566 15076173424 0015640 0 ustar 00root root 0000000 0000000 /* This file is automatically added by @npmcli/template-oss. Do not edit. */
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'deps', 'chore']],
'header-max-length': [2, 'always', 80],
'subject-case': [0],
'body-max-line-length': [0],
'footer-max-line-length': [0],
},
}
nopt-9.0.0/.eslintrc.js 0000664 0000000 0000000 00000000623 15076173424 0014751 0 ustar 00root root 0000000 0000000 /* This file is automatically added by @npmcli/template-oss. Do not edit. */
'use strict'
const { readdirSync: readdir } = require('fs')
const localConfigs = readdir(__dirname)
.filter((file) => file.startsWith('.eslintrc.local.'))
.map((file) => `./${file}`)
module.exports = {
root: true,
ignorePatterns: [
'tap-testdir*/',
],
extends: [
'@npmcli',
...localConfigs,
],
}
nopt-9.0.0/.github/ 0000775 0000000 0000000 00000000000 15076173424 0014051 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.github/CODEOWNERS 0000664 0000000 0000000 00000000132 15076173424 0015440 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
* @npm/cli-team
nopt-9.0.0/.github/ISSUE_TEMPLATE/ 0000775 0000000 0000000 00000000000 15076173424 0016234 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.github/ISSUE_TEMPLATE/bug.yml 0000664 0000000 0000000 00000002655 15076173424 0017544 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Bug
description: File a bug/issue
title: "[BUG]
"
labels: [ Bug, Needs Triage ]
body:
- type: checkboxes
attributes:
label: Is there an existing issue for this?
description: Please [search here](./issues) to see if an issue already exists for your problem.
options:
- label: I have searched the existing issues
required: true
- type: textarea
attributes:
label: Current Behavior
description: A clear & concise description of what you're experiencing.
validations:
required: false
- type: textarea
attributes:
label: Expected Behavior
description: A clear & concise description of what you expected to happen.
validations:
required: false
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
value: |
1. In this environment...
2. With this config...
3. Run '...'
4. See error...
validations:
required: false
- type: textarea
attributes:
label: Environment
description: |
examples:
- **npm**: 7.6.3
- **Node**: 13.14.0
- **OS**: Ubuntu 20.04
- **platform**: Macbook Pro
value: |
- npm:
- Node:
- OS:
- platform:
validations:
required: false
nopt-9.0.0/.github/ISSUE_TEMPLATE/config.yml 0000664 0000000 0000000 00000000145 15076173424 0020224 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
blank_issues_enabled: true
nopt-9.0.0/.github/actions/ 0000775 0000000 0000000 00000000000 15076173424 0015511 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.github/actions/create-check/ 0000775 0000000 0000000 00000000000 15076173424 0020027 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.github/actions/create-check/action.yml 0000664 0000000 0000000 00000002720 15076173424 0022030 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: 'Create Check'
inputs:
name:
required: true
token:
required: true
sha:
required: true
check-name:
default: ''
outputs:
check-id:
value: ${{ steps.create-check.outputs.check_id }}
runs:
using: "composite"
steps:
- name: Get Workflow Job
uses: actions/github-script@v7
id: workflow
env:
JOB_NAME: "${{ inputs.name }}"
SHA: "${{ inputs.sha }}"
with:
result-encoding: string
script: |
const { repo: { owner, repo}, runId, serverUrl } = context
const { JOB_NAME, SHA } = process.env
const job = await github.rest.actions.listJobsForWorkflowRun({
owner,
repo,
run_id: runId,
per_page: 100
}).then(r => r.data.jobs.find(j => j.name.endsWith(JOB_NAME)))
return [
`This check is assosciated with ${serverUrl}/${owner}/${repo}/commit/${SHA}.`,
'Run logs:',
job?.html_url || `could not be found for a job ending with: "${JOB_NAME}"`,
].join(' ')
- name: Create Check
uses: LouisBrunner/checks-action@v1.6.0
id: create-check
with:
token: ${{ inputs.token }}
sha: ${{ inputs.sha }}
status: in_progress
name: ${{ inputs.check-name || inputs.name }}
output: |
{"summary":"${{ steps.workflow.outputs.result }}"}
nopt-9.0.0/.github/actions/install-latest-npm/ 0000775 0000000 0000000 00000000000 15076173424 0021241 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.github/actions/install-latest-npm/action.yml 0000664 0000000 0000000 00000003406 15076173424 0023244 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: 'Install Latest npm'
description: 'Install the latest version of npm compatible with the Node version'
inputs:
node:
description: 'Current Node version'
required: true
runs:
using: "composite"
steps:
# node 10/12/14 ship with npm@6, which is known to fail when updating itself in windows
- name: Update Windows npm
if: |
runner.os == 'Windows' && (
startsWith(inputs.node, 'v10.') ||
startsWith(inputs.node, 'v12.') ||
startsWith(inputs.node, 'v14.')
)
shell: cmd
run: |
curl -sO https://registry.npmjs.org/npm/-/npm-7.5.4.tgz
tar xf npm-7.5.4.tgz
cd package
node lib/npm.js install --no-fund --no-audit -g ..\npm-7.5.4.tgz
cd ..
rmdir /s /q package
- name: Install Latest npm
shell: bash
env:
NODE_VERSION: ${{ inputs.node }}
working-directory: ${{ runner.temp }}
run: |
MATCH=""
SPECS=("latest" "next-10" "next-9" "next-8" "next-7" "next-6")
echo "node@$NODE_VERSION"
for SPEC in ${SPECS[@]}; do
ENGINES=$(npm view npm@$SPEC --json | jq -r '.engines.node')
echo "Checking if node@$NODE_VERSION satisfies npm@$SPEC ($ENGINES)"
if npx semver -r "$ENGINES" "$NODE_VERSION" > /dev/null; then
MATCH=$SPEC
echo "Found compatible version: npm@$MATCH"
break
fi
done
if [ -z $MATCH ]; then
echo "Could not find a compatible version of npm for node@$NODE_VERSION"
exit 1
fi
npm i --prefer-online --no-fund --no-audit -g npm@$MATCH
- name: npm Version
shell: bash
run: npm -v
nopt-9.0.0/.github/dependabot.yml 0000664 0000000 0000000 00000000656 15076173424 0016710 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: daily
target-branch: "main"
allow:
- dependency-type: direct
versioning-strategy: increase-if-necessary
commit-message:
prefix: deps
prefix-development: chore
labels:
- "Dependencies"
open-pull-requests-limit: 10
nopt-9.0.0/.github/matchers/ 0000775 0000000 0000000 00000000000 15076173424 0015657 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.github/matchers/tap.json 0000664 0000000 0000000 00000001204 15076173424 0017333 0 ustar 00root root 0000000 0000000 {
"//@npmcli/template-oss": "This file is automatically added by @npmcli/template-oss. Do not edit.",
"problemMatcher": [
{
"owner": "tap",
"pattern": [
{
"regexp": "^\\s*not ok \\d+ - (.*)",
"message": 1
},
{
"regexp": "^\\s*---"
},
{
"regexp": "^\\s*at:"
},
{
"regexp": "^\\s*line:\\s*(\\d+)",
"line": 1
},
{
"regexp": "^\\s*column:\\s*(\\d+)",
"column": 1
},
{
"regexp": "^\\s*file:\\s*(.*)",
"file": 1
}
]
}
]
}
nopt-9.0.0/.github/settings.yml 0000664 0000000 0000000 00000001377 15076173424 0016444 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
repository:
allow_merge_commit: false
allow_rebase_merge: true
allow_squash_merge: true
squash_merge_commit_title: PR_TITLE
squash_merge_commit_message: PR_BODY
delete_branch_on_merge: true
enable_automated_security_fixes: true
enable_vulnerability_alerts: true
branches:
- name: main
protection:
required_status_checks: null
enforce_admins: true
block_creations: true
required_pull_request_reviews:
required_approving_review_count: 1
require_code_owner_reviews: true
require_last_push_approval: true
dismiss_stale_reviews: true
restrictions:
apps: []
users: []
teams: [ "cli-team" ]
nopt-9.0.0/.github/workflows/ 0000775 0000000 0000000 00000000000 15076173424 0016106 5 ustar 00root root 0000000 0000000 nopt-9.0.0/.github/workflows/audit.yml 0000664 0000000 0000000 00000002275 15076173424 0017745 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Audit
on:
workflow_dispatch:
schedule:
# "At 08:00 UTC (01:00 PT) on Monday" https://crontab.guru/#0_8_*_*_1
- cron: "0 8 * * 1"
permissions:
contents: read
jobs:
audit:
name: Audit Dependencies
if: github.repository_owner == 'npm'
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund --package-lock
- name: Run Production Audit
run: npm audit --omit=dev
- name: Run Full Audit
run: npm audit --audit-level=none
nopt-9.0.0/.github/workflows/ci-release.yml 0000664 0000000 0000000 00000010567 15076173424 0020653 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: CI - Release
on:
workflow_dispatch:
inputs:
ref:
required: true
type: string
default: main
workflow_call:
inputs:
ref:
required: true
type: string
check-sha:
required: true
type: string
permissions:
contents: read
checks: write
jobs:
lint-all:
name: Lint All
if: github.repository_owner == 'npm'
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ inputs.ref }}
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Create Check
id: create-check
if: ${{ inputs.check-sha }}
uses: ./.github/actions/create-check
with:
name: "Lint All"
token: ${{ secrets.GITHUB_TOKEN }}
sha: ${{ inputs.check-sha }}
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Lint
run: npm run lint --ignore-scripts
- name: Post Lint
run: npm run postlint --ignore-scripts
- name: Conclude Check
uses: LouisBrunner/checks-action@v1.6.0
if: steps.create-check.outputs.check-id && always()
with:
token: ${{ secrets.GITHUB_TOKEN }}
conclusion: ${{ job.status }}
check_id: ${{ steps.create-check.outputs.check-id }}
test-all:
name: Test All - ${{ matrix.platform.name }} - ${{ matrix.node-version }}
if: github.repository_owner == 'npm'
strategy:
fail-fast: false
matrix:
platform:
- name: Linux
os: ubuntu-latest
shell: bash
- name: macOS
os: macos-latest
shell: bash
- name: macOS
os: macos-13
shell: bash
node-version:
- 20.17.0
- 20.x
- 22.9.0
- 22.x
exclude:
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 20.17.0
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 20.x
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 22.9.0
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 22.x
runs-on: ${{ matrix.platform.os }}
defaults:
run:
shell: ${{ matrix.platform.shell }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ inputs.ref }}
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Create Check
id: create-check
if: ${{ inputs.check-sha }}
uses: ./.github/actions/create-check
with:
name: "Test All - ${{ matrix.platform.name }} - ${{ matrix.node-version }}"
token: ${{ secrets.GITHUB_TOKEN }}
sha: ${{ inputs.check-sha }}
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: ${{ matrix.node-version }}
check-latest: contains(matrix.node-version, '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Add Problem Matcher
run: echo "::add-matcher::.github/matchers/tap.json"
- name: Test
run: npm test --ignore-scripts
- name: Conclude Check
uses: LouisBrunner/checks-action@v1.6.0
if: steps.create-check.outputs.check-id && always()
with:
token: ${{ secrets.GITHUB_TOKEN }}
conclusion: ${{ job.status }}
check_id: ${{ steps.create-check.outputs.check-id }}
nopt-9.0.0/.github/workflows/ci.yml 0000664 0000000 0000000 00000006021 15076173424 0017223 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: CI
on:
workflow_dispatch:
pull_request:
push:
branches:
- main
schedule:
# "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1
- cron: "0 9 * * 1"
permissions:
contents: read
jobs:
lint:
name: Lint
if: github.repository_owner == 'npm'
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Lint
run: npm run lint --ignore-scripts
- name: Post Lint
run: npm run postlint --ignore-scripts
test:
name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }}
if: github.repository_owner == 'npm'
strategy:
fail-fast: false
matrix:
platform:
- name: Linux
os: ubuntu-latest
shell: bash
- name: macOS
os: macos-latest
shell: bash
- name: macOS
os: macos-13
shell: bash
node-version:
- 20.17.0
- 20.x
- 22.9.0
- 22.x
exclude:
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 20.17.0
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 20.x
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 22.9.0
- platform: { name: macOS, os: macos-13, shell: bash }
node-version: 22.x
runs-on: ${{ matrix.platform.os }}
defaults:
run:
shell: ${{ matrix.platform.shell }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: ${{ matrix.node-version }}
check-latest: contains(matrix.node-version, '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Add Problem Matcher
run: echo "::add-matcher::.github/matchers/tap.json"
- name: Test
run: npm test --ignore-scripts
nopt-9.0.0/.github/workflows/codeql-analysis.yml 0000664 0000000 0000000 00000001606 15076173424 0021724 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: CodeQL
on:
push:
branches:
- main
pull_request:
branches:
- main
schedule:
# "At 10:00 UTC (03:00 PT) on Monday" https://crontab.guru/#0_10_*_*_1
- cron: "0 10 * * 1"
permissions:
contents: read
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: javascript
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
nopt-9.0.0/.github/workflows/post-dependabot.yml 0000664 0000000 0000000 00000012004 15076173424 0021716 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Post Dependabot
on: pull_request
permissions:
contents: write
jobs:
template-oss:
name: template-oss
if: github.repository_owner == 'npm' && github.actor == 'dependabot[bot]'
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Fetch Dependabot Metadata
id: metadata
uses: dependabot/fetch-metadata@v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
# Dependabot can update multiple directories so we output which directory
# it is acting on so we can run the command for the correct root or workspace
- name: Get Dependabot Directory
if: contains(steps.metadata.outputs.dependency-names, '@npmcli/template-oss')
id: flags
run: |
dependabot_dir="${{ steps.metadata.outputs.directory }}"
if [[ "$dependabot_dir" == "/" || "$dependabot_dir" == "/main" ]]; then
echo "workspace=-iwr" >> $GITHUB_OUTPUT
else
# strip leading slash from directory so it works as a
# a path to the workspace flag
echo "workspace=--workspace ${dependabot_dir#/}" >> $GITHUB_OUTPUT
fi
- name: Apply Changes
if: steps.flags.outputs.workspace
id: apply
run: |
npm run template-oss-apply ${{ steps.flags.outputs.workspace }}
if [[ `git status --porcelain` ]]; then
echo "changes=true" >> $GITHUB_OUTPUT
fi
# This only sets the conventional commit prefix. This workflow can't reliably determine
# what the breaking change is though. If a BREAKING CHANGE message is required then
# this PR check will fail and the commit will be amended with stafftools
if [[ "${{ steps.metadata.outputs.update-type }}" == "version-update:semver-major" ]]; then
prefix='feat!'
else
prefix='chore'
fi
echo "message=$prefix: postinstall for dependabot template-oss PR" >> $GITHUB_OUTPUT
# This step will fail if template-oss has made any workflow updates. It is impossible
# for a workflow to update other workflows. In the case it does fail, we continue
# and then try to apply only a portion of the changes in the next step
- name: Push All Changes
if: steps.apply.outputs.changes
id: push
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git commit -am "${{ steps.apply.outputs.message }}"
git push
# If the previous step failed, then reset the commit and remove any workflow changes
# and attempt to commit and push again. This is helpful because we will have a commit
# with the correct prefix that we can then --amend with @npmcli/stafftools later.
- name: Push All Changes Except Workflows
if: steps.apply.outputs.changes && steps.push.outcome == 'failure'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git reset HEAD~
git checkout HEAD -- .github/workflows/
git clean -fd .github/workflows/
git commit -am "${{ steps.apply.outputs.message }}"
git push
# Check if all the necessary template-oss changes were applied. Since we continued
# on errors in one of the previous steps, this check will fail if our follow up
# only applied a portion of the changes and we need to followup manually.
#
# Note that this used to run `lint` and `postlint` but that will fail this action
# if we've also shipped any linting changes separate from template-oss. We do
# linting in another action, so we want to fail this one only if there are
# template-oss changes that could not be applied.
- name: Check Changes
if: steps.apply.outputs.changes
run: |
npm exec --offline ${{ steps.flags.outputs.workspace }} -- template-oss-check
- name: Fail on Breaking Change
if: steps.apply.outputs.changes && startsWith(steps.apply.outputs.message, 'feat!')
run: |
echo "This PR has a breaking change. Run 'npx -p @npmcli/stafftools gh template-oss-fix'"
echo "for more information on how to fix this with a BREAKING CHANGE footer."
exit 1
nopt-9.0.0/.github/workflows/pull-request.yml 0000664 0000000 0000000 00000002737 15076173424 0021304 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Pull Request
on:
pull_request:
types:
- opened
- reopened
- edited
- synchronize
permissions:
contents: read
jobs:
commitlint:
name: Lint Commits
if: github.repository_owner == 'npm'
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Run Commitlint on Commits
id: commit
continue-on-error: true
run: npx --offline commitlint -V --from 'origin/${{ github.base_ref }}' --to ${{ github.event.pull_request.head.sha }}
- name: Run Commitlint on PR Title
if: steps.commit.outcome == 'failure'
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: echo "$PR_TITLE" | npx --offline commitlint -V
nopt-9.0.0/.github/workflows/release-integration.yml 0000664 0000000 0000000 00000004163 15076173424 0022576 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Release Integration
on:
workflow_dispatch:
inputs:
releases:
required: true
type: string
description: 'A json array of releases. Required fields: publish: tagName, publishTag. publish check: pkgName, version'
workflow_call:
inputs:
releases:
required: true
type: string
description: 'A json array of releases. Required fields: publish: tagName, publishTag. publish check: pkgName, version'
secrets:
PUBLISH_TOKEN:
required: true
permissions:
contents: read
id-token: write
jobs:
publish:
name: Publish
runs-on: ubuntu-latest
defaults:
run:
shell: bash
permissions:
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ fromJSON(inputs.releases)[0].tagName }}
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Set npm authToken
run: npm config set '//registry.npmjs.org/:_authToken'=\${PUBLISH_TOKEN}
- name: Publish
env:
PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }}
RELEASES: ${{ inputs.releases }}
run: |
EXIT_CODE=0
for release in $(echo $RELEASES | jq -r '.[] | @base64'); do
PUBLISH_TAG=$(echo "$release" | base64 --decode | jq -r .publishTag)
npm publish --provenance --tag="$PUBLISH_TAG"
STATUS=$?
if [[ "$STATUS" -eq 1 ]]; then
EXIT_CODE=$STATUS
fi
done
exit $EXIT_CODE
nopt-9.0.0/.github/workflows/release.yml 0000664 0000000 0000000 00000026106 15076173424 0020256 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
name: Release
on:
push:
branches:
- main
permissions:
contents: write
pull-requests: write
checks: write
jobs:
release:
outputs:
pr: ${{ steps.release.outputs.pr }}
pr-branch: ${{ steps.release.outputs.pr-branch }}
pr-number: ${{ steps.release.outputs.pr-number }}
pr-sha: ${{ steps.release.outputs.pr-sha }}
releases: ${{ steps.release.outputs.releases }}
comment-id: ${{ steps.create-comment.outputs.comment-id || steps.update-comment.outputs.comment-id }}
check-id: ${{ steps.create-check.outputs.check-id }}
name: Release
if: github.repository_owner == 'npm'
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Release Please
id: release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: npx --offline template-oss-release-please --branch="${{ github.ref_name }}" --backport="" --defaultTag="latest"
- name: Create Release Manager Comment Text
if: steps.release.outputs.pr-number
uses: actions/github-script@v7
id: comment-text
with:
result-encoding: string
script: |
const { runId, repo: { owner, repo } } = context
const { data: workflow } = await github.rest.actions.getWorkflowRun({ owner, repo, run_id: runId })
return['## Release Manager', `Release workflow run: ${workflow.html_url}`].join('\n\n')
- name: Find Release Manager Comment
uses: peter-evans/find-comment@v2
if: steps.release.outputs.pr-number
id: found-comment
with:
issue-number: ${{ steps.release.outputs.pr-number }}
comment-author: 'github-actions[bot]'
body-includes: '## Release Manager'
- name: Create Release Manager Comment
id: create-comment
if: steps.release.outputs.pr-number && !steps.found-comment.outputs.comment-id
uses: peter-evans/create-or-update-comment@v3
with:
issue-number: ${{ steps.release.outputs.pr-number }}
body: ${{ steps.comment-text.outputs.result }}
- name: Update Release Manager Comment
id: update-comment
if: steps.release.outputs.pr-number && steps.found-comment.outputs.comment-id
uses: peter-evans/create-or-update-comment@v3
with:
comment-id: ${{ steps.found-comment.outputs.comment-id }}
body: ${{ steps.comment-text.outputs.result }}
edit-mode: 'replace'
- name: Create Check
id: create-check
uses: ./.github/actions/create-check
if: steps.release.outputs.pr-sha
with:
name: "Release"
token: ${{ secrets.GITHUB_TOKEN }}
sha: ${{ steps.release.outputs.pr-sha }}
update:
needs: release
outputs:
sha: ${{ steps.commit.outputs.sha }}
check-id: ${{ steps.create-check.outputs.check-id }}
name: Update - Release
if: github.repository_owner == 'npm' && needs.release.outputs.pr
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ needs.release.outputs.pr-branch }}
- name: Setup Git User
run: |
git config --global user.email "npm-cli+bot@github.com"
git config --global user.name "npm CLI robot"
- name: Setup Node
uses: actions/setup-node@v4
id: node
with:
node-version: 22.x
check-latest: contains('22.x', '.x')
- name: Install Latest npm
uses: ./.github/actions/install-latest-npm
with:
node: ${{ steps.node.outputs.node-version }}
- name: Install Dependencies
run: npm i --ignore-scripts --no-audit --no-fund
- name: Create Release Manager Checklist Text
id: comment-text
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: npm exec --offline -- template-oss-release-manager --pr="${{ needs.release.outputs.pr-number }}" --backport="" --defaultTag="latest" --publish
- name: Append Release Manager Comment
uses: peter-evans/create-or-update-comment@v3
with:
comment-id: ${{ needs.release.outputs.comment-id }}
body: ${{ steps.comment-text.outputs.result }}
edit-mode: 'append'
- name: Run Post Pull Request Actions
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: npm run rp-pull-request --ignore-scripts --if-present -- --pr="${{ needs.release.outputs.pr-number }}" --commentId="${{ needs.release.outputs.comment-id }}"
- name: Commit
id: commit
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git commit --all --amend --no-edit || true
git push --force-with-lease
echo "sha=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
- name: Create Check
id: create-check
uses: ./.github/actions/create-check
with:
name: "Update - Release"
check-name: "Release"
token: ${{ secrets.GITHUB_TOKEN }}
sha: ${{ steps.commit.outputs.sha }}
- name: Conclude Check
uses: LouisBrunner/checks-action@v1.6.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
conclusion: ${{ job.status }}
check_id: ${{ needs.release.outputs.check-id }}
ci:
name: CI - Release
needs: [ release, update ]
if: needs.release.outputs.pr
uses: ./.github/workflows/ci-release.yml
with:
ref: ${{ needs.release.outputs.pr-branch }}
check-sha: ${{ needs.update.outputs.sha }}
post-ci:
needs: [ release, update, ci ]
name: Post CI - Release
if: github.repository_owner == 'npm' && needs.release.outputs.pr && always()
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Get CI Conclusion
id: conclusion
run: |
result=""
if [[ "${{ contains(needs.*.result, 'failure') }}" == "true" ]]; then
result="failure"
elif [[ "${{ contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
result="cancelled"
else
result="success"
fi
echo "result=$result" >> $GITHUB_OUTPUT
- name: Conclude Check
uses: LouisBrunner/checks-action@v1.6.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
conclusion: ${{ steps.conclusion.outputs.result }}
check_id: ${{ needs.update.outputs.check-id }}
post-release:
needs: release
outputs:
comment-id: ${{ steps.create-comment.outputs.comment-id }}
name: Post Release - Release
if: github.repository_owner == 'npm' && needs.release.outputs.releases
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Create Release PR Comment Text
id: comment-text
uses: actions/github-script@v7
env:
RELEASES: ${{ needs.release.outputs.releases }}
with:
result-encoding: string
script: |
const releases = JSON.parse(process.env.RELEASES)
const { runId, repo: { owner, repo } } = context
const issue_number = releases[0].prNumber
const runUrl = `https://github.com/${owner}/${repo}/actions/runs/${runId}`
return [
'## Release Workflow\n',
...releases.map(r => `- \`${r.pkgName}@${r.version}\` ${r.url}`),
`- Workflow run: :arrows_counterclockwise: ${runUrl}`,
].join('\n')
- name: Create Release PR Comment
id: create-comment
uses: peter-evans/create-or-update-comment@v3
with:
issue-number: ${{ fromJSON(needs.release.outputs.releases)[0].prNumber }}
body: ${{ steps.comment-text.outputs.result }}
release-integration:
needs: release
name: Release Integration
if: needs.release.outputs.releases
uses: ./.github/workflows/release-integration.yml
permissions:
contents: read
id-token: write
secrets:
PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }}
with:
releases: ${{ needs.release.outputs.releases }}
post-release-integration:
needs: [ release, release-integration, post-release ]
name: Post Release Integration - Release
if: github.repository_owner == 'npm' && needs.release.outputs.releases && always()
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Get Post Release Conclusion
id: conclusion
run: |
if [[ "${{ contains(needs.*.result, 'failure') }}" == "true" ]]; then
result="x"
elif [[ "${{ contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
result="heavy_multiplication_x"
else
result="white_check_mark"
fi
echo "result=$result" >> $GITHUB_OUTPUT
- name: Find Release PR Comment
uses: peter-evans/find-comment@v2
id: found-comment
with:
issue-number: ${{ fromJSON(needs.release.outputs.releases)[0].prNumber }}
comment-author: 'github-actions[bot]'
body-includes: '## Release Workflow'
- name: Create Release PR Comment Text
id: comment-text
if: steps.found-comment.outputs.comment-id
uses: actions/github-script@v7
env:
RESULT: ${{ steps.conclusion.outputs.result }}
BODY: ${{ steps.found-comment.outputs.comment-body }}
with:
result-encoding: string
script: |
const { RESULT, BODY } = process.env
const body = [BODY.replace(/(Workflow run: :)[a-z_]+(:)/, `$1${RESULT}$2`)]
if (RESULT !== 'white_check_mark') {
body.push(':rotating_light::rotating_light::rotating_light:')
body.push([
'@npm/cli-team: The post-release workflow failed for this release.',
'Manual steps may need to be taken after examining the workflow output.'
].join(' '))
body.push(':rotating_light::rotating_light::rotating_light:')
}
return body.join('\n\n').trim()
- name: Update Release PR Comment
if: steps.comment-text.outputs.result
uses: peter-evans/create-or-update-comment@v3
with:
comment-id: ${{ steps.found-comment.outputs.comment-id }}
body: ${{ steps.comment-text.outputs.result }}
edit-mode: 'replace'
nopt-9.0.0/.gitignore 0000664 0000000 0000000 00000001050 15076173424 0014475 0 ustar 00root root 0000000 0000000 # This file is automatically added by @npmcli/template-oss. Do not edit.
# ignore everything in the root
/*
!**/.gitignore
!/.commitlintrc.js
!/.eslint.config.js
!/.eslintrc.js
!/.eslintrc.local.*
!/.git-blame-ignore-revs
!/.github/
!/.gitignore
!/.npmrc
!/.prettierignore
!/.prettierrc.js
!/.release-please-manifest.json
!/bin/
!/CHANGELOG*
!/CODE_OF_CONDUCT.md
!/CONTRIBUTING.md
!/docs/
!/lib/
!/LICENSE*
!/map.js
!/package.json
!/README*
!/release-please-config.json
!/scripts/
!/SECURITY.md
!/tap-snapshots/
!/test/
!/tsconfig.json
tap-testdir*/
nopt-9.0.0/.npmrc 0000664 0000000 0000000 00000000135 15076173424 0013630 0 ustar 00root root 0000000 0000000 ; This file is automatically added by @npmcli/template-oss. Do not edit.
package-lock=false
nopt-9.0.0/.release-please-manifest.json 0000664 0000000 0000000 00000000023 15076173424 0020150 0 ustar 00root root 0000000 0000000 {
".": "9.0.0"
}
nopt-9.0.0/CHANGELOG.md 0000664 0000000 0000000 00000023214 15076173424 0014324 0 ustar 00root root 0000000 0000000 # Changelog
## [9.0.0](https://github.com/npm/nopt/compare/v8.1.0...v9.0.0) (2025-10-22)
### ⚠️ BREAKING CHANGES
* `nopt` now supports node `^20.17.0 || >=22.9.0`
### Bug Fixes
* [`d304e27`](https://github.com/npm/nopt/commit/d304e2760823ac02925c5d1dfb1593554603e30a) [#189](https://github.com/npm/nopt/pull/189) align to npm 11 node engine range (@owlstronaut)
### Dependencies
* [`5b85c97`](https://github.com/npm/nopt/commit/5b85c97364837a9739b6eae8d2bc4a9b780134bd) [#189](https://github.com/npm/nopt/pull/189) `abbrev@4.0.0`
### Chores
* [`ffb5dad`](https://github.com/npm/nopt/commit/ffb5dad71d1c6c72a6c299d735d9adb461410913) [#189](https://github.com/npm/nopt/pull/189) template-oss-apply (@owlstronaut)
* [`af91ff2`](https://github.com/npm/nopt/commit/af91ff27ef60d64c1aa6a092627e39ea0a905820) [#188](https://github.com/npm/nopt/pull/188) bump @npmcli/template-oss from 4.26.0 to 4.27.1 (#188) (@dependabot[bot], @npm-cli-bot)
## [8.1.0](https://github.com/npm/nopt/compare/v8.0.0...v8.1.0) (2025-01-21)
### Features
* [`3319782`](https://github.com/npm/nopt/commit/33197822ef1bbcefe8878531598cea25088595fc) [#180](https://github.com/npm/nopt/pull/180) add unknownHandler and abbrevHandler (@wraithgar)
### Bug Fixes
* [`304b903`](https://github.com/npm/nopt/commit/304b903c118ac10ed28c0cc4b3fab6c32b6b4da0) [#179](https://github.com/npm/nopt/pull/179) log warnings about unknown config situations (@wraithgar)
### Dependencies
* [`a7156b2`](https://github.com/npm/nopt/commit/a7156b2491a82bca3950c4ea6b3059697ae5b638) [#180](https://github.com/npm/nopt/pull/180) remove proc-log
* [`8dd86dd`](https://github.com/npm/nopt/commit/8dd86ddbd2d93bac42b03c826ea2292256abb32e) [#179](https://github.com/npm/nopt/pull/179) add `proc-log@5.0.0`
* [`9e64314`](https://github.com/npm/nopt/commit/9e64314c2c688b8309f6a9fa6c5d23ff60b4b7b8) [#176](https://github.com/npm/nopt/pull/176) bump abbrev from 2.0.0 to 3.0.0 (#176)
### Chores
* [`d7916cd`](https://github.com/npm/nopt/commit/d7916cd03d22e6653ce7c3d6e90f6557dee789a1) [#181](https://github.com/npm/nopt/pull/181) bump @npmcli/template-oss from 4.23.4 to 4.23.6 (#181) (@dependabot[bot], @npm-cli-bot)
## [8.0.0](https://github.com/npm/nopt/compare/v7.2.1...v8.0.0) (2024-09-03)
### ⚠️ BREAKING CHANGES
* `nopt` now supports node `^18.17.0 || >=20.5.0`
### Bug Fixes
* [`208d02b`](https://github.com/npm/nopt/commit/208d02bba7e5934086d0b53228fb4272d91fa07d) [#174](https://github.com/npm/nopt/pull/174) align to npm 10 node engine range (@hashtagchris)
### Chores
* [`a8e567c`](https://github.com/npm/nopt/commit/a8e567cd637d02cb5cb19c1b0a01d888bc48f38b) [#174](https://github.com/npm/nopt/pull/174) run template-oss-apply (@hashtagchris)
* [`5429145`](https://github.com/npm/nopt/commit/54291454fdd28107257a2d109314f886f15356f0) [#172](https://github.com/npm/nopt/pull/172) bump @npmcli/eslint-config from 4.0.5 to 5.0.0 (@dependabot[bot])
* [`5eeda97`](https://github.com/npm/nopt/commit/5eeda97149cfae9f4d93d74553109c576cd5babc) [#173](https://github.com/npm/nopt/pull/173) postinstall for dependabot template-oss PR (@hashtagchris)
* [`bff360b`](https://github.com/npm/nopt/commit/bff360bdcf65f89df5983a4842691802b8811050) [#173](https://github.com/npm/nopt/pull/173) bump @npmcli/template-oss from 4.23.1 to 4.23.3 (@dependabot[bot])
## [7.2.1](https://github.com/npm/nopt/compare/v7.2.0...v7.2.1) (2024-05-04)
### Bug Fixes
* [`2fb2144`](https://github.com/npm/nopt/commit/2fb21444311086adb561de0eed68ccff155fd444) [#160](https://github.com/npm/nopt/pull/160) linting: no-unused-vars (@lukekarrys)
### Chores
* [`2bdcfcb`](https://github.com/npm/nopt/commit/2bdcfcbc11059556899d5bf448ac527ad294efdf) [#160](https://github.com/npm/nopt/pull/160) bump @npmcli/template-oss to 4.22.0 (@lukekarrys)
* [`0aa1d01`](https://github.com/npm/nopt/commit/0aa1d01d99cacc5f1cc73071e1b476039b6ef2f5) [#160](https://github.com/npm/nopt/pull/160) postinstall for dependabot template-oss PR (@lukekarrys)
* [`28cb4e1`](https://github.com/npm/nopt/commit/28cb4e19f4c80fcd440c64e81fde8ba872a9a976) [#159](https://github.com/npm/nopt/pull/159) bump @npmcli/template-oss from 4.21.3 to 4.21.4 (@dependabot[bot])
## [7.2.0](https://github.com/npm/nopt/compare/v7.1.0...v7.2.0) (2023-06-15)
### Features
* [`008c672`](https://github.com/npm/nopt/commit/008c672daccf9e6fadcb349b95221c9e166d6a9e) [#125](https://github.com/npm/nopt/pull/125) add fallback option to use function when looking up types (@lukekarrys)
* [`082bad3`](https://github.com/npm/nopt/commit/082bad3511cb41a382fd596584fb178b5694e851) [#124](https://github.com/npm/nopt/pull/124) allow setting `typeDefault` on `nopt` and `clean` lib methods (@lukekarrys)
### Bug Fixes
* [`a28412f`](https://github.com/npm/nopt/commit/a28412fd5299a1adcd1fbfd549ee4aa2f51c504d) [#127](https://github.com/npm/nopt/pull/127) cleanup bin (#127) (@lukekarrys)
* [`7f5b507`](https://github.com/npm/nopt/commit/7f5b50795ba3b658223a8a15489369578393e594) [#126](https://github.com/npm/nopt/pull/126) 100 test coverage (#126) (@lukekarrys)
## [7.1.0](https://github.com/npm/nopt/compare/v7.0.0...v7.1.0) (2023-03-08)
### Features
* [`6830137`](https://github.com/npm/nopt/commit/68301373544fe6a5802360eedd114cacfc3340f7) [#116](https://github.com/npm/nopt/pull/116) add lib export to use nopt in non-global mode (#116) (@lukekarrys)
### Bug Fixes
* [`ce918b9`](https://github.com/npm/nopt/commit/ce918b99911acb85060ef25e600db1bc1c626c2e) [#114](https://github.com/npm/nopt/pull/114) remove dead code (@wraithgar)
## [7.0.0](https://github.com/npm/nopt/compare/v6.0.0...v7.0.0) (2022-11-02)
### ⚠️ BREAKING CHANGES
* `nopt` is now compatible with the following semver range for node: `^14.17.0 || ^16.13.0 || >=18.0.0`
### Features
* [`f905544`](https://github.com/npm/nopt/commit/f9055443d05cf155de44d9cae1fb2d65b3adba10) [#101](https://github.com/npm/nopt/pull/101) postinstall for dependabot template-oss PR (@lukekarrys)
### Dependencies
* [`040677d`](https://github.com/npm/nopt/commit/040677de5492fef5d2c91a180e1e73093d40b951) [#111](https://github.com/npm/nopt/pull/111) bump abbrev from 1.1.1 to 2.0.0 (#111)
## [6.0.0](https://github.com/npm/nopt/compare/v5.0.0...v6.0.0) (2022-07-20)
### ⚠ BREAKING CHANGES
* This drops support for node 6 through 10 and non-LTS versions of node12 and node14
### Bug Fixes
* linting ([0cb6aa8](https://github.com/npm/nopt/commit/0cb6aa835eb07279cb063a68a5a1ec999745cb5b))
* replace deprecated String.prototype.substr() ([#85](https://github.com/npm/nopt/issues/85)) ([40c686f](https://github.com/npm/nopt/commit/40c686faffc600ed6f53c5ef1c3c6e1eaeda7c77))
* @npmcli/template-oss@3.5.0 ([56e6c7e](https://github.com/npm/nopt/commit/56e6c7e158737b590ea97fc1aa1d6837451a389d))
### Dependencies
* fix abbrev requirement to use proper spec ([b8c751a](https://github.com/npm/nopt/commit/b8c751a0763b2f622291040fe92ad9547b22a8a9))
### v4.0.1 (2016-12-14)
#### WHOOPS
* [`fb9b1ce`](https://github.com/npm/nopt/commit/fb9b1ce57b3c69b4f7819015be87719204f77ef6)
Merged so many patches at once that the code fencing
([@adius](https://github.com/adius)) added got broken. Sorry,
([@adius](https://github.com/adius))!
([@othiym23](https://github.com/othiym23))
### v4.0.0 (2016-12-13)
#### BREAKING CHANGES
* [`651d447`](https://github.com/npm/nopt/commit/651d4473946096d341a480bbe56793de3fc706aa)
When parsing String-typed arguments, if the next value is `""`, don't simply
swallow it. ([@samjonester](https://github.com/samjonester))
#### PERFORMANCE TWEAKS
* [`3370ce8`](https://github.com/npm/nopt/commit/3370ce87a7618ba228883861db84ddbcdff252a9)
Simplify initialization. ([@elidoran](https://github.com/elidoran))
* [`356e58e`](https://github.com/npm/nopt/commit/356e58e3b3b431a4b1af7fd7bdee44c2c0526a09)
Store `Array.isArray(types[arg])` for reuse.
([@elidoran](https://github.com/elidoran))
* [`0d95e90`](https://github.com/npm/nopt/commit/0d95e90515844f266015b56d2c80b94e5d14a07e)
Interpret single-item type arrays as a single type.
([@samjonester](https://github.com/samjonester))
* [`07c69d3`](https://github.com/npm/nopt/commit/07c69d38b5186450941fbb505550becb78a0e925)
Simplify key-value extraction. ([@elidoran](https://github.com/elidoran))
* [`39b6e5c`](https://github.com/npm/nopt/commit/39b6e5c65ac47f60cd43a1fbeece5cd4c834c254)
Only call `Date.parse(val)` once. ([@elidoran](https://github.com/elidoran))
* [`934943d`](https://github.com/npm/nopt/commit/934943dffecb55123a2b15959fe2a359319a5dbd)
Use `osenv.home()` to find a user's home directory instead of assuming it's
always `$HOME`. ([@othiym23](https://github.com/othiym23))
#### TEST & CI IMPROVEMENTS
* [`326ffff`](https://github.com/npm/nopt/commit/326ffff7f78a00bcd316adecf69075f8a8093619)
Fix `/tmp` test to work on Windows.
([@elidoran](https://github.com/elidoran))
* [`c89d31a`](https://github.com/npm/nopt/commit/c89d31a49d14f2238bc6672db08da697bbc57f1b)
Only run Windows tests on Windows, only run Unix tests on a Unix.
([@elidoran](https://github.com/elidoran))
* [`affd3d1`](https://github.com/npm/nopt/commit/affd3d1d0addffa93006397b2013b18447339366)
Refresh Travis to run the tests against the currently-supported batch of npm
versions. ([@helio](https://github.com/helio)-frota)
* [`55f9449`](https://github.com/npm/nopt/commit/55f94497d163ed4d16dd55fd6c4fb95cc440e66d)
`tap@8.0.1` ([@othiym23](https://github.com/othiym23))
#### DOC TWEAKS
* [`5271229`](https://github.com/npm/nopt/commit/5271229ee7c810217dd51616c086f5d9ab224581)
Use JavaScript code block for syntax highlighting.
([@adius](https://github.com/adius))
* [`c0d156f`](https://github.com/npm/nopt/commit/c0d156f229f9994c5dfcec4a8886eceff7a07682)
The code sample in the README had `many2: [ oneThing ]`, and now it has
`many2: [ two, things ]`. ([@silkentrance](https://github.com/silkentrance))
nopt-9.0.0/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000000507 15076173424 0015312 0 ustar 00root root 0000000 0000000
All interactions in this repo are covered by the [npm Code of
Conduct](https://docs.npmjs.com/policies/conduct)
The npm cli team may, at its own discretion, moderate, remove, or edit
any interactions such as pull requests, issues, and comments.
nopt-9.0.0/CONTRIBUTING.md 0000664 0000000 0000000 00000005133 15076173424 0014744 0 ustar 00root root 0000000 0000000
# Contributing
## Code of Conduct
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).
## Reporting Bugs
Before submitting a new bug report please search for an existing or similar report.
Use one of our existing issue templates if you believe you've come across a unique problem.
Duplicate issues, or issues that don't use one of our templates may get closed without a response.
## Pull Request Conventions
### Commits
We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).
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:
- `feat`: For when introducing a new feature. The result will be a new semver minor version of the package when it is next published.
- `fix`: For bug fixes. The result will be a new semver patch version of the package when it is next published.
- `docs`: For documentation updates. The result will be a new semver patch version of the package when it is next published.
- `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).
### Test Coverage
Pull requests made against this repo will run `npm test` automatically. Please make sure tests pass locally before submitting a PR.
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.
### Linting
Linting is also done automatically once tests pass. `npm run lintfix` will fix most linting errors automatically.
Please make sure linting passes before submitting a PR.
## What _not_ to contribute?
### Dependencies
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.
### Tools/Automation
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.
nopt-9.0.0/LICENSE 0000664 0000000 0000000 00000001375 15076173424 0013524 0 ustar 00root root 0000000 0000000 The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
nopt-9.0.0/README.md 0000664 0000000 0000000 00000017457 15076173424 0014006 0 ustar 00root root 0000000 0000000 If you want to write an option parser, and have it be good, there are
two ways to do it. The Right Way, and the Wrong Way.
The Wrong Way is to sit down and write an option parser. We've all done
that.
The Right Way is to write some complex configurable program with so many
options that you hit the limit of your frustration just trying to
manage them all, and defer it with duct-tape solutions until you see
exactly to the core of the problem, and finally snap and write an
awesome option parser.
If you want to write an option parser, don't write an option parser.
Write a package manager, or a source control system, or a service
restarter, or an operating system. You probably won't end up with a
good one of those, but if you don't give up, and you are relentless and
diligent enough in your procrastination, you may just end up with a very
nice option parser.
## USAGE
```javascript
// my-program.js
var nopt = require("nopt")
, Stream = require("stream").Stream
, path = require("path")
, knownOpts = { "foo" : [String, null]
, "bar" : [Stream, Number]
, "baz" : path
, "bloo" : [ "big", "medium", "small" ]
, "flag" : Boolean
, "pick" : Boolean
, "many1" : [String, Array]
, "many2" : [path, Array]
}
, shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
, "b7" : ["--bar", "7"]
, "m" : ["--bloo", "medium"]
, "p" : ["--pick"]
, "f" : ["--flag"]
}
// everything is optional.
// knownOpts and shorthands default to {}
// arg list defaults to process.argv
// slice defaults to 2
, parsed = nopt(knownOpts, shortHands, process.argv, 2)
console.log(parsed)
```
This would give you support for any of the following:
```console
$ node my-program.js --foo "blerp" --no-flag
{ "foo" : "blerp", "flag" : false }
$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
{ bar: 7, foo: "Mr. Hand", flag: true }
$ node my-program.js --foo "blerp" -f -----p
{ foo: "blerp", flag: true, pick: true }
$ node my-program.js -fp --foofoo
{ foo: "Mr. Foo", flag: true, pick: true }
$ node my-program.js --foofoo -- -fp # -- stops the flag parsing.
{ foo: "Mr. Foo", argv: { remain: ["-fp"] } }
$ node my-program.js --blatzk -fp # unknown opts are ok.
{ blatzk: true, flag: true, pick: true }
$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value
{ blatzk: 1000, flag: true, pick: true }
$ node my-program.js --no-blatzk -fp # unless they start with "no-"
{ blatzk: false, flag: true, pick: true }
$ node my-program.js --baz b/a/z # known paths are resolved.
{ baz: "/Users/isaacs/b/a/z" }
# if Array is one of the types, then it can take many
# values, and will always be an array. The other types provided
# specify what types are allowed in the list.
$ node my-program.js --many1 5 --many1 null --many1 foo
{ many1: ["5", "null", "foo"] }
$ node my-program.js --many2 foo --many2 bar
{ many2: ["/path/to/foo", "path/to/bar"] }
```
Read the tests at the bottom of `lib/nopt.js` for more examples of
what this puppy can do.
## Types
The following types are supported, and defined on `nopt.typeDefs`
* String: A normal string. No parsing is done.
* path: A file system path. Gets resolved against cwd if not absolute.
* url: A url. If it doesn't parse, it isn't accepted.
* Number: Must be numeric.
* Date: Must parse as a date. If it does, and `Date` is one of the options,
then it will return a Date object, not a string.
* Boolean: Must be either `true` or `false`. If an option is a boolean,
then it does not need a value, and its presence will imply `true` as
the value. To negate boolean flags, do `--no-whatever` or `--whatever
false`
* NaN: Means that the option is strictly not allowed. Any value will
fail.
* Stream: An object matching the "Stream" class in node. Valuable
for use when validating programmatically. (npm uses this to let you
supply any WriteStream on the `outfd` and `logfd` config options.)
* Array: If `Array` is specified as one of the types, then the value
will be parsed as a list of options. This means that multiple values
can be specified, and that the value will always be an array.
If a type is an array of values not on this list, then those are
considered valid values. For instance, in the example above, the
`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`,
and any other value will be rejected.
When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be
interpreted as their JavaScript equivalents.
You can also mix types and values, or multiple types, in a list. For
instance `{ blah: [Number, null] }` would allow a value to be set to
either a Number or null. When types are ordered, this implies a
preference, and the first type that can be used to properly interpret
the value will be used.
To define a new type, add it to `nopt.typeDefs`. Each item in that
hash is an object with a `type` member and a `validate` method. The
`type` member is an object that matches what goes in the type list. The
`validate` method is a function that gets called with `validate(data,
key, val)`. Validate methods should assign `data[key]` to the valid
value of `val` if it can be handled properly, or return boolean
`false` if it cannot.
You can also call `nopt.clean(data, types, typeDefs)` to clean up a
config object and remove its invalid properties.
## Error Handling
By default nopt logs debug messages if `DEBUG_NOPT` or `NOPT_DEBUG` are set in the environment.
You can assign the following methods to `nopt` for a more granular notification of invalid, unknown, and expanding options:
`nopt.invalidHandler(key, value, type, data)` - Called when a value is invalid for its option.
`nopt.unknownHandler(key, next)` - Called when an option is found that has no configuration. In certain situations the next option on the command line will be parsed on its own instead of as part of the unknown option. In this case `next` will contain that option.
`nopt.abbrevHandler(short, long)` - Called when an option is automatically translated via abbreviations.
You can also set any of these to `false` to disable the debugging messages that they generate.
## Abbreviations
Yes, they are supported. If you define options like this:
```javascript
{ "foolhardyelephants" : Boolean
, "pileofmonkeys" : Boolean }
```
Then this will work:
```bash
node program.js --foolhar --pil
node program.js --no-f --pileofmon
# etc.
```
## Shorthands
Shorthands are a hash of shorter option names to a snippet of args that
they expand to.
If multiple one-character shorthands are all combined, and the
combination does not unambiguously match any other option or shorthand,
then they will be broken up into their constituent parts. For example:
```json
{ "s" : ["--loglevel", "silent"]
, "g" : "--global"
, "f" : "--force"
, "p" : "--parseable"
, "l" : "--long"
}
```
```bash
npm ls -sgflp
# just like doing this:
npm ls --loglevel silent --global --force --long --parseable
```
## The Rest of the args
The config object returned by nopt is given a special member called
`argv`, which is an object with the following fields:
* `remain`: The remaining args after all the parsing has occurred.
* `original`: The args as they originally appeared.
* `cooked`: The args after flags and shorthands are expanded.
## Slicing
Node programs are called with more or less the exact argv as it appears
in C land, after the v8 and node-specific options have been plucked off.
As such, `argv[0]` is always `node` and `argv[1]` is always the
JavaScript program being run.
That's usually not very useful to you. So they're sliced off by
default. If you want them, then you can pass in `0` as the last
argument, or any other number that you'd like to slice off the start of
the list.
nopt-9.0.0/SECURITY.md 0000664 0000000 0000000 00000002320 15076173424 0014277 0 ustar 00root root 0000000 0000000
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).
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.
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).
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.
**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**
Thanks for helping make GitHub safe for everyone.
nopt-9.0.0/bin/ 0000775 0000000 0000000 00000000000 15076173424 0013261 5 ustar 00root root 0000000 0000000 nopt-9.0.0/bin/nopt.js 0000775 0000000 0000000 00000001204 15076173424 0014577 0 ustar 00root root 0000000 0000000 #!/usr/bin/env node
const nopt = require('../lib/nopt')
const path = require('path')
console.log('parsed', nopt({
num: Number,
bool: Boolean,
help: Boolean,
list: Array,
'num-list': [Number, Array],
'str-list': [String, Array],
'bool-list': [Boolean, Array],
str: String,
clear: Boolean,
config: Boolean,
length: Number,
file: path,
}, {
s: ['--str', 'astring'],
b: ['--bool'],
nb: ['--no-bool'],
tft: ['--bool-list', '--no-bool-list', '--bool-list', 'true'],
'?': ['--help'],
h: ['--help'],
H: ['--help'],
n: ['--num', '125'],
c: ['--config'],
l: ['--length'],
f: ['--file'],
}, process.argv, 2))
nopt-9.0.0/lib/ 0000775 0000000 0000000 00000000000 15076173424 0013257 5 ustar 00root root 0000000 0000000 nopt-9.0.0/lib/debug.js 0000664 0000000 0000000 00000000265 15076173424 0014706 0 ustar 00root root 0000000 0000000 /* istanbul ignore next */
module.exports = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG
// eslint-disable-next-line no-console
? (...a) => console.error(...a)
: () => {}
nopt-9.0.0/lib/nopt-lib.js 0000664 0000000 0000000 00000033550 15076173424 0015347 0 ustar 00root root 0000000 0000000 const abbrev = require('abbrev')
const debug = require('./debug')
const defaultTypeDefs = require('./type-defs')
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k)
const getType = (k, { types, dynamicTypes }) => {
let hasType = hasOwn(types, k)
let type = types[k]
if (!hasType && typeof dynamicTypes === 'function') {
const matchedType = dynamicTypes(k)
if (matchedType !== undefined) {
type = matchedType
hasType = true
}
}
return [hasType, type]
}
const isTypeDef = (type, def) => def && type === def
const hasTypeDef = (type, def) => def && type.indexOf(def) !== -1
const doesNotHaveTypeDef = (type, def) => def && !hasTypeDef(type, def)
function nopt (args, {
types,
shorthands,
typeDefs,
invalidHandler, // opt is configured but its value does not validate against given type
unknownHandler, // opt is not configured
abbrevHandler, // opt is being expanded via abbrev
typeDefault,
dynamicTypes,
} = {}) {
debug(types, shorthands, args, typeDefs)
const data = {}
const argv = {
remain: [],
cooked: args,
original: args.slice(0),
}
parse(args, data, argv.remain, {
typeDefs, types, dynamicTypes, shorthands, unknownHandler, abbrevHandler,
})
// now data is full
clean(data, { types, dynamicTypes, typeDefs, invalidHandler, typeDefault })
data.argv = argv
Object.defineProperty(data.argv, 'toString', {
value: function () {
return this.original.map(JSON.stringify).join(' ')
},
enumerable: false,
})
return data
}
function clean (data, {
types = {},
typeDefs = {},
dynamicTypes,
invalidHandler,
typeDefault,
} = {}) {
const StringType = typeDefs.String?.type
const NumberType = typeDefs.Number?.type
const ArrayType = typeDefs.Array?.type
const BooleanType = typeDefs.Boolean?.type
const DateType = typeDefs.Date?.type
const hasTypeDefault = typeof typeDefault !== 'undefined'
if (!hasTypeDefault) {
typeDefault = [false, true, null]
if (StringType) {
typeDefault.push(StringType)
}
if (ArrayType) {
typeDefault.push(ArrayType)
}
}
const remove = {}
Object.keys(data).forEach((k) => {
if (k === 'argv') {
return
}
let val = data[k]
debug('val=%j', val)
const isArray = Array.isArray(val)
let [hasType, rawType] = getType(k, { types, dynamicTypes })
let type = rawType
if (!isArray) {
val = [val]
}
if (!type) {
type = typeDefault
}
if (isTypeDef(type, ArrayType)) {
type = typeDefault.concat(ArrayType)
}
if (!Array.isArray(type)) {
type = [type]
}
debug('val=%j', val)
debug('types=', type)
val = val.map((v) => {
// if it's an unknown value, then parse false/true/null/numbers/dates
if (typeof v === 'string') {
debug('string %j', v)
v = v.trim()
if ((v === 'null' && ~type.indexOf(null))
|| (v === 'true' &&
(~type.indexOf(true) || hasTypeDef(type, BooleanType)))
|| (v === 'false' &&
(~type.indexOf(false) || hasTypeDef(type, BooleanType)))) {
v = JSON.parse(v)
debug('jsonable %j', v)
} else if (hasTypeDef(type, NumberType) && !isNaN(v)) {
debug('convert to number', v)
v = +v
} else if (hasTypeDef(type, DateType) && !isNaN(Date.parse(v))) {
debug('convert to date', v)
v = new Date(v)
}
}
if (!hasType) {
if (!hasTypeDefault) {
return v
}
// if the default type has been passed in then we want to validate the
// unknown data key instead of bailing out earlier. we also set the raw
// type which is passed to the invalid handler so that it can be
// determined if during validation if it is unknown vs invalid
rawType = typeDefault
}
// allow `--no-blah` to set 'blah' to null if null is allowed
if (v === false && ~type.indexOf(null) &&
!(~type.indexOf(false) || hasTypeDef(type, BooleanType))) {
v = null
}
const d = {}
d[k] = v
debug('prevalidated val', d, v, rawType)
if (!validate(d, k, v, rawType, { typeDefs })) {
if (invalidHandler) {
invalidHandler(k, v, rawType, data)
} else if (invalidHandler !== false) {
debug('invalid: ' + k + '=' + v, rawType)
}
return remove
}
debug('validated v', d, v, rawType)
return d[k]
}).filter((v) => v !== remove)
// if we allow Array specifically, then an empty array is how we
// express 'no value here', not null. Allow it.
if (!val.length && doesNotHaveTypeDef(type, ArrayType)) {
debug('VAL HAS NO LENGTH, DELETE IT', val, k, type.indexOf(ArrayType))
delete data[k]
} else if (isArray) {
debug(isArray, data[k], val)
data[k] = val
} else {
data[k] = val[0]
}
debug('k=%s val=%j', k, val, data[k])
})
}
function validate (data, k, val, type, { typeDefs } = {}) {
const ArrayType = typeDefs?.Array?.type
// arrays are lists of types.
if (Array.isArray(type)) {
for (let i = 0, l = type.length; i < l; i++) {
if (isTypeDef(type[i], ArrayType)) {
continue
}
if (validate(data, k, val, type[i], { typeDefs })) {
return true
}
}
delete data[k]
return false
}
// an array of anything?
if (isTypeDef(type, ArrayType)) {
return true
}
// Original comment:
// NaN is poisonous. Means that something is not allowed.
// New comment: Changing this to an isNaN check breaks a lot of tests.
// Something is being assumed here that is not actually what happens in
// practice. Fixing it is outside the scope of getting linting to pass in
// this repo. Leaving as-is for now.
/* eslint-disable-next-line no-self-compare */
if (type !== type) {
debug('Poison NaN', k, val, type)
delete data[k]
return false
}
// explicit list of values
if (val === type) {
debug('Explicitly allowed %j', val)
data[k] = val
return true
}
// now go through the list of typeDefs, validate against each one.
let ok = false
const types = Object.keys(typeDefs)
for (let i = 0, l = types.length; i < l; i++) {
debug('test type %j %j %j', k, val, types[i])
const t = typeDefs[types[i]]
if (t && (
(type && type.name && t.type && t.type.name) ?
(type.name === t.type.name) :
(type === t.type)
)) {
const d = {}
ok = t.validate(d, k, val) !== false
val = d[k]
if (ok) {
data[k] = val
break
}
}
}
debug('OK? %j (%j %j %j)', ok, k, val, types[types.length - 1])
if (!ok) {
delete data[k]
}
return ok
}
function parse (args, data, remain, {
types = {},
typeDefs = {},
shorthands = {},
dynamicTypes,
unknownHandler,
abbrevHandler,
} = {}) {
const StringType = typeDefs.String?.type
const NumberType = typeDefs.Number?.type
const ArrayType = typeDefs.Array?.type
const BooleanType = typeDefs.Boolean?.type
debug('parse', args, data, remain)
const abbrevs = abbrev(Object.keys(types))
debug('abbrevs=%j', abbrevs)
const shortAbbr = abbrev(Object.keys(shorthands))
for (let i = 0; i < args.length; i++) {
let arg = args[i]
debug('arg', arg)
if (arg.match(/^-{2,}$/)) {
// done with keys.
// the rest are args.
remain.push.apply(remain, args.slice(i + 1))
args[i] = '--'
break
}
let hadEq = false
if (arg.charAt(0) === '-' && arg.length > 1) {
const at = arg.indexOf('=')
if (at > -1) {
hadEq = true
const v = arg.slice(at + 1)
arg = arg.slice(0, at)
args.splice(i, 1, arg, v)
}
// see if it's a shorthand
// if so, splice and back up to re-parse it.
const shRes = resolveShort(arg, shortAbbr, abbrevs, { shorthands, abbrevHandler })
debug('arg=%j shRes=%j', arg, shRes)
if (shRes) {
args.splice.apply(args, [i, 1].concat(shRes))
if (arg !== shRes[0]) {
i--
continue
}
}
arg = arg.replace(/^-+/, '')
let no = null
while (arg.toLowerCase().indexOf('no-') === 0) {
no = !no
arg = arg.slice(3)
}
// abbrev includes the original full string in its abbrev list
if (abbrevs[arg] && abbrevs[arg] !== arg) {
if (abbrevHandler) {
abbrevHandler(arg, abbrevs[arg])
} else if (abbrevHandler !== false) {
debug(`abbrev: ${arg} -> ${abbrevs[arg]}`)
}
arg = abbrevs[arg]
}
let [hasType, argType] = getType(arg, { types, dynamicTypes })
let isTypeArray = Array.isArray(argType)
if (isTypeArray && argType.length === 1) {
isTypeArray = false
argType = argType[0]
}
let isArray = isTypeDef(argType, ArrayType) ||
isTypeArray && hasTypeDef(argType, ArrayType)
// allow unknown things to be arrays if specified multiple times.
if (!hasType && hasOwn(data, arg)) {
if (!Array.isArray(data[arg])) {
data[arg] = [data[arg]]
}
isArray = true
}
let val
let la = args[i + 1]
const isBool = typeof no === 'boolean' ||
isTypeDef(argType, BooleanType) ||
isTypeArray && hasTypeDef(argType, BooleanType) ||
(typeof argType === 'undefined' && !hadEq) ||
(la === 'false' &&
(argType === null ||
isTypeArray && ~argType.indexOf(null)))
if (typeof argType === 'undefined') {
// la is going to unexpectedly be parsed outside the context of this arg
const hangingLa = !hadEq && la && !la?.startsWith('-') && !['true', 'false'].includes(la)
if (unknownHandler) {
if (hangingLa) {
unknownHandler(arg, la)
} else {
unknownHandler(arg)
}
} else if (unknownHandler !== false) {
debug(`unknown: ${arg}`)
if (hangingLa) {
debug(`unknown: ${la} parsed as normal opt`)
}
}
}
if (isBool) {
// just set and move along
val = !no
// however, also support --bool true or --bool false
if (la === 'true' || la === 'false') {
val = JSON.parse(la)
la = null
if (no) {
val = !val
}
i++
}
// also support "foo":[Boolean, "bar"] and "--foo bar"
if (isTypeArray && la) {
if (~argType.indexOf(la)) {
// an explicit type
val = la
i++
} else if (la === 'null' && ~argType.indexOf(null)) {
// null allowed
val = null
i++
} else if (!la.match(/^-{2,}[^-]/) &&
!isNaN(la) &&
hasTypeDef(argType, NumberType)) {
// number
val = +la
i++
} else if (!la.match(/^-[^-]/) && hasTypeDef(argType, StringType)) {
// string
val = la
i++
}
}
if (isArray) {
(data[arg] = data[arg] || []).push(val)
} else {
data[arg] = val
}
continue
}
if (isTypeDef(argType, StringType)) {
if (la === undefined) {
la = ''
} else if (la.match(/^-{1,2}[^-]+/)) {
la = ''
i--
}
}
if (la && la.match(/^-{2,}$/)) {
la = undefined
i--
}
val = la === undefined ? true : la
if (isArray) {
(data[arg] = data[arg] || []).push(val)
} else {
data[arg] = val
}
i++
continue
}
remain.push(arg)
}
}
const SINGLES = Symbol('singles')
const singleCharacters = (arg, shorthands) => {
let singles = shorthands[SINGLES]
if (!singles) {
singles = Object.keys(shorthands).filter((s) => s.length === 1).reduce((l, r) => {
l[r] = true
return l
}, {})
shorthands[SINGLES] = singles
debug('shorthand singles', singles)
}
const chrs = arg.split('').filter((c) => singles[c])
return chrs.join('') === arg ? chrs : null
}
function resolveShort (arg, ...rest) {
const { abbrevHandler, types = {}, shorthands = {} } = rest.length ? rest.pop() : {}
const shortAbbr = rest[0] ?? abbrev(Object.keys(shorthands))
const abbrevs = rest[1] ?? abbrev(Object.keys(types))
// handle single-char shorthands glommed together, like
// npm ls -glp, but only if there is one dash, and only if
// all of the chars are single-char shorthands, and it's
// not a match to some other abbrev.
arg = arg.replace(/^-+/, '')
// if it's an exact known option, then don't go any further
if (abbrevs[arg] === arg) {
return null
}
// if it's an exact known shortopt, same deal
if (shorthands[arg]) {
// make it an array, if it's a list of words
if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
shorthands[arg] = shorthands[arg].split(/\s+/)
}
return shorthands[arg]
}
// first check to see if this arg is a set of single-char shorthands
const chrs = singleCharacters(arg, shorthands)
if (chrs) {
return chrs.map((c) => shorthands[c]).reduce((l, r) => l.concat(r), [])
}
// if it's an arg abbrev, and not a literal shorthand, then prefer the arg
if (abbrevs[arg] && !shorthands[arg]) {
return null
}
// if it's an abbr for a shorthand, then use that
// exact match has already happened so we don't need to account for that here
if (shortAbbr[arg]) {
if (abbrevHandler) {
abbrevHandler(arg, shortAbbr[arg])
} else if (abbrevHandler !== false) {
debug(`abbrev: ${arg} -> ${shortAbbr[arg]}`)
}
arg = shortAbbr[arg]
}
// make it an array, if it's a list of words
if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
shorthands[arg] = shorthands[arg].split(/\s+/)
}
return shorthands[arg]
}
module.exports = {
nopt,
clean,
parse,
validate,
resolveShort,
typeDefs: defaultTypeDefs,
}
nopt-9.0.0/lib/nopt.js 0000664 0000000 0000000 00000002147 15076173424 0014601 0 ustar 00root root 0000000 0000000 const lib = require('./nopt-lib')
const defaultTypeDefs = require('./type-defs')
// This is the version of nopt's API that requires setting typeDefs and invalidHandler
// on the required `nopt` object since it is a singleton. To not do a breaking change
// an API that requires all options be passed in is located in `nopt-lib.js` and
// exported here as lib.
// TODO(breaking): make API only work in non-singleton mode
module.exports = exports = nopt
exports.clean = clean
exports.typeDefs = defaultTypeDefs
exports.lib = lib
function nopt (types, shorthands, args = process.argv, slice = 2) {
return lib.nopt(args.slice(slice), {
types: types || {},
shorthands: shorthands || {},
typeDefs: exports.typeDefs,
invalidHandler: exports.invalidHandler,
unknownHandler: exports.unknownHandler,
abbrevHandler: exports.abbrevHandler,
})
}
function clean (data, types, typeDefs = exports.typeDefs) {
return lib.clean(data, {
types: types || {},
typeDefs,
invalidHandler: exports.invalidHandler,
unknownHandler: exports.unknownHandler,
abbrevHandler: exports.abbrevHandler,
})
}
nopt-9.0.0/lib/type-defs.js 0000664 0000000 0000000 00000003756 15076173424 0015530 0 ustar 00root root 0000000 0000000 const url = require('url')
const path = require('path')
const Stream = require('stream').Stream
const os = require('os')
const debug = require('./debug')
function validateString (data, k, val) {
data[k] = String(val)
}
function validatePath (data, k, val) {
if (val === true) {
return false
}
if (val === null) {
return true
}
val = String(val)
const isWin = process.platform === 'win32'
const homePattern = isWin ? /^~(\/|\\)/ : /^~\//
const home = os.homedir()
if (home && val.match(homePattern)) {
data[k] = path.resolve(home, val.slice(2))
} else {
data[k] = path.resolve(val)
}
return true
}
function validateNumber (data, k, val) {
debug('validate Number %j %j %j', k, val, isNaN(val))
if (isNaN(val)) {
return false
}
data[k] = +val
}
function validateDate (data, k, val) {
const s = Date.parse(val)
debug('validate Date %j %j %j', k, val, s)
if (isNaN(s)) {
return false
}
data[k] = new Date(val)
}
function validateBoolean (data, k, val) {
if (typeof val === 'string') {
if (!isNaN(val)) {
val = !!(+val)
} else if (val === 'null' || val === 'false') {
val = false
} else {
val = true
}
} else {
val = !!val
}
data[k] = val
}
function validateUrl (data, k, val) {
// Changing this would be a breaking change in the npm cli
/* eslint-disable-next-line node/no-deprecated-api */
val = url.parse(String(val))
if (!val.host) {
return false
}
data[k] = val.href
}
function validateStream (data, k, val) {
if (!(val instanceof Stream)) {
return false
}
data[k] = val
}
module.exports = {
String: { type: String, validate: validateString },
Boolean: { type: Boolean, validate: validateBoolean },
url: { type: url, validate: validateUrl },
Number: { type: Number, validate: validateNumber },
path: { type: path, validate: validatePath },
Stream: { type: Stream, validate: validateStream },
Date: { type: Date, validate: validateDate },
Array: { type: Array },
}
nopt-9.0.0/package.json 0000664 0000000 0000000 00000002276 15076173424 0015006 0 ustar 00root root 0000000 0000000 {
"name": "nopt",
"version": "9.0.0",
"description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.",
"author": "GitHub Inc.",
"main": "lib/nopt.js",
"scripts": {
"test": "tap",
"lint": "npm run eslint",
"postlint": "template-oss-check",
"template-oss-apply": "template-oss-apply --force",
"lintfix": "npm run eslint -- --fix",
"snap": "tap",
"posttest": "npm run lint",
"eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/npm/nopt.git"
},
"bin": {
"nopt": "bin/nopt.js"
},
"license": "ISC",
"dependencies": {
"abbrev": "^4.0.0"
},
"devDependencies": {
"@npmcli/eslint-config": "^5.0.0",
"@npmcli/template-oss": "4.27.1",
"tap": "^16.3.0"
},
"tap": {
"nyc-arg": [
"--exclude",
"tap-snapshots/**"
]
},
"files": [
"bin/",
"lib/"
],
"engines": {
"node": "^20.17.0 || >=22.9.0"
},
"templateOSS": {
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
"windowsCI": false,
"version": "4.27.1",
"publish": true
}
}
nopt-9.0.0/release-please-config.json 0000664 0000000 0000000 00000001277 15076173424 0017545 0 ustar 00root root 0000000 0000000 {
"group-pull-request-title-pattern": "chore: release ${version}",
"pull-request-title-pattern": "chore: release${component} ${version}",
"changelog-sections": [
{
"type": "feat",
"section": "Features",
"hidden": false
},
{
"type": "fix",
"section": "Bug Fixes",
"hidden": false
},
{
"type": "docs",
"section": "Documentation",
"hidden": false
},
{
"type": "deps",
"section": "Dependencies",
"hidden": false
},
{
"type": "chore",
"section": "Chores",
"hidden": true
}
],
"packages": {
".": {
"package-name": ""
}
},
"prerelease-type": "pre.0"
}
nopt-9.0.0/test/ 0000775 0000000 0000000 00000000000 15076173424 0013470 5 ustar 00root root 0000000 0000000 nopt-9.0.0/test/basic.js 0000664 0000000 0000000 00000027640 15076173424 0015120 0 ustar 00root root 0000000 0000000 const nopt = require('../')
const t = require('tap')
const isWin = process.platform === 'win32'
t.test('empty array is fine if type includes Array', t => {
const types = {
arr: [Array, String],
}
const data = {
arr: [],
}
nopt.clean(data, types)
t.same(data.arr, [])
t.end()
})
t.test('passing a string results in a string', t => {
const parsed = nopt({ key: String }, {}, ['--key', 'myvalue'], 0)
t.same(parsed.key, 'myvalue')
t.end()
})
// https://github.com/npm/nopt/issues/31
t.test('Empty String results in empty string, not true', t => {
const parsed = nopt({ empty: String }, {}, ['--empty'], 0)
t.same(parsed.empty, '')
t.end()
})
// https://github.com/npm/nopt/issues/65
t.test('Empty String should not swallow next flag', t => {
const parsed = nopt({ empty: String, foo: String }, {}, ['--empty', '--foo'], 0)
t.same(parsed.empty, '')
t.same(parsed.foo, '')
t.end()
})
// https://github.com/npm/nopt/issues/66
t.test('Empty String should not be true when type is single item Array', t => {
const parsed = nopt({ foo: [String] }, {}, ['--foo'], 0)
t.same(parsed.foo, '')
t.end()
})
t.test('~ path is resolved to ' + (isWin ? '%USERPROFILE%' : '$HOME'), t => {
const path = require('path')
const the = isWin
? {
key: 'USERPROFILE',
dir: 'C:\\temp',
val: '~\\val',
} : {
key: 'HOME',
dir: '/tmp',
val: '~/val',
}
if (!process.env[the.key]) {
process.env[the.key] = the.dir
}
const parsed = nopt({ key: path }, {}, ['--key=' + the.val], 0)
t.same(parsed.key, path.resolve(process.env[the.key], 'val'))
t.end()
})
// https://github.com/npm/nopt/issues/24
t.test('Unknown options are not parsed as numbers', t => {
const parsed = nopt({ 'parse-me': Number }, null, ['--leave-as-is=1.20', '--parse-me=1.20'], 0)
t.equal(parsed['leave-as-is'], '1.20')
t.equal(parsed['parse-me'], 1.2)
t.end()
})
// https://github.com/npm/nopt/issues/48
t.test('Check types based on name of type', t => {
const parsed = nopt({ 'parse-me': { name: 'Number' } }, null, ['--parse-me=1.20'], 0)
t.equal(parsed['parse-me'], 1.2)
t.end()
})
t.test('Missing types are not parsed', t => {
const parsed = nopt({ 'parse-me': {} }, null, ['--parse-me=1.20'], 0)
// should only contain argv
t.equal(Object.keys(parsed).length, 1)
t.end()
})
t.test('Types passed without a name are not parsed', t => {
const parsed = nopt({ 'parse-me': {} }, {}, ['--parse-me=1.20'], 0)
// should only contain argv
t.equal(Object.keys(parsed).length, 1)
t.end()
})
t.test('no types does not throw', t => {
const parsed = nopt(null, null, ['--leave-as-is=1.20'], 0)
t.equal(parsed['leave-as-is'], '1.20')
t.end()
})
t.test('clean: no types does not throw', t => {
const data = { 'leave-unknown': 'still here' }
nopt.clean(data)
t.strictSame(data, { 'leave-unknown': 'still here' })
t.end()
})
t.test('other tests', t => {
const Stream = require('stream')
const path = require('path')
const url = require('url')
const shorthands =
{ s: ['--loglevel', 'silent'],
d: ['--loglevel', 'info'],
dd: ['--loglevel', 'verbose'],
ddd: ['--loglevel', 'silly'],
noreg: ['--no-registry'],
reg: ['--registry'],
'no-reg': ['--no-registry'],
silent: ['--loglevel', 'silent'],
verbose: ['--loglevel', 'verbose'],
h: ['--usage'],
H: ['--usage'],
'?': ['--usage'],
help: ['--usage'],
v: ['--version'],
f: ['--force'],
desc: ['--description'],
'no-desc': ['--no-description'],
local: ['--no-global'],
l: ['--long'],
p: ['--parseable'],
porcelain: ['--parseable'],
g: ['--global'],
}
const types =
{ aoa: Array,
nullstream: [null, Stream],
date: Date,
str: String,
browser: String,
cache: path,
color: ['always', Boolean],
depth: Number,
description: Boolean,
dev: Boolean,
editor: path,
force: Boolean,
global: Boolean,
globalconfig: path,
group: [String, Number],
gzipbin: String,
logfd: [Number, Stream],
loglevel: ['silent', 'win', 'error', 'warn', 'info', 'verbose', 'silly'],
long: Boolean,
'node-version': [false, String],
npaturl: url,
npat: Boolean,
'onload-script': [false, String],
outfd: [Number, Stream],
parseable: Boolean,
pre: Boolean,
prefix: path,
proxy: url,
'rebuild-bundle': Boolean,
registry: url,
searchopts: String,
searchexclude: [null, String],
shell: path,
t: [Array, String],
tag: String,
tar: String,
tmp: path,
'unsafe-perm': Boolean,
usage: Boolean,
user: String,
username: String,
userconfig: path,
version: Boolean,
viewer: path,
_exit: Boolean,
path: path,
}
; [['-v', { version: true }, []],
['---v', { version: true }, []],
['ls -s --no-reg connect -d',
{ loglevel: 'info', registry: null }, ['ls', 'connect']],
['ls ---s foo', { loglevel: 'silent' }, ['ls', 'foo']],
['ls --registry blargle', {}, ['ls']],
['--no-registry', { registry: null }, []],
['--no-color true', { color: false }, []],
['--no-color false', { color: true }, []],
['--no-color', { color: false }, []],
['--color false', { color: false }, []],
['--color --logfd 7', { logfd: 7, color: true }, []],
['--color=true', { color: true }, []],
['--logfd=10', { logfd: 10 }, []],
['--tmp=/tmp -tar=gtar', { tmp: isWin ? 'C:\\tmp' : '/tmp', tar: 'gtar' }, []],
['--tmp=tmp -tar=gtar',
{ tmp: path.resolve(process.cwd(), 'tmp'), tar: 'gtar' }, []],
['--logfd x', {}, []],
['a -true -- -no-false', { true: true }, ['a', '-no-false']],
['a -no-false', { false: false }, ['a']],
['a -no-no-true', { true: true }, ['a']],
['a -no-no-no-false', { false: false }, ['a']],
['---NO-no-No-no-no-no-nO-no-no' +
'-No-no-no-no-no-no-no-no-no' +
'-no-no-no-no-NO-NO-no-no-no-no-no-no' +
'-no-body-can-do-the-boogaloo-like-I-do',
{ 'body-can-do-the-boogaloo-like-I-do': false }, []],
['we are -no-strangers-to-love ' +
'--you-know=the-rules --and=so-do-i ' +
'---im-thinking-of=a-full-commitment ' +
'--no-you-would-get-this-from-any-other-guy ' +
'--no-gonna-give-you-up ' +
'-no-gonna-let-you-down=true ' +
'--no-no-gonna-run-around false ' +
'--desert-you=false ' +
'--make-you-cry false ' +
'--no-tell-a-lie ' +
'--no-no-and-hurt-you false',
{ 'strangers-to-love': false,
'you-know': 'the-rules',
and: 'so-do-i',
'you-would-get-this-from-any-other-guy': false,
'gonna-give-you-up': false,
'gonna-let-you-down': false,
'gonna-run-around': false,
'desert-you': false,
'make-you-cry': false,
'tell-a-lie': false,
'and-hurt-you': false,
}, ['we', 'are']],
['-t one -t two -t three',
{ t: ['one', 'two', 'three'] },
[]],
['-t one -t null -t three four five null',
{ t: ['one', 'null', 'three'] },
['four', 'five', 'null']],
['-t foo',
{ t: ['foo'] },
[]],
['--no-t',
{ t: ['false'] },
[]],
['-no-no-t',
{ t: ['true'] },
[]],
['-aoa one -aoa null -aoa 100',
{ aoa: ['one', null, '100'] },
[]],
['-str 100',
{ str: '100' },
[]],
['--color always',
{ color: 'always' },
[]],
['--no-nullstream',
{ nullstream: null },
[]],
['--nullstream false',
{ nullstream: null },
[]],
['--notadate=2011-01-25',
{ notadate: '2011-01-25' },
[]],
['--date 2011-01-25',
{ date: new Date('2011-01-25') },
[]],
['--date xxxxxxxxxx', // invalid date -> NaN
{},
[]],
['--registry https://github.com',
{ registry: 'https://github.com/' },
[]],
['-cl 1',
{ config: true, length: 1 },
[],
{ config: Boolean, length: Number, clear: Boolean },
{ c: '--config', l: '--length' }],
['--acount bla',
{ acount: true },
['bla'],
{ account: Boolean, credentials: Boolean, options: String },
{ a: '--account', c: '--credentials', o: '--options' }],
['--clear',
{ clear: true },
[],
{ clear: Boolean, con: Boolean, len: Boolean, exp: Boolean, add: Boolean, rep: Boolean },
{ c: '--con', l: '--len', e: '--exp', a: '--add', r: '--rep' }],
['--file -',
{ file: '-' },
[],
{ file: String },
{}],
['--file -',
{ file: true },
['-'],
{ file: Boolean },
{}],
['--path',
{ path: null },
[]],
['--path .',
{ path: process.cwd() },
[]],
].forEach(function (params) {
const argv = params[0].split(/\s+/)
const opts = params[1]
const rem = params[2]
const actual = nopt(params[3] || types, params[4] || shorthands, argv, 0)
const parsed = actual.argv
delete actual.argv
for (const i in opts) {
const e = JSON.stringify(opts[i])
const a = JSON.stringify(actual[i] === undefined ? null : actual[i])
if (e && typeof e === 'object') {
t.same(e, a)
} else {
t.equal(e, a)
}
}
t.same(rem, parsed.remain)
})
t.end()
})
t.test('argv toString()', t => {
const parsed = nopt({ key: String }, {}, ['--key', 'myvalue'], 0)
t.same(parsed.argv.toString(), '"--key" "myvalue"')
t.end()
})
t.test('custom invalidHandler', t => {
t.teardown(() => {
delete nopt.invalidHandler
})
nopt.invalidHandler = (k, v) => {
t.match(k, 'key')
t.match(v, 'nope')
t.end()
}
nopt({ key: Number }, {}, ['--key', 'nope'], 0)
})
t.test('custom unknownHandler string', t => {
t.teardown(() => {
delete nopt.unknownHandler
})
nopt.unknownHandler = (k, next) => {
t.match(k, 'x')
t.match(next, 'null')
t.end()
}
nopt({}, {}, ['--x', 'null'], 0)
})
t.test('custom unknownHandler boolean', t => {
t.teardown(() => {
delete nopt.unknownHandler
})
nopt.unknownHandler = (k, next) => {
t.match(k, 'x')
t.match(next, undefined)
t.end()
}
nopt({}, {}, ['--x', 'false'], 0)
})
t.test('custom normal abbrevHandler', t => {
t.teardown(() => {
delete nopt.abbrevHandler
})
nopt.abbrevHandler = (short, long) => {
t.match(short, 'shor')
t.match(long, 'shorthand')
t.end()
}
nopt({ shorthand: Boolean }, {}, ['--short', 'true'], 0)
})
t.test('custom shorthand abbrevHandler', t => {
t.teardown(() => {
delete nopt.abbrevHandler
})
nopt.abbrevHandler = (short, long) => {
t.match(short, 'shor')
t.match(long, 'shorthand')
t.end()
}
nopt({
longhand: Boolean,
}, { shorthand: '--longhand' },
['--short', 'true'], 0)
})
t.test('numbered boolean', t => {
const parsed = nopt({ key: [Boolean, String] }, {}, ['--key', '0'], 0)
t.same(parsed.key, false)
t.end()
})
t.test('false string boolean', t => {
const parsed = nopt({ key: [Boolean, String] }, {}, ['--key', 'false'], 0)
t.same(parsed.key, false)
t.end()
})
t.test('true string boolean', t => {
const parsed = nopt({ key: [Boolean, String] }, {}, ['--key', 'true'], 0)
t.same(parsed.key, true)
t.end()
})
t.test('null string boolean', t => {
const parsed = nopt({ key: [Boolean, String] }, {}, ['--key', 'null'], 0)
t.same(parsed.key, false)
t.end()
})
t.test('other string boolean', t => {
const parsed = nopt({ key: [Boolean, String] }, {}, ['--key', 'yes'], 0)
t.same(parsed.key, true)
t.end()
})
t.test('number boolean', t => {
const parsed = nopt({ key: [Boolean, Number] }, {}, ['--key', '100'], 0)
t.same(parsed.key, true)
t.end()
})
t.test('no args', (t) => {
const _argv = process.argv
t.teardown(() => process.argv = _argv)
process.argv = ['', '', 'a']
t.strictSame(nopt(), { argv: { remain: ['a'], cooked: ['a'], original: ['a'] } })
t.end()
})
nopt-9.0.0/test/dynamic-types.js 0000664 0000000 0000000 00000002401 15076173424 0016611 0 ustar 00root root 0000000 0000000 const t = require('tap')
const nopt = require('../lib/nopt-lib.js')
t.test('fallback types', (t) => {
const n = (dynamicTypes) => {
const args = [
'--hello', '100',
'--goodbye', '50',
'--hat=blue',
'--mult', '200',
'--mult', '300',
'--multeq=111',
'--multeq=999',
]
const res = nopt.nopt(args, {
types: { hello: nopt.typeDefs.Number.type },
dynamicTypes,
typeDefs: nopt.typeDefs,
shorthands: {},
})
delete res.argv.cooked
delete res.argv.original
return res
}
t.strictSame(n(), {
hello: 100,
goodbye: true,
hat: 'blue',
mult: [
true,
true,
],
multeq: [
'111',
'999',
],
argv: {
remain: [
'50',
'200',
'300',
],
},
}, 'parse args with no fallback')
t.strictSame(n((k) => {
if (k.startsWith('goo')) {
return nopt.typeDefs.Number.type
}
if (k === 'mult') {
return [nopt.typeDefs.Number.type, nopt.typeDefs.Array.type]
}
}), {
hello: 100,
goodbye: 50,
hat: 'blue',
mult: [
200,
300,
],
multeq: [
'111',
'999',
],
argv: {
remain: [],
},
}, 'parse args with no fallback')
t.end()
})
nopt-9.0.0/test/lib.js 0000664 0000000 0000000 00000012150 15076173424 0014573 0 ustar 00root root 0000000 0000000 const t = require('tap')
const noptLib = require('../lib/nopt-lib.js')
const Stream = require('stream')
const nopt = (t, argv, opts, expected) => {
if (Array.isArray(argv)) {
t.strictSame(noptLib.nopt(argv, { typeDefs: noptLib.typeDefs, ...opts }), expected)
} else {
noptLib.clean(argv, { typeDefs: noptLib.typeDefs, ...opts })
t.match(argv, expected)
}
t.end()
}
t.test('stream', t => {
nopt(t, { x: new Stream.Readable() }, { types: { x: Stream } }, {})
})
t.test('no/missing options', t => {
t.doesNotThrow(() => noptLib.nopt([]))
t.doesNotThrow(() => noptLib.nopt([], {}))
t.doesNotThrow(() => noptLib.clean({}))
t.doesNotThrow(() => noptLib.clean({}, {}))
t.doesNotThrow(() => noptLib.parse([]))
t.doesNotThrow(() => noptLib.parse([], {}, [], {}))
t.doesNotThrow(() => noptLib.validate({}))
t.doesNotThrow(() => noptLib.validate({}, null, null, null, {}))
t.doesNotThrow(() => noptLib.resolveShort(''))
t.doesNotThrow(() => noptLib.resolveShort('', {}))
t.doesNotThrow(() => noptLib.resolveShort('', {}, {}, {}))
t.end()
})
t.test('key argv is ignored', (t) => {
nopt(t, ['--argvv', '--argv'], {}, {
argvv: true,
argv: {
remain: [],
cooked: ['--argvv', '--argv'],
original: ['--argvv', '--argv'],
},
})
})
t.test('boolean with null', (t) => {
nopt(t, ['--boolNull', 'null', '--boolOnly', 'null'], {
types: {
boolNull: [Boolean, null],
boolOnly: [Boolean],
},
}, {
boolNull: false,
boolOnly: true,
argv: {
remain: ['null'],
cooked: ['--boolNull', 'null', '--boolOnly', 'null'],
original: ['--boolNull', 'null', '--boolOnly', 'null'],
},
})
})
t.test('-- after non string type', (t) => {
nopt(t, ['--x', '5', '--y', '--', '200'], {
types: {
x: Number,
y: Number,
},
}, {
x: 5,
// XXX: getting coverage to 100 and this seems wrong
// test matches current implementation for now
y: 1,
argv: {
remain: ['200'],
cooked: ['--x', '5', '--y', '--', '200'],
original: ['--x', '5', '--y', '--', '200'],
},
})
})
t.test('nan', (t) => {
nopt(t, ['--x', '5'], {
types: {
x: NaN,
},
}, {
x: undefined,
argv: {
remain: [],
cooked: ['--x', '5'],
original: ['--x', '5'],
},
})
})
t.test('string/null', (t) => {
nopt(t, ['--x', 'null', '--y', 'false', '--z', 'true'], {
types: {
x: Number,
y: Number,
z: Number,
},
}, {
argv: {
remain: [],
cooked: ['--x', 'null', '--y', 'false', '--z', 'true'],
original: ['--x', 'null', '--y', 'false', '--z', 'true'],
},
})
})
t.test('false invalid handler', (t) => {
// this is only for coverage
nopt(t, ['--x', 'null'], {
types: {
x: Number,
},
invalidHandler: false,
}, {
argv: {
remain: [],
cooked: ['--x', 'null'],
original: ['--x', 'null'],
},
})
})
t.test('false unknown handler string', (t) => {
// this is only for coverage
nopt(t, ['--x', 'null'], {
unknownHandler: false,
}, {
x: true,
argv: {
remain: ['null'],
cooked: ['--x', 'null'],
original: ['--x', 'null'],
},
})
})
t.test('default unknown handler opt', (t) => {
// this is only for coverage
nopt(t, ['--x', '--y'], {}, {
x: true,
y: true,
argv: {
remain: [],
cooked: ['--x', '--y'],
original: ['--x', '--y'],
},
})
})
t.test('false abbrev handler normal', (t) => {
// this is only for coverage
nopt(t, ['--long', 'true'], {
types: {
longhand: Boolean,
},
abbrevHandler: false,
}, {
longhand: true,
argv: {
remain: [],
cooked: ['--long', 'true'],
original: ['--long', 'true'],
},
})
})
t.test('false abbrev handler shorthand', (t) => {
// this is only for coverage
nopt(t, ['--shor', 'true'], {
types: {},
shorthands: {
short: '--longhand',
},
abbrevHandler: false,
}, {
longhand: true,
argv: {
remain: [],
cooked: ['--longhand', 'true'],
original: ['--shor', 'true'],
},
})
})
t.test('normal abbreviation', (t) => {
nopt(t, ['--shor', 'text'], {
types: {
shorthand: String,
},
}, {
shorthand: 'text',
argv: {
remain: [],
cooked: ['--shor', 'text'],
original: ['--shor', 'text'],
},
})
})
t.test('shorthand abbreviation', (t) => {
nopt(t, ['--shor'], {
types: {},
shorthands: {
short: '--longhand',
},
}, {
longhand: true,
argv: {
remain: [],
cooked: ['--longhand'],
original: ['--shor'],
},
})
})
t.test('shorthands that is the same', (t) => {
nopt(t, ['--sh'], {
types: {},
shorthands: {
sh: '--sh',
},
}, {
sh: true,
argv: {
remain: [],
cooked: ['--sh'],
original: ['--sh'],
},
})
})
t.test('unknown multiple', (t) => {
nopt(t, ['--mult', '--mult', '--mult', 'extra'], {
types: {},
}, {
mult: [true, true, true],
argv: {
remain: ['extra'],
cooked: ['--mult', '--mult', '--mult', 'extra'],
original: ['--mult', '--mult', '--mult', 'extra'],
},
})
})
nopt-9.0.0/test/resolve-short.js 0000664 0000000 0000000 00000001040 15076173424 0016635 0 ustar 00root root 0000000 0000000 const t = require('tap')
const nopt = require('../lib/nopt-lib.js')
t.test('basic', (t) => {
const assertShort = (v, expected) => {
const k = 'package-lock'
t.strictSame(nopt.resolveShort(v, {
shorthands: { shrinkwrap: `--${k} true` },
types: { [k]: Boolean },
}), expected !== undefined ? expected : [`--${k}`, 'true'], v)
}
assertShort('--shrinkwrap')
assertShort('--shrinkwra')
assertShort('-shrinkwra')
assertShort('shr')
assertShort('--package-lock', null)
assertShort('--pa', null)
t.end()
})
nopt-9.0.0/test/type-default.js 0000664 0000000 0000000 00000002263 15076173424 0016434 0 ustar 00root root 0000000 0000000 const t = require('tap')
const nopt = require('../lib/nopt-lib.js')
t.test('use other type default', (t) => {
const NotAllowed = Symbol('NotAllowed')
const Invalid = Symbol('Invalid')
const clean = (data, opts) => {
const invalids = []
nopt.clean(data, {
types: {
str: nopt.typeDefs.String.type,
invalid: Invalid,
},
typeDefs: {
...nopt.typeDefs,
NotAllowed: { type: NotAllowed, validate: () => false },
Invalid: { type: Invalid, validate: () => false },
},
invalidHandler: (k, v, type) => invalids.push([k, v, type]),
...opts,
})
return {
keys: Object.keys(data),
invalids,
}
}
t.strictSame(clean({
str: 'aaa',
invalid: 'bad',
unknown: 'huh?',
}), {
keys: ['str', 'unknown'],
invalids: [['invalid', 'bad', Invalid]],
}, 'invalid data is removed with clean')
t.strictSame(clean({
str: 'aaa',
invalid: 'bad',
unknown: 'huh?',
}, { typeDefault: NotAllowed }), {
keys: ['str'],
invalids: [['invalid', 'bad', Invalid], ['unknown', 'huh?', NotAllowed]],
}, 'invalid and unknown data is removed with a custom typeDefault')
t.end()
})
nopt-9.0.0/test/type-defs.js 0000664 0000000 0000000 00000001441 15076173424 0015726 0 ustar 00root root 0000000 0000000 const t = require('tap')
const path = require('path')
const os = require('os')
const nopt = (t, argv, opts, expected) => {
const mockNopt = t.mock('../lib/nopt-lib.js', {
'../lib/type-defs.js': t.mock('../lib/type-defs.js'),
})
t.match(
mockNopt.nopt(argv, { typeDefs: mockNopt.typeDefs, ...opts }),
expected
)
t.end()
}
t.test('path + null', t => {
nopt(t, ['--x', 'null'], { types: { x: [path, null] } }, {
x: undefined,
})
})
t.test('win32 path', t => {
const platform = Object.getOwnPropertyDescriptor(process, 'platform')
t.teardown(() => Object.defineProperty(process, 'platform', platform))
Object.defineProperty(process, 'platform', { ...platform, value: 'win32' })
nopt(t, ['--x', '~/y'], { types: { x: path } }, {
x: `${os.homedir()}/y`,
})
})