import { CliArgsObject, ArgumentValue } from '@push-based/models';
/**
* Converts an object with different types of values into an array of command-line arguments.
*
* @example
* const args = objectToCliArgs({
* _: ['node', 'index.js'], // node index.js
* name: 'Juanita', // --name=Juanita
* formats: ['json', 'md'] // --format=json --format=md
* });
*/
export function objectToCliArgs<
T extends object = Record<string, ArgumentValue>,
>(params?: CliArgsObject<T>): string[] {
if (!params) {
return [];
}
return Object.entries(params).flatMap(([key, value]) => {
// process/file/script
if (key === '_') {
return Array.isArray(value) ? value : [`${value}`];
}
const prefix = key.length === 1 ? '-' : '--';
// "-*" arguments (shorthands)
if (Array.isArray(value)) {
return value.map((v) => `${prefix}${key}="${v}"`);
}
// "--*" arguments ==========
if (Array.isArray(value)) {
return value.map((v) => `${prefix}${key}="${v}"`);
}
if (typeof value === 'object') {
return Object.entries(value as Record<string, ArgumentValue>).flatMap(
// transform nested objects to the dot notation `key.subkey`
([k, v]) => objectToCliArgs({ [`${key}.${k}`]: v }),
);
}
if (typeof value === 'string') {
return [`${prefix}${key}="${value}"`];
}
if (typeof value === 'number') {
return [`${prefix}${key}=${value}`];
}
if (typeof value === 'boolean') {
return [`${prefix}${value ? '' : 'no-'}${key}`];
}
throw new Error(`Unsupported type ${typeof value} for key ${key}`);
});
}
export function calcDuration(start: number, stop?: number): number {
return Math.round((stop ?? performance.now()) - start);
}