Repository: sindresorhus/dargs
Branch: main
Commit: bf0169727d87
Files: 14
Total size: 16.8 KB
Directory structure:
gitextract_r37fvqu1/
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── funding.yml
│ ├── security.md
│ └── workflows/
│ └── main.yml
├── .gitignore
├── .npmrc
├── index.d.ts
├── index.js
├── index.test-d.ts
├── license
├── package.json
├── readme.md
└── test.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_style = space
indent_size = 2
================================================
FILE: .gitattributes
================================================
* text=auto eol=lf
================================================
FILE: .github/funding.yml
================================================
github: sindresorhus
open_collective: sindresorhus
custom: https://sindresorhus.com/donate
tidelift: npm/dargs
================================================
FILE: .github/security.md
================================================
# Security Policy
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
================================================
FILE: .github/workflows/main.yml
================================================
name: CI
on:
- push
- pull_request
jobs:
test:
name: Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version:
- 16
- 14
- 12
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
================================================
FILE: .gitignore
================================================
node_modules
yarn.lock
================================================
FILE: .npmrc
================================================
package-lock=false
================================================
FILE: index.d.ts
================================================
export interface Options {
/**
Keys or regex of keys to exclude. Takes precedence over `includes`.
*/
readonly excludes?: ReadonlyArray<string | RegExp>;
/**
Keys or regex of keys to include.
*/
readonly includes?: ReadonlyArray<string | RegExp>;
/**
Maps keys in `input` to an aliased name. Matching keys are converted to arguments with a single dash (`-`) in front of the aliased key and the value in a separate array item. Keys are still affected by `includes` and `excludes`.
*/
readonly aliases?: Record<string, string>;
/**
Setting this to `false` makes it return the key and value as separate array items instead of using a `=` separator in one item. This can be useful for tools that doesn't support `--foo=bar` style flags.
@default true
@example
```
import dargs from 'dargs';
console.log(dargs({foo: 'bar'}, {useEquals: false}));
// [
// '--foo', 'bar'
// ]
```
*/
readonly useEquals?: boolean;
/**
Make a single character option key `{a: true}` become a short flag `-a` instead of `--a`.
@default true
@example
```
import dargs from 'dargs';
console.log(dargs({a: true}));
//=> ['-a']
console.log(dargs({a: true}, {shortFlag: false}));
//=> ['--a']
```
*/
readonly shortFlag?: boolean;
/**
Exclude `true` values. Can be useful when dealing with argument parsers that only expect negated arguments like `--no-foo`.
@default false
*/
readonly ignoreTrue?: boolean;
/**
Exclude `false` values. Can be useful when dealing with strict argument parsers that throw on unknown arguments like `--no-foo`.
@default false
*/
readonly ignoreFalse?: boolean;
/**
By default, camel-cased keys will be hyphenated. Enabling this will bypass the conversion process.
@default false
@example
```
import dargs from 'dargs';
console.log(dargs({fooBar: 'baz'}));
//=> ['--foo-bar', 'baz']
console.log(dargs({fooBar: 'baz'}, {allowCamelCase: true}));
//=> ['--fooBar', 'baz']
```
*/
readonly allowCamelCase?: boolean;
}
/**
Reverse [`minimist`](https://github.com/substack/minimist). Convert an object of options into an array of command-line arguments.
@param object - Object to convert to command-line arguments.
@example
```
import dargs from 'dargs';
const input = {
_: ['some', 'option'], // Values in '_' will be appended to the end of the generated argument list
'--': ['separated', 'option'], // Values in '--' will be put at the very end of the argument list after the escape option (`--`)
foo: 'bar',
hello: true, // Results in only the key being used
cake: false, // Prepends `no-` before the key
camelCase: 5, // CamelCase is slugged to `camel-case`
multiple: ['value', 'value2'], // Converted to multiple arguments
pieKind: 'cherry',
sad: ':('
};
const excludes = ['sad', /.*Kind$/]; // Excludes and includes accept regular expressions
const includes = ['camelCase', 'multiple', 'sad', /^pie.+/];
const aliases = {file: 'f'};
console.log(dargs(input, {excludes}));
// [
// '--foo=bar',
// '--hello',
// '--no-cake',
// '--camel-case=5',
// '--multiple=value',
// '--multiple=value2',
// 'some',
// 'option',
// '--',
// 'separated',
// 'option'
// ]
console.log(dargs(input, {excludes, includes}));
// [
// '--camel-case=5',
// '--multiple=value',
// '--multiple=value2'
// ]
console.log(dargs(input, {includes}));
// [
// '--camel-case=5',
// '--multiple=value',
// '--multiple=value2',
// '--pie-kind=cherry',
// '--sad=:('
// ]
console.log(dargs({
foo: 'bar',
hello: true,
file: 'baz'
}, {aliases}));
// [
// '--foo=bar',
// '--hello',
// '-f', 'baz'
// ]
```
*/
export default function dargs(
object: {
'--'?: string[];
_?: string[];
} & Record<string, string | boolean | number | readonly string[]>,
options?: Options
): string[];
================================================
FILE: index.js
================================================
const match = (array, value) =>
array.some(element => (element instanceof RegExp ? element.test(value) : element === value));
export default function dargs(object, options) {
const arguments_ = [];
let extraArguments = [];
let separatedArguments = [];
options = {
useEquals: true,
shortFlag: true,
...options
};
const makeArguments = (key, value) => {
const prefix = options.shortFlag && key.length === 1 ? '-' : '--';
const theKey = (options.allowCamelCase ?
key :
key.replace(/[A-Z]/g, '-$&').toLowerCase());
key = prefix + theKey;
if (options.useEquals) {
arguments_.push(key + (value ? `=${value}` : ''));
} else {
arguments_.push(key);
if (value) {
arguments_.push(value);
}
}
};
const makeAliasArg = (key, value) => {
arguments_.push(`-${key}`);
if (value) {
arguments_.push(value);
}
};
for (let [key, value] of Object.entries(object)) {
let pushArguments = makeArguments;
if (Array.isArray(options.excludes) && match(options.excludes, key)) {
continue;
}
if (Array.isArray(options.includes) && !match(options.includes, key)) {
continue;
}
if (typeof options.aliases === 'object' && options.aliases[key]) {
key = options.aliases[key];
pushArguments = makeAliasArg;
}
if (key === '--') {
if (!Array.isArray(value)) {
throw new TypeError(
`Expected key \`--\` to be Array, got ${typeof value}`
);
}
separatedArguments = value;
continue;
}
if (key === '_') {
if (!Array.isArray(value)) {
throw new TypeError(
`Expected key \`_\` to be Array, got ${typeof value}`
);
}
extraArguments = value;
continue;
}
if (value === true && !options.ignoreTrue) {
pushArguments(key, '');
}
if (value === false && !options.ignoreFalse) {
pushArguments(`no-${key}`);
}
if (typeof value === 'string') {
pushArguments(key, value);
}
if (typeof value === 'number' && !Number.isNaN(value)) {
pushArguments(key, String(value));
}
if (Array.isArray(value)) {
for (const arrayValue of value) {
pushArguments(key, arrayValue);
}
}
}
for (const argument of extraArguments) {
arguments_.push(String(argument));
}
if (separatedArguments.length > 0) {
arguments_.push('--');
}
for (const argument of separatedArguments) {
arguments_.push(String(argument));
}
return arguments_;
}
================================================
FILE: index.test-d.ts
================================================
import {expectType, expectError} from 'tsd';
import dargs from './index.js';
const object = {
_: ['some', 'option'],
foo: 'bar',
hello: true,
cake: false,
camelCase: 5,
multiple: ['value', 'value2'],
pieKind: 'cherry',
sad: ':('
};
const excludes = ['sad', /.*Kind$/];
const includes = ['camelCase', 'multiple', 'sad', /^pie.*/];
const aliases = {file: 'f'};
expectType<string[]>(dargs(object, {excludes}));
expectType<string[]>(dargs(object, {includes}));
expectType<string[]>(dargs(object, {aliases}));
expectType<string[]>(dargs(object, {useEquals: false}));
expectType<string[]>(dargs(object, {shortFlag: true}));
expectType<string[]>(dargs(object, {ignoreTrue: true}));
expectType<string[]>(dargs(object, {ignoreFalse: true}));
expectType<string[]>(dargs(object, {allowCamelCase: true}));
expectError(dargs({_: 'foo'}));
expectError(dargs({'--': 'foo'}));
================================================
FILE: license
================================================
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: package.json
================================================
{
"name": "dargs",
"version": "8.1.0",
"description": "Reverse minimist. Convert an object of options into an array of command-line arguments.",
"license": "MIT",
"repository": "sindresorhus/dargs",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"reverse",
"minimist",
"options",
"arguments",
"args",
"flags",
"cli",
"nopt",
"commander",
"binary",
"command",
"inverse",
"opposite",
"invert",
"switch",
"construct",
"parse",
"parser",
"argv"
],
"devDependencies": {
"ava": "^3.15.0",
"tsd": "^0.14.0",
"xo": "^0.39.1"
}
}
================================================
FILE: readme.md
================================================
# dargs
> Reverse [`minimist`](https://github.com/minimistjs/minimist). Convert an object of options into an array of command-line arguments.
Useful when spawning command-line tools.
## Install
```
$ npm install dargs
```
## Usage
```js
import dargs from 'dargs';
const object = {
_: ['some', 'option'], // Values in '_' will be appended to the end of the generated argument list
'--': ['separated', 'option'], // Values in '--' will be put at the very end of the argument list after the escape option (`--`)
foo: 'bar',
hello: true, // Results in only the key being used
cake: false, // Prepends `no-` before the key
camelCase: 5, // CamelCase is slugged to `camel-case`
multiple: ['value', 'value2'], // Converted to multiple arguments
pieKind: 'cherry',
sad: ':('
};
const excludes = ['sad', /.*Kind$/]; // Excludes and includes accept regular expressions
const includes = ['camelCase', 'multiple', 'sad', /^pie.*/];
const aliases = {file: 'f'};
console.log(dargs(object, {excludes}));
/*
[
'--foo=bar',
'--hello',
'--no-cake',
'--camel-case=5',
'--multiple=value',
'--multiple=value2',
'some',
'option',
'--',
'separated',
'option'
]
*/
console.log(dargs(object, {excludes, includes}));
/*
[
'--camel-case=5',
'--multiple=value',
'--multiple=value2'
]
*/
console.log(dargs(object, {includes}));
/*
[
'--camel-case=5',
'--multiple=value',
'--multiple=value2',
'--pie-kind=cherry',
'--sad=:('
]
*/
console.log(dargs({
foo: 'bar',
hello: true,
file: 'baz'
}, {aliases}));
/*
[
'--foo=bar',
'--hello',
'-f', 'baz'
]
*/
```
## API
### dargs(object, options?)
#### object
Type: `object`
Object to convert to command-line arguments.
#### options
Type: `object`
##### excludes
Type: `Array<string | RegExp>`
Keys or regex of keys to exclude. Takes precedence over `includes`.
##### includes
Type: `Array<string | RegExp>`
Keys or regex of keys to include.
##### aliases
Type: `object`
Maps keys in `object` to an aliased name. Matching keys are converted to arguments with a single dash (`-`) in front of the aliased key and the value in a separate array item. Keys are still affected by `includes` and `excludes`.
##### useEquals
Type: `boolean`\
Default: `true`
Setting this to `false` makes it return the key and value as separate array items instead of using a `=` separator in one item. This can be useful for tools that doesn't support `--foo=bar` style flags.
```js
import dargs from 'dargs';
console.log(dargs({foo: 'bar'}, {useEquals: false}));
/*
[
'--foo', 'bar'
]
*/
```
##### shortFlag
Type: `boolean`\
Default: `true`
Make a single character option key `{a: true}` become a short flag `-a` instead of `--a`.
```js
import dargs from 'dargs';
console.log(dargs({a: true}));
//=> ['-a']
console.log(dargs({a: true}, {shortFlag: false}));
//=> ['--a']
```
##### ignoreTrue
Type: `boolean`\
Default: `false`
Exclude `true` values. Can be useful when dealing with argument parsers that only expect negated arguments like `--no-foo`.
##### ignoreFalse
Type: `boolean`\
Default: `false`
Exclude `false` values. Can be useful when dealing with strict argument parsers that throw on unknown arguments like `--no-foo`.
##### allowCamelCase
Type: `boolean`\
Default: `false`
By default, camel-cased keys will be hyphenated. Enabling this will bypass the conversion process.
```js
import dargs from 'dargs';
console.log(dargs({fooBar: 'baz'}));
//=> ['--foo-bar', 'baz']
console.log(dargs({fooBar: 'baz'}, {allowCamelCase: true}));
//=> ['--fooBar', 'baz']
```
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-dargs?utm_source=npm-dargs&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
================================================
FILE: test.js
================================================
import test from 'ava';
import dargs from './index.js';
const fixture = {
_: ['some', 'option'],
'--': ['other', 'args', '-z', '--camelCaseOpt'],
a: 'foo',
b: true,
c: false,
d: 5,
e: ['foo', 'bar'],
f: null,
g: undefined,
h: 'with a space',
i: 'let\'s try quotes',
camelCaseCamel: true
};
test('convert options to cli flags', t => {
t.deepEqual(dargs(fixture), [
'-a=foo',
'-b',
'--no-c',
'-d=5',
'-e=foo',
'-e=bar',
'-h=with a space',
'-i=let\'s try quotes',
'--camel-case-camel',
'some',
'option',
'--',
'other',
'args',
'-z',
'--camelCaseOpt' // Case unaffected for separated options
]);
});
test('raises a TypeError if \'_\' value is not an Array', t => {
t.throws(dargs.bind(dargs, {a: 'foo', _: 'baz'}), {instanceOf: TypeError});
});
test('raises a TypeError if \'--\' value is not an Array', t => {
t.throws(dargs.bind(dargs, {a: 'foo', '--': 'baz'}), {instanceOf: TypeError});
});
test('useEquals options', t => {
t.deepEqual(dargs(fixture, {
useEquals: false
}), [
'-a',
'foo',
'-b',
'--no-c',
'-d',
'5',
'-e',
'foo',
'-e',
'bar',
'-h',
'with a space',
'-i',
'let\'s try quotes',
'--camel-case-camel',
'some',
'option',
'--',
'other',
'args',
'-z',
'--camelCaseOpt'
]);
});
test('exclude options', t => {
t.deepEqual(dargs(fixture, {excludes: ['b', /^e$/, 'h', 'i']}), [
'-a=foo',
'--no-c',
'-d=5',
'--camel-case-camel',
'some',
'option',
'--',
'other',
'args',
'-z',
'--camelCaseOpt'
]);
});
test('includes options', t => {
t.deepEqual(dargs(fixture, {includes: ['a', 'c', 'd', 'e', /^camelCase.*/]}), [
'-a=foo',
'--no-c',
'-d=5',
'-e=foo',
'-e=bar',
'--camel-case-camel'
]);
});
test('excludes and includes options', t => {
t.deepEqual(dargs(fixture, {
excludes: ['a', 'd'],
includes: ['a', 'c', /^[de]$/, 'camelCaseCamel']
}), [
'--no-c',
'-e=foo',
'-e=bar',
'--camel-case-camel'
]);
});
test('option to ignore true values', t => {
t.deepEqual(dargs({foo: true}, {ignoreTrue: true}), []);
});
test('option to ignore false values', t => {
t.deepEqual(dargs({foo: false}, {ignoreFalse: true}), []);
});
test('aliases option', t => {
t.deepEqual(dargs({a: 'foo', file: 'test'}, {
aliases: {file: 'f'}
}), [
'-a=foo',
'-f',
'test'
]);
});
test('includes and aliases options', t => {
t.deepEqual(dargs(fixture, {
includes: ['a', 'c', 'd', 'e', 'camelCaseCamel'],
aliases: {a: 'a'}
}), [
'-a',
'foo',
'--no-c',
'-d=5',
'-e=foo',
'-e=bar',
'--camel-case-camel'
]);
});
test('camelCase option', t => {
t.deepEqual(dargs(fixture, {
allowCamelCase: true
}), [
'-a=foo',
'-b',
'--no-c',
'-d=5',
'-e=foo',
'-e=bar',
'-h=with a space',
'-i=let\'s try quotes',
'--camelCaseCamel',
'some',
'option',
'--',
'other',
'args',
'-z',
'--camelCaseOpt'
]);
});
test('shortFlag option', t => {
t.deepEqual(dargs({a: 123, b: 'foo', foo: 'bar', camelCaseCamel: true}, {
shortFlag: false
}), [
'--a=123',
'--b=foo',
'--foo=bar',
'--camel-case-camel'
]);
});
gitextract_r37fvqu1/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── funding.yml │ ├── security.md │ └── workflows/ │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md └── test.js
SYMBOL INDEX (2 symbols across 2 files)
FILE: index.d.ts
type Options (line 1) | interface Options {
FILE: index.js
function dargs (line 4) | function dargs(object, options) {
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (19K chars).
[
{
"path": ".editorconfig",
"chars": 175,
"preview": "root = true\n\n[*]\nindent_style = tab\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newlin"
},
{
"path": ".gitattributes",
"chars": 19,
"preview": "* text=auto eol=lf\n"
},
{
"path": ".github/funding.yml",
"chars": 111,
"preview": "github: sindresorhus\nopen_collective: sindresorhus\ncustom: https://sindresorhus.com/donate\ntidelift: npm/dargs\n"
},
{
"path": ".github/security.md",
"chars": 179,
"preview": "# Security Policy\n\nTo report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/s"
},
{
"path": ".github/workflows/main.yml",
"chars": 436,
"preview": "name: CI\non:\n - push\n - pull_request\njobs:\n test:\n name: Node.js ${{ matrix.node-version }}\n runs-on: ubuntu-la"
},
{
"path": ".gitignore",
"chars": 23,
"preview": "node_modules\nyarn.lock\n"
},
{
"path": ".npmrc",
"chars": 19,
"preview": "package-lock=false\n"
},
{
"path": "index.d.ts",
"chars": 3838,
"preview": "export interface Options {\n\t/**\n\tKeys or regex of keys to exclude. Takes precedence over `includes`.\n\t*/\n\treadonly exclu"
},
{
"path": "index.js",
"chars": 2380,
"preview": "const match = (array, value) =>\n\tarray.some(element => (element instanceof RegExp ? element.test(value) : element === va"
},
{
"path": "index.test-d.ts",
"chars": 873,
"preview": "import {expectType, expectError} from 'tsd';\nimport dargs from './index.js';\n\nconst object = {\n\t_: ['some', 'option'],\n\t"
},
{
"path": "license",
"chars": 1117,
"preview": "MIT License\n\nCopyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n\nPermission is hereby grant"
},
{
"path": "package.json",
"chars": 886,
"preview": "{\n\t\"name\": \"dargs\",\n\t\"version\": \"8.1.0\",\n\t\"description\": \"Reverse minimist. Convert an object of options into an array o"
},
{
"path": "readme.md",
"chars": 4042,
"preview": "# dargs\n\n> Reverse [`minimist`](https://github.com/minimistjs/minimist). Convert an object of options into an array of c"
},
{
"path": "test.js",
"chars": 3096,
"preview": "import test from 'ava';\nimport dargs from './index.js';\n\nconst fixture = {\n\t_: ['some', 'option'],\n\t'--': ['other', 'arg"
}
]
About this extraction
This page contains the full source code of the sindresorhus/dargs GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (16.8 KB), approximately 5.4k tokens, and a symbol index with 2 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.