storybook/scripts/utils/options.ts

328 lines
10 KiB
TypeScript
Raw Normal View History

/**
* Use commander and prompts to gather a list of options for a script
*/
2022-11-24 20:13:28 +01:00
import prompts from 'prompts';
import type { PromptObject, Falsy, PrevCaller, PromptType } from 'prompts';
import program from 'commander';
2022-08-08 18:29:08 +02:00
import dedent from 'ts-dedent';
import chalk from 'chalk';
2022-07-25 16:21:49 +10:00
import kebabCase from 'lodash/kebabCase';
2022-07-27 20:13:36 +10:00
// Option types
export type OptionId = string;
export type BaseOption = {
type: 'boolean' | 'string' | 'string[]';
description?: string;
2022-07-25 16:21:49 +10:00
/**
* By default the one-char version of the option key will be used as short flag. Override here,
* e.g. `shortFlag: 'c'`
*/
shortFlag?: string;
2022-07-28 20:15:57 +10:00
/**
* What type of prompt to use? (return false to skip, true for default)
*/
promptType?: PromptType | Falsy | PrevCaller<string, PromptType | boolean>;
};
2022-07-25 16:21:49 +10:00
export type BooleanOption = BaseOption & {
type: 'boolean';
2022-07-25 16:21:49 +10:00
/**
* Does this option default true?
*/
inverse?: boolean;
};
export type StringOption = BaseOption & {
type: 'string';
2022-07-28 20:15:57 +10:00
/**
* What values are allowed for this option?
*/
values?: readonly string[];
/**
* How to describe the values when selecting them
*/
valueDescriptions?: readonly string[];
2022-07-28 20:15:57 +10:00
/**
* Is a value required for this option?
*/
required?: boolean | ((previous: Record<string, any>) => boolean);
};
2022-07-27 20:13:36 +10:00
export type StringArrayOption = BaseOption & {
type: 'string[]';
2022-07-28 20:15:57 +10:00
/**
* What values are allowed for this option?
*/
values?: readonly string[];
/**
* How to describe the values when selecting them
*/
valueDescriptions?: readonly string[];
2022-07-27 20:13:36 +10:00
};
export type Option = BooleanOption | StringOption | StringArrayOption;
export type MaybeOptionValue<TOption extends Option> = TOption extends StringArrayOption
? TOption extends { values: infer TValues }
? TValues extends readonly string[]
? TValues[number][]
: never // It isn't possible for values to not be a readonly string[], but TS can't work it out
: string[]
2022-07-27 20:13:36 +10:00
: TOption extends StringOption
? TOption extends { values: infer TValues }
? TValues extends readonly string[]
? TValues[number] | undefined
: never // It isn't possible for values to not be a readonly string[], but TS can't work it out
: string | undefined
2022-07-27 20:13:36 +10:00
: TOption extends BooleanOption
? boolean
: never;
export type OptionValue<TOption extends Option> = TOption extends { required: true }
? NonNullable<MaybeOptionValue<TOption>>
2022-07-27 20:13:36 +10:00
: MaybeOptionValue<TOption>;
export type OptionSpecifier = Record<OptionId, Option>;
2022-07-27 20:13:36 +10:00
export type MaybeOptionValues<TOptions extends OptionSpecifier> = {
[TKey in keyof TOptions]: MaybeOptionValue<TOptions[TKey]>;
};
2022-07-28 20:15:57 +10:00
export type OptionValues<TOptions extends OptionSpecifier = OptionSpecifier> = {
2022-07-27 20:13:36 +10:00
[TKey in keyof TOptions]: OptionValue<TOptions[TKey]>;
};
export function createOptions<TOptions extends OptionSpecifier>(options: TOptions) {
return options;
}
const logger = console;
2022-07-25 16:21:49 +10:00
function shortFlag(key: OptionId, option: Option) {
const inverse = option.type === 'boolean' && option.inverse;
2022-07-25 16:21:49 +10:00
const defaultShortFlag = inverse ? key.substring(0, 1).toUpperCase() : key.substring(0, 1);
2022-07-27 20:13:36 +10:00
const short = option.shortFlag || defaultShortFlag;
if (short.length !== 1) {
2022-07-25 16:21:49 +10:00
throw new Error(
2022-07-27 20:13:36 +10:00
`Invalid shortFlag for ${key}: '${short}', needs to be a single character (e.g. 's')`
2022-07-25 16:21:49 +10:00
);
}
2022-07-27 20:13:36 +10:00
return short;
2022-07-25 16:21:49 +10:00
}
function longFlag(key: OptionId, option: Option) {
const inverse = option.type === 'boolean' && option.inverse;
2022-07-25 16:21:49 +10:00
return inverse ? `no-${kebabCase(key)}` : kebabCase(key);
}
function optionFlags(key: OptionId, option: Option) {
const base = `-${shortFlag(key, option)}, --${longFlag(key, option)}`;
if (option.type === 'string' || option.type === 'string[]') {
2022-07-25 16:21:49 +10:00
return `${base} <${key}>`;
}
return base;
}
2022-07-27 20:13:36 +10:00
export function getOptions<TOptions extends OptionSpecifier>(
command: program.Command,
2022-07-27 20:13:36 +10:00
options: TOptions,
argv: string[]
): MaybeOptionValues<TOptions> {
2022-07-25 16:21:49 +10:00
Object.entries(options)
.reduce((acc, [key, option]) => {
const flags = optionFlags(key, option);
2022-07-27 20:13:36 +10:00
if (option.type === 'boolean') return acc.option(flags, option.description, !!option.inverse);
2022-07-27 20:13:36 +10:00
const checkStringValue = (raw: string) => {
2022-08-08 10:34:39 +10:00
if (option.values && !option.values.includes(raw)) {
2022-08-08 18:29:08 +02:00
const possibleOptions = chalk.cyan(option.values.join(', '));
throw new Error(
dedent`Unexpected value '${chalk.yellow(raw)}' for option '${chalk.magenta(key)}'.
These are the possible options: ${possibleOptions}\n\n`
);
}
2022-07-27 20:13:36 +10:00
return raw;
};
if (option.type === 'string')
2022-07-27 20:13:36 +10:00
return acc.option(flags, option.description, (raw) => checkStringValue(raw));
if (option.type === 'string[]') {
2022-07-27 20:13:36 +10:00
return acc.option(
flags,
option.description,
(raw, values) => [...values, checkStringValue(raw)],
[]
);
}
2022-07-27 20:13:36 +10:00
throw new Error(`Unexpected option type '${key}'`);
}, command)
.parse(argv);
2022-07-27 20:13:36 +10:00
// Note the code above guarantees the types as they come in, so we cast here.
// Not sure there is an easier way to do this
return command.opts() as MaybeOptionValues<TOptions>;
2022-07-25 16:29:14 +10:00
}
// Boolean values will have a default, usually `false`, `true` if they are "inverse".
// String arrays default to []
// Currently it isn't possible to have a default for string
export function getDefaults<TOptions extends OptionSpecifier>(options: TOptions) {
return Object.fromEntries(
Object.entries(options)
.filter(([, { type }]) => type === 'boolean' || type === 'string[]')
.map(([key, option]) => {
if (option.type === 'boolean') return [key, !!option.inverse];
if (option.type === 'string[]') return [key, []];
throw new Error('Not reachable');
})
);
}
function checkRequired<TOptions extends OptionSpecifier>(
option: TOptions[keyof TOptions],
values: MaybeOptionValues<TOptions>
) {
if (option.type !== 'string' || !option.required) return false;
if (typeof option.required === 'boolean') return option.required;
return option.required(values);
}
2022-07-27 20:13:36 +10:00
export function areOptionsSatisfied<TOptions extends OptionSpecifier>(
options: TOptions,
values: MaybeOptionValues<TOptions>
) {
return !Object.entries(options)
.filter(([, option]) => checkRequired(option as TOptions[keyof TOptions], values))
.find(([key]) => !values[key]);
}
2022-07-27 20:13:36 +10:00
export async function promptOptions<TOptions extends OptionSpecifier>(
options: TOptions,
values: MaybeOptionValues<TOptions>
): Promise<OptionValues<TOptions>> {
const questions = Object.entries(options).map(([key, option]): PromptObject => {
2022-07-28 20:15:57 +10:00
let defaultType: PromptType = 'toggle';
if (option.type !== 'boolean') {
if (option.type === 'string[]') {
defaultType = option.values ? 'autocompleteMultiselect' : 'list';
} else {
defaultType = option.values ? 'select' : 'text';
}
}
2022-07-28 20:15:57 +10:00
2022-07-28 20:30:06 +10:00
const passedType = option.promptType;
2022-07-28 20:15:57 +10:00
let type: PromptObject['type'] = defaultType;
// Allow returning `undefined` from `type()` function to fallback to default
if (typeof passedType === 'function') {
type = (...args: Parameters<typeof passedType>) => {
const chosenType = passedType(...args);
return chosenType === true ? defaultType : chosenType;
};
} else if (typeof passedType !== 'undefined') {
2022-07-28 20:15:57 +10:00
type = passedType;
}
if (option.type !== 'boolean') {
if (values[key]) {
return { name: key, type: false };
}
return {
name: key,
2022-07-28 20:15:57 +10:00
type,
message: option.description,
choices: option.values?.map((value, index) => ({
title: option.valueDescriptions?.[index] || value,
value,
})),
};
}
return {
2022-07-28 20:15:57 +10:00
type,
message: option.description,
name: key,
2022-07-25 16:21:49 +10:00
initial: option.inverse,
2022-07-25 17:00:35 +10:00
active: 'yes',
inactive: 'no',
};
});
2022-08-15 10:45:30 +02:00
const selection = await prompts(questions, {
onCancel: () => {
logger.log('Command cancelled by the user. Exiting...');
2022-08-15 16:59:55 +08:00
process.exit(1);
2022-08-15 10:45:30 +02:00
},
});
2022-07-27 20:13:36 +10:00
// Again the structure of the questions guarantees we get responses of the type we need
return { ...values, ...selection } as OptionValues<TOptions>;
}
2022-07-27 20:13:36 +10:00
function getFlag<TOption extends Option>(
key: OptionId,
option: TOption,
2022-07-27 22:17:39 +10:00
value?: OptionValue<TOption>
2022-07-27 20:13:36 +10:00
) {
if (option.type === 'boolean') {
2022-07-27 20:13:36 +10:00
const toggled = option.inverse ? !value : value;
return toggled ? `--${longFlag(key, option)}` : '';
}
if (option.type === 'string[]') {
2022-07-27 22:13:29 +10:00
// I'm not sure why TS isn't able to infer that OptionValue<TOption> is a
// OptionValue<StringArrayOption> (i.e. a string[]), given that it knows
// option is a StringArrayOption
return ((value || []) as OptionValue<StringArrayOption>)
2022-07-28 19:46:40 +10:00
.map((v) => `--${longFlag(key, option)} ${v}`)
.join(' ');
2022-07-27 20:13:36 +10:00
}
if (option.type === 'string') {
if (value) {
2022-07-25 16:21:49 +10:00
return `--${longFlag(key, option)} ${value}`;
}
2022-07-25 16:21:49 +10:00
return '';
}
2022-07-27 20:13:36 +10:00
throw new Error(`Unknown option type for '${key}'`);
}
2022-07-27 20:13:36 +10:00
export function getCommand<TOptions extends OptionSpecifier>(
prefix: string,
options: TOptions,
2022-07-27 22:17:39 +10:00
values: Partial<OptionValues<TOptions>>
2022-07-27 20:13:36 +10:00
) {
const flags = Object.keys(options)
2022-07-25 16:21:49 +10:00
.map((key) => getFlag(key, options[key], values[key]))
.filter(Boolean);
return `${prefix} ${flags.join(' ')}`;
}
2022-07-27 20:13:36 +10:00
export async function getOptionsOrPrompt<TOptions extends OptionSpecifier>(
commandPrefix: string,
options: TOptions
): Promise<OptionValues<TOptions>> {
const main = program.version('5.0.0');
const cliValues = getOptions(main as any, options, process.argv);
if (areOptionsSatisfied(options, cliValues)) {
2022-07-27 20:13:36 +10:00
// areOptionsSatisfied could be a type predicate but I'm not quite sure how to do it
return cliValues as OptionValues<TOptions>;
}
if (process.env.CI)
throw new Error(`${commandPrefix} needed to prompt for options, this is not possible in CI!`);
const finalValues = await promptOptions(options, cliValues);
const command = getCommand(commandPrefix, options, finalValues);
logger.log(`\nTo run this directly next time, use:\n ${command}\n`);
return finalValues;
}