Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support array-type #1

Merged
merged 4 commits into from
Dec 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ const parsed = typeFlag(process.argv.slice(2), {
someBoolean: {
type: Boolean,
alias: 'b'
},

// Wrap with an array to indicate an array type
stringArray: [String],

numberArray: {
type: [Number]
}
})

Expand All @@ -46,9 +53,11 @@ console.log(parsed.flags.someString[0])
```ts
{
flags: {
someString: string[];
someNumber: boolean[];
someBoolean: number[];
someString: string | undefined;
someNumber: boolean | undefined;
someBoolean: number | undefined;
stringArray: string[];
numberArray: number[];
};
unknownFlags: {
[flagName: string]: (string | boolean)[];
Expand Down Expand Up @@ -142,7 +151,7 @@ const parsed = typeFlag(process.argv.slice(2), {
```ts
const parsed: {
flags: {
size: Sizes[];
size: Sizes | undefined;
};
...
}
Expand Down Expand Up @@ -182,7 +191,7 @@ function EnvObject(value: string): Env {
}

const parsed = typeFlag(process.argv.slice(2), {
env: EnvObject,
env: [EnvObject],
});

const env = parsed.flags.env.reduce((agg, next) => Object.assign(agg, next), {});
Expand All @@ -206,7 +215,7 @@ $ node ./cli --boolean-flag false
```ts
{
flags: {
booleanFlag: [true]
booleanFlag: true
},
_: ['false']
}
Expand All @@ -220,7 +229,7 @@ Returns an object with the shape:
```ts
{
flags: {
[flagName: string]: InferredType[];
[flagName: string]: InferredType;
};
unknownFlags: {
[flagName: string]: (string | boolean)[];
Expand All @@ -241,8 +250,8 @@ Type:
type TypeFunction = (argvValue: any) => any;

type FlagSchema = {
[flagName: string]: TypeFunction | {
type?: TypeFunction; // defaults to String
[flagName: string]: TypeFunction | [TypeFunction] | {
type: TypeFunction | [TypeFunction];
alias?: string;
};
};
Expand Down
2 changes: 1 addition & 1 deletion examples/dot-nested.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function EnvironmentObject(value: string): Environment {
}

const parsed = typeFlag(process.argv.slice(2), {
env: EnvironmentObject,
env: [EnvironmentObject],
});

// eslint-disable-next-line unicorn/no-array-reduce,unicorn/prefer-object-from-entries
Expand Down
51 changes: 33 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,69 @@
import type {
TypeFunction,
FlagSchema,
Flags,
ParsedFlags,
FlagTypeOrSchema,
} from './types';
import {
toCamelCase,
createFlagsObject,
mapAliases,
parseFlag,
getDefaultFromTypeWithValue,
isFlagSchemaWithType,
} from './utils';

const isAliasPattern = /^-[\da-z]+/i;
const isFlagPattern = /^--[\w-]{2,}/;

const getFlagType = (
flagSchema: FlagTypeOrSchema,
): TypeFunction => {
if (typeof flagSchema === 'function') {
return flagSchema;
}

if (Array.isArray(flagSchema)) {
return flagSchema[0];
}

return getFlagType(flagSchema.type);
};

function typeFlag<Schemas extends Flags>(
argv: string[],
schemas: Schemas,
) {
const aliasesMap = mapAliases(schemas);
const flags = createFlagsObject<Schemas>(schemas);
const unknownFlags: ParsedFlags = {};
const unknownFlags: {
[flag: string]: (string | boolean)[];
} = {};
const remainingArguments: string[] = [];

let expectingValue: undefined | ((value?: string | boolean) => void);

const setKnown = (
flagName: string,
flagSchema: TypeFunction | FlagSchema,
flagName: keyof Schemas,
flagSchema: FlagTypeOrSchema,
flagValue: any,
) => {
const flagType = (
typeof flagSchema === 'function'
? flagSchema
: (
isFlagSchemaWithType(flagSchema)
? flagSchema.type
: String
)
);
const flagType = getFlagType(flagSchema);

flagValue = getDefaultFromTypeWithValue(flagType, flagValue);

if (flagValue !== undefined && !Number.isNaN(flagValue)) {
flags[flagName].push(flagType(flagValue));
if (Array.isArray(flags[flagName])) {
flags[flagName].push(flagType(flagValue));
} else {
flags[flagName] = flagType(flagValue);
}
} else {
expectingValue = (value) => {
flags[flagName].push(flagType(getDefaultFromTypeWithValue(flagType, value || '')));
if (Array.isArray(flags[flagName])) {
flags[flagName].push(flagType(getDefaultFromTypeWithValue(flagType, value || '')));
} else {
flags[flagName] = flagType(getDefaultFromTypeWithValue(flagType, value || ''));
}

expectingValue = undefined;
};
}
Expand Down Expand Up @@ -93,7 +108,7 @@ function typeFlag<Schemas extends Flags>(
let { flagName } = parsedFlag;

if (isAlias) {
const aliases = flagName.split('');
const aliases = flagName.split(''); // TODO: no need to splitt
for (let j = 0; j < aliases.length; j += 1) {
const alias = aliases[j];
const hasAlias = aliasesMap.get(alias);
Expand Down
35 changes: 18 additions & 17 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
export type TypeFunction = (argvValue: any) => any;
export type TypeFunction<T = any> = (argvValue: any) => T;

export type TypeFunctionArray<T = any> = [TypeFunction<T>];

export type FlagSchema = {
type?: TypeFunction;
type: TypeFunction | TypeFunctionArray;
alias?: string;
};

export type FlagTypeOrSchema = TypeFunction | TypeFunctionArray | FlagSchema;

export type Flags = {
[flagName: string]: TypeFunction | FlagSchema;
[flagName: string]: FlagTypeOrSchema;
};

export type ParsedFlags = {
[flag: string]: (string | boolean)[];
};

export type InferFlagType<Flag extends (TypeFunction | FlagSchema)> = ReturnType<
Flag extends TypeFunction
// Constructor function
? Flag

// Schema object
: (
Flag extends { type: TypeFunction }
// Constructor function
? Flag['type']
export type InferFlagType<
Flag extends FlagTypeOrSchema
> = Flag extends (TypeFunction<infer T> | { type: TypeFunction<infer T> })
// Type function return-type
? (T | undefined)

// Fallback to string
: StringConstructor
)
>;
// Type function return-type in array
: (
Flag extends (TypeFunctionArray<infer T> | { type: TypeFunctionArray<infer T> })
? T[]
: never
);
27 changes: 14 additions & 13 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import type {
TypeFunction,
FlagSchema,
Flags,
ParsedFlags,
InferFlagType,
FlagTypeOrSchema,
} from './types';

const kebabCasePattern = /-(\w)/g;
Expand Down Expand Up @@ -85,9 +85,9 @@ export function mapAliases<Schemas extends Flags>(

validateFlagName(schemas, name);

const schema = schemas[name];
const schema = schemas[name] as FlagSchema;
if (schema && typeof schema === 'object') {
const { alias } = schema as FlagSchema;
const { alias } = schema;
if (alias) {
assert(alias.length > 0, `Invalid flag alias ${stringify(name)}: flag alias cannot be empty`);
assert(alias.length === 1, `Invalid flag alias ${stringify(name)}: flag aliases can only be a single-character`);
Expand All @@ -107,17 +107,25 @@ export function mapAliases<Schemas extends Flags>(
return aliases;
}

const isArrayType = (schema: FlagTypeOrSchema) => {
if (typeof schema === 'function') {
return false;
}

return (Array.isArray(schema) || Array.isArray(schema.type));
};

export const createFlagsObject = <Schemas extends Flags>(schema: Flags) => {
const flags: ParsedFlags = {};
const flags: Record<string, any> = {};

for (const flag in schema) {
if (hasOwn(schema, flag)) {
flags[flag] = [];
flags[flag] = isArrayType(schema[flag]) ? [] : undefined;
}
}

return flags as {
[flag in keyof Schemas]: InferFlagType<Schemas[flag]>[];
[flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
};
};

Expand All @@ -135,10 +143,3 @@ export const getDefaultFromTypeWithValue = (

return value;
};

export const isFlagSchemaWithType = (
schema: FlagSchema,
): schema is { type: TypeFunction } => (
('type' in schema)
&& (typeof schema.type === 'function')
);
Loading