@keg-hub/args-parse
Advanced tools
Comparing version 6.2.3 to 6.3.0
{ | ||
"name": "@keg-hub/args-parse", | ||
"version": "6.2.3", | ||
"version": "6.3.0", | ||
"description": "Parse command line arguments", | ||
@@ -5,0 +5,0 @@ "main": "src/index.js", |
@@ -236,2 +236,34 @@ const { testTask1, testTask2, testTask3, testTask4, testTask5 } = require('../__mocks__/testTasks') | ||
it('should convert an object type to an object when it is a colon string with multiple entries', async () => { | ||
const expected = { | ||
foo: "1", | ||
bar: "2", | ||
baz: 'hello' | ||
} | ||
const parsed = await argsParse({ | ||
args: [ | ||
"--object", | ||
"foo:1,bar:2,baz:hello" | ||
], | ||
task: testTask3, | ||
}) | ||
expect(parsed.object).toEqual(expected) | ||
}) | ||
it('should convert an object type to an object when it is a colon string with a single entry', async () => { | ||
const expected = { | ||
foo: "1", | ||
} | ||
const parsed = await argsParse({ | ||
args: [ | ||
"--object", | ||
"foo:1" | ||
], | ||
task: testTask3, | ||
}) | ||
expect(parsed.object).toEqual(expected) | ||
}) | ||
it('should call @keg-hub/ask-it when no value is passed and task.ask is exist', async () => { | ||
@@ -238,0 +270,0 @@ |
@@ -40,2 +40,35 @@ const { checkBoolValue } = require('./checkBoolValue') | ||
/** | ||
* @param {string} str | ||
* @returns {Object} the comma-separated colon string converted into an object | ||
* @example | ||
* colonStringToObject("foo:1,bar:2") => { foo: "1", bar: "2" } | ||
*/ | ||
const colonStringToObject = str => { | ||
const pairs = str.trim().split(',') | ||
return pairs.reduce( | ||
(obj, pair) => { | ||
const [ key, value ] = pair.trim().split(':') | ||
obj[key] = value | ||
return obj | ||
}, | ||
{} | ||
) | ||
} | ||
/** | ||
* Convert the passed in value to an object | ||
* <br/>If it can't convert to an object, it returns an empty object | ||
* @function | ||
* @param {string} value - Data passed from cmd line | ||
*/ | ||
const valueToObject = value => { | ||
if (!isStr(value)) return {} | ||
// check if the string matches pattern <key>:<value>,<key>:<value> | ||
return value.trim().match(/^[^\s{}]+:[^\s{}]+$/g) | ||
? colonStringToObject(value) | ||
: parseJSON(value, false) || {} | ||
} | ||
/** | ||
* Convert the passed in value to a type based on the meta | ||
@@ -58,3 +91,3 @@ * @function | ||
case 'object': { | ||
return parseJSON(value, false) | ||
return valueToObject(value) | ||
} | ||
@@ -61,0 +94,0 @@ case 'num': |
44433
1256