@trenskow/arguments-parser 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +11 -0
- package/README.md +85 -0
- package/eslint.config.js +54 -0
- package/index.js +9 -0
- package/lib/index.js +224 -0
- package/package.json +32 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Copyright 2024 Kristian Trenskow
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
4
|
+
|
|
5
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
6
|
+
|
|
7
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
8
|
+
|
|
9
|
+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
10
|
+
|
|
11
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# @trenskow/arguments-parser
|
|
2
|
+
|
|
3
|
+
Yet another arguments parser.
|
|
4
|
+
|
|
5
|
+
# Usage
|
|
6
|
+
|
|
7
|
+
````javascript
|
|
8
|
+
import argumentsParser from '@trenskow/arguments-parser';
|
|
9
|
+
|
|
10
|
+
const login = async (...args) => {
|
|
11
|
+
|
|
12
|
+
const {
|
|
13
|
+
username,
|
|
14
|
+
password
|
|
15
|
+
} = await argumentParser(args).options({
|
|
16
|
+
username: {
|
|
17
|
+
type: String,
|
|
18
|
+
required: true,
|
|
19
|
+
len: '1-',
|
|
20
|
+
description: "Username of the user"
|
|
21
|
+
},
|
|
22
|
+
password: {
|
|
23
|
+
type: String,
|
|
24
|
+
required: true,
|
|
25
|
+
len: '6-',
|
|
26
|
+
description: "Password of the user"
|
|
27
|
+
}
|
|
28
|
+
}, { login });
|
|
29
|
+
|
|
30
|
+
// Do login logic.
|
|
31
|
+
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
login.description = 'Logs in a user';
|
|
35
|
+
|
|
36
|
+
const message = async (...args) => {
|
|
37
|
+
|
|
38
|
+
const {
|
|
39
|
+
message
|
|
40
|
+
} = await argumentParser(args).options({
|
|
41
|
+
message: {
|
|
42
|
+
type: String,
|
|
43
|
+
default: 'Empty message',
|
|
44
|
+
description: 'Message to send'
|
|
45
|
+
}
|
|
46
|
+
}, { message });
|
|
47
|
+
|
|
48
|
+
// Do message logic.
|
|
49
|
+
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
message.description = 'Sends a message from a user.';
|
|
53
|
+
|
|
54
|
+
await argumentsParser(/* argv (default is `process.argv.slice(2)` */)
|
|
55
|
+
.command({ login, message });
|
|
56
|
+
````
|
|
57
|
+
|
|
58
|
+
The above example will output.
|
|
59
|
+
|
|
60
|
+
````
|
|
61
|
+
# ./my-script
|
|
62
|
+
Usage: my-script [command]
|
|
63
|
+
|
|
64
|
+
Available commands:
|
|
65
|
+
login Logs in a user.
|
|
66
|
+
message Sends a message from a user.
|
|
67
|
+
# ./my-script login --help
|
|
68
|
+
Usage: my-script login [options]
|
|
69
|
+
|
|
70
|
+
Options:
|
|
71
|
+
--username Username of the user.
|
|
72
|
+
--password Password of the user.
|
|
73
|
+
# ./my-script message --help
|
|
74
|
+
Usage: my-script message [options]
|
|
75
|
+
|
|
76
|
+
Options:
|
|
77
|
+
--message Message to send (default: `Empty message`).
|
|
78
|
+
|
|
79
|
+
````
|
|
80
|
+
|
|
81
|
+
> The validation schema is described in package [isvalid](https://github.com/trenskow/isvalid).
|
|
82
|
+
|
|
83
|
+
# License
|
|
84
|
+
|
|
85
|
+
See license in LICENSE.
|
package/eslint.config.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import globals from 'globals';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import js from '@eslint/js';
|
|
5
|
+
import { FlatCompat } from '@eslint/eslintrc';
|
|
6
|
+
|
|
7
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
8
|
+
const __dirname = path.dirname(__filename);
|
|
9
|
+
const compat = new FlatCompat({
|
|
10
|
+
baseDirectory: __dirname,
|
|
11
|
+
recommendedConfig: js.configs.recommended,
|
|
12
|
+
allConfig: js.configs.all
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export default [...compat.extends('eslint:recommended'), {
|
|
16
|
+
languageOptions: {
|
|
17
|
+
globals: {
|
|
18
|
+
...globals.node,
|
|
19
|
+
...globals.mocha,
|
|
20
|
+
},
|
|
21
|
+
|
|
22
|
+
ecmaVersion: 'latest',
|
|
23
|
+
sourceType: 'module',
|
|
24
|
+
},
|
|
25
|
+
|
|
26
|
+
rules: {
|
|
27
|
+
indent: ['error', 'tab', {
|
|
28
|
+
SwitchCase: 1,
|
|
29
|
+
}],
|
|
30
|
+
|
|
31
|
+
'linebreak-style': ['error', 'unix'],
|
|
32
|
+
quotes: ['error', 'single'],
|
|
33
|
+
semi: ['error', 'always'],
|
|
34
|
+
|
|
35
|
+
'no-console': ['error', {
|
|
36
|
+
allow: ['warn', 'error', 'info'],
|
|
37
|
+
}],
|
|
38
|
+
|
|
39
|
+
'no-unused-vars': ['error', {
|
|
40
|
+
argsIgnorePattern: '^_',
|
|
41
|
+
}],
|
|
42
|
+
|
|
43
|
+
'no-empty': ['error', {
|
|
44
|
+
allowEmptyCatch: true,
|
|
45
|
+
}],
|
|
46
|
+
|
|
47
|
+
'no-trailing-spaces': ['error', {
|
|
48
|
+
ignoreComments: true,
|
|
49
|
+
}],
|
|
50
|
+
|
|
51
|
+
'require-atomic-updates': 'off',
|
|
52
|
+
'eol-last': ['error', 'always'],
|
|
53
|
+
},
|
|
54
|
+
}];
|
package/index.js
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
//
|
|
2
|
+
// index.js
|
|
3
|
+
// @trenskow/arguments-parser
|
|
4
|
+
//
|
|
5
|
+
// Created by Kristian Trenskow on 2023/08/07
|
|
6
|
+
// See license in LICENSE.
|
|
7
|
+
//
|
|
8
|
+
|
|
9
|
+
import { basename } from 'path';
|
|
10
|
+
|
|
11
|
+
import caseit from '@trenskow/caseit';
|
|
12
|
+
import { default as isvalid, keyPaths, formalize } from 'isvalid';
|
|
13
|
+
import print from '@trenskow/print';
|
|
14
|
+
|
|
15
|
+
export default (args, argvLevel = 0) => {
|
|
16
|
+
|
|
17
|
+
const baseArguments = `${process.argv.slice(1, argvLevel + 2).map(((arg) => basename(arg))).join(' ')}`;
|
|
18
|
+
|
|
19
|
+
const list = (items) => {
|
|
20
|
+
|
|
21
|
+
const maxLength = Object.keys(items)
|
|
22
|
+
.reduce((length, key) => Math.max(length, key.length), 0);
|
|
23
|
+
|
|
24
|
+
Object.entries(items)
|
|
25
|
+
.forEach(([key, description]) => {
|
|
26
|
+
print.nn(` ${key}`, { minimumLength: maxLength + 4 });
|
|
27
|
+
print.sentence(description);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
command: async (commands) => {
|
|
34
|
+
|
|
35
|
+
const printHelp = (error) => {
|
|
36
|
+
|
|
37
|
+
print();
|
|
38
|
+
print(`Usage: ${baseArguments} [command]`);
|
|
39
|
+
print();
|
|
40
|
+
print('Available commands:');
|
|
41
|
+
print();
|
|
42
|
+
|
|
43
|
+
const tools = Object.keys(commands).map((key) => ({
|
|
44
|
+
name: caseit(key, 'kebab'),
|
|
45
|
+
description: commands[key].description
|
|
46
|
+
}));
|
|
47
|
+
|
|
48
|
+
tools.sort((a, b) => a.name > b.name ? 1 : -1);
|
|
49
|
+
|
|
50
|
+
list(Object.fromEntries(tools
|
|
51
|
+
.map((tool) => [tool.name, tool.description || 'No description'])));
|
|
52
|
+
|
|
53
|
+
if (error) {
|
|
54
|
+
print();
|
|
55
|
+
print();
|
|
56
|
+
print(`Error: ${error.message}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
print();
|
|
60
|
+
|
|
61
|
+
process.exit(error ? 1 : 0);
|
|
62
|
+
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
if (args.length === 0) printHelp();
|
|
66
|
+
|
|
67
|
+
const tool = caseit(args[0]);
|
|
68
|
+
|
|
69
|
+
if (!commands[tool]) printHelp(new Error(`${args[0]}: Command not found.`));
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
await commands[tool](...args.slice(1));
|
|
73
|
+
} catch (error) {
|
|
74
|
+
print.err(`${error.stack}`);
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
},
|
|
79
|
+
options: async (schema, options = {}) => {
|
|
80
|
+
|
|
81
|
+
schema = formalize(schema, {
|
|
82
|
+
plugins: [() => ({
|
|
83
|
+
phase: 'pre',
|
|
84
|
+
supportsType: () => true,
|
|
85
|
+
validatorsForType: () => ({
|
|
86
|
+
description: ['string'],
|
|
87
|
+
defaultDescription: ['string']
|
|
88
|
+
}),
|
|
89
|
+
validate: (data) => data,
|
|
90
|
+
formalize: (schema) => schema
|
|
91
|
+
})]
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
let nonOptions;
|
|
95
|
+
let nonOptionsIndex = args.indexOf('--');
|
|
96
|
+
|
|
97
|
+
if (nonOptionsIndex > -1) {
|
|
98
|
+
nonOptions = args.slice(nonOptionsIndex + 1).join(' ');
|
|
99
|
+
args = args.slice(0, nonOptionsIndex);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const allKeyPaths = keyPaths(schema)
|
|
103
|
+
.all()
|
|
104
|
+
.filter((keyPath) => keyPath);
|
|
105
|
+
|
|
106
|
+
const printHelp = (error) => {
|
|
107
|
+
|
|
108
|
+
if (typeof options?.cmd?.description === 'string') {
|
|
109
|
+
print();
|
|
110
|
+
print(options.cmd.description);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
print();
|
|
114
|
+
print.nn(`Usage: ${baseArguments} [options]`);
|
|
115
|
+
|
|
116
|
+
if (options.help?.postfix) print.nn(options.help.postfix);
|
|
117
|
+
|
|
118
|
+
print();
|
|
119
|
+
|
|
120
|
+
if (allKeyPaths.length) {
|
|
121
|
+
|
|
122
|
+
print();
|
|
123
|
+
print('Options:');
|
|
124
|
+
|
|
125
|
+
list(Object.fromEntries(allKeyPaths
|
|
126
|
+
.map((keyPath) => {
|
|
127
|
+
|
|
128
|
+
const keyPathSchema = keyPaths(schema).get(keyPath);
|
|
129
|
+
|
|
130
|
+
let description = keyPathSchema.description || 'No description';
|
|
131
|
+
|
|
132
|
+
if (typeof keyPathSchema.enum !== 'undefined') {
|
|
133
|
+
description += ` (${Object.keys(keyPathSchema.enum).map((value) => `\`${value}\``).join(', ')})`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (keyPathSchema.type === Array) {
|
|
137
|
+
description += ' (allows multiple)';
|
|
138
|
+
} else if (keyPathSchema.required === true) {
|
|
139
|
+
description += ' (required)';
|
|
140
|
+
} else if (typeof keyPathSchema.default !== 'undefined') {
|
|
141
|
+
description += ' (default: ';
|
|
142
|
+
if (keyPathSchema.type === Boolean) {
|
|
143
|
+
description += keyPathSchema.default === true ? 'enabled' : 'disabled';
|
|
144
|
+
} else {
|
|
145
|
+
description += `\`${keyPathSchema.defaultDescription ?? keyPathSchema.default}\``;
|
|
146
|
+
}
|
|
147
|
+
description += ')';
|
|
148
|
+
}
|
|
149
|
+
description += '.';
|
|
150
|
+
|
|
151
|
+
return [`--${caseit(keyPath, 'kebab')}`, description];
|
|
152
|
+
|
|
153
|
+
})));
|
|
154
|
+
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
print();
|
|
158
|
+
|
|
159
|
+
process.exit(error ? 1 : 0);
|
|
160
|
+
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
let data = {};
|
|
164
|
+
let rest = [];
|
|
165
|
+
|
|
166
|
+
let idx;
|
|
167
|
+
|
|
168
|
+
for (idx = 0 ; idx < args.length ; idx++) {
|
|
169
|
+
|
|
170
|
+
if (args[idx].slice(0, 2) !== '--') {
|
|
171
|
+
rest.push(args[idx]);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const arg = args[idx].slice(2);
|
|
176
|
+
|
|
177
|
+
const key = caseit(arg);
|
|
178
|
+
|
|
179
|
+
if (key === 'help') printHelp();
|
|
180
|
+
|
|
181
|
+
if (!keyPaths(schema).all().includes(key)) printHelp(new Error(`Unknown option: ${args[idx]}.`));
|
|
182
|
+
|
|
183
|
+
let value;
|
|
184
|
+
|
|
185
|
+
if (keyPaths(schema).get(key).type === Boolean) {
|
|
186
|
+
value = true;
|
|
187
|
+
} else {
|
|
188
|
+
if (args.length <= idx + 1 || args[idx + 1].slice(0, 2) === '--') {
|
|
189
|
+
printHelp(new Error(`Argument missing for option: ${args[idx]}.`));
|
|
190
|
+
}
|
|
191
|
+
value = args[++idx];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (typeof data[key] === 'undefined') {
|
|
195
|
+
data[key] = value;
|
|
196
|
+
} else if (Array.isArray(data[key])) {
|
|
197
|
+
data[key].push(value);
|
|
198
|
+
} else {
|
|
199
|
+
data[key] = [data[key], value];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
try {
|
|
205
|
+
data = await isvalid(data, schema, {
|
|
206
|
+
stopAtFirstError: false
|
|
207
|
+
});
|
|
208
|
+
} catch (error) {
|
|
209
|
+
printHelp(new Error(`--${caseit(error.keyPath.join('.'), 'kebab')}: ${error.message}`));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return Object.assign({}, data, {
|
|
213
|
+
onError: (error) => {
|
|
214
|
+
print.err(error.message);
|
|
215
|
+
process.exit(1);
|
|
216
|
+
},
|
|
217
|
+
nonOptions,
|
|
218
|
+
rest
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@trenskow/arguments-parser",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Yet another arguments parser.",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/trenskow/arguments-parser.git"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"arguments",
|
|
16
|
+
"parser",
|
|
17
|
+
"argument",
|
|
18
|
+
"parse"
|
|
19
|
+
],
|
|
20
|
+
"author": "Kristian Trenskow <this.is@kristians.email>",
|
|
21
|
+
"license": "BSD-3-Clause",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/trenskow/arguments-parser/issues"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/trenskow/arguments-parser#readme",
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@trenskow/caseit": "^1.4.5",
|
|
28
|
+
"@trenskow/print": "^0.1.0",
|
|
29
|
+
"eslint": "^9.17.0",
|
|
30
|
+
"isvalid": "^4.1.23"
|
|
31
|
+
}
|
|
32
|
+
}
|