Skip to content
Open
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
29 changes: 29 additions & 0 deletions src/command.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { autoConfig } from './index';
import { mockArgv, setEnvKey } from './test/utils';

import minimist from 'minimist';
console.log('process.argv', process.argv);
console.log('minimist', minimist(process.argv.slice(2)))

describe('autoCommand CLI functionality', () => {
test('handles sub-commands', () => {
const resetEnv = setEnvKey('PORT', '8080');

const command = autoConfig({
port: {
help: 'The port to listen on.',
args: ['--port', 'PORT'],
type: 'number',
required: true,
},
debugMode: {
args: ['--debug', 'DEBUG', '--debugMode', 'DEBUG_MODE'],
type: 'boolean',
default: true,
},
});
resetEnv();
// expect(config.port).toBe(8080);
// expect(config.debugMode).toBe(true);
});
});
49 changes: 49 additions & 0 deletions src/command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import debug from 'debug';
import { autoConfig } from 'src';
import { CommandOption, CompleteConfig, OptionTypeConfig } from './types';

type Commands<TInput> = {
[commandName: string]: CompleteConfig<TInput>;
// TODO: Add Commands
};
type OptionTypes = NonNullable<OptionTypeConfig['type']>;

type AutoCommandOptions = {
cliArgs: string[];
envKeys: Record<string, string | undefined>;
};

const defaultOptions = {
cliArgs: process.argv.slice(2),
envKeys: process.env,
} as const;

export default function autoCommand<TInput extends object>(
commandConfig: Commands<TInput>,
{
cliArgs = process.argv.slice(2),
envKeys = process.env,
}: AutoCommandOptions = defaultOptions
) {
const debugLog = debug('auto-command');
debugLog(`Starting Command Processor for args: ${cliArgs.join(', ')}`);
const availableCommands = Object.keys(commandConfig);
debugLog('availableCommands', availableCommands);
// TODO
// 1. check for sub-commands in argv
// 2. if sub-command found, split the argv, and use autoConfig on the following arguments
const baseCommand = cliArgs[0];
debugLog(`Looking for base command: ${baseCommand}`);
if (baseCommand && availableCommands.includes(baseCommand)) {
debugLog(`Found base command: ${baseCommand}`);
const subCommandConfig = commandConfig[baseCommand];
debugLog('subCommandConfig', subCommandConfig);
autoConfig(subCommandConfig, {
overrides: {cliArgs, envKeys}
})
// if (typeof subCommandConfig === 'object') {
// return autoCommand(subCommandConfig);
// }
}
// const matchingCommand = process.argv.find(arg => availableCommands.includes(arg));
}
2 changes: 1 addition & 1 deletion src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ beforeEach(() => {
processExitSpy.mockClear();
});

describe('core features', () => {
describe.only('core features', () => {
test('loads environment variables', () => {
const resetPort = setEnvKey('PORT', '8080');
const config = autoConfig({
Expand Down
17 changes: 14 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,30 @@ import {
} from './utils';
import type {
CommandOption,
CompleteConfig,
ConfigInputsParsed,
ConfigInputsRaw,
ConfigResults,
} from './types';
import { optionsHelp } from './render';

export { easyConfig } from './easy-config';

export const SupportedDataTypes = ['string', 'number', 'boolean', 'array', 'date'];

interface InputOverrides {
overrides: ConfigInputsRaw;
}

export const autoConfig = function <
TInput extends { [K in keyof TInput]: CommandOption }
>(config: TInput) {
TInput extends CompleteConfig<TInput>
>(config: TInput, {
overrides
}: InputOverrides = { overrides: {} }) {
const debugLog = debug('auto-config');
debugLog('START: Loading runtime environment & command line arguments.');
let { cliArgs, envKeys } = getEnvAndArgs();
let { cliArgs, envKeys } = getEnvAndArgs({ ...overrides });

if (debugLog.enabled) {
debugLog('runtime.cliArgs', JSON.stringify(cliArgs));
debugLog('runtime.envKeys', JSON.stringify(envKeys));
Expand Down
7 changes: 5 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ export type OptionTypeConfig =
max?: number;
};


export type CompleteConfig<TInput> = { [K in keyof TInput]: CommandOption };

// type Flatten<Type> = Type extends Array<infer Item> ? Item : Type;
// type GetEnumOption<TOption> = TOption extends { enum: Array<infer EnumItem> } ? EnumItem : never;
export type PrimitiveTypes = string | number | boolean | Date | null;
Expand All @@ -74,8 +77,8 @@ export type ConfigInputsRaw = {
};

export type ConfigInputsParsed = {
cliArgs?: minimist.ParsedArgs;
envKeys?: NodeJS.ProcessEnv;
cliArgs: minimist.ParsedArgs;
envKeys: NodeJS.ProcessEnv;
};

export type ConfigResults<
Expand Down
22 changes: 14 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,18 @@ import type {
OptionTypeConfig,
} from './types';


const debugLog = debug('auto-config:utils');

/**
* ⚠️ **Warning:** Very permissive boolean coercion.
*
* 1. Normalizes inputs to string, trim, and lower case.
* 2. Returns true if input matches any: `1`, `on`, `t`, `true`, `y`, and `yes`
*
*/
export function toBoolean(value: any) {
value = value.toString().toLowerCase();
value = `${value}`.toString().trim().toLowerCase();
return (
value === 'true' ||
value === 't' ||
Expand All @@ -21,9 +29,6 @@ export function toBoolean(value: any) {
value === 'on'
);
}
// export function isNestedObject(obj: unknown) {
// return isObject(obj) && !Array.isArray(obj) && keys(obj).length > 0;
// }

export function applyType(
value: string,
Expand Down Expand Up @@ -57,16 +62,16 @@ export function cleanupStringList(
return processed as string[];
}

export const stripDashes = (str: string = '') => str.replace(/^-+/gi, '');
export const stripDashes = (str: string = '') => str.replace(/^(-|--)/gi, '');
export const stripDashesSlashes = (str: string = '') =>
str.replace(/^[-\/]+/g, '');

export function getEnvAndArgs({
cliArgs = process.argv,
cliArgs = process.argv.slice(2),
envKeys = process.env,
}: ConfigInputsRaw = {}): ConfigInputsParsed {
debugLog('extractEnvArgs.cliArgs', cliArgs);
debugLog('extractEnvArgs.envKeys', envKeys);
// debugLog('extractEnvArgs.envKeys', envKeys);

let cliParsed: ReturnType<typeof minimist> | undefined = undefined;

Expand All @@ -75,7 +80,8 @@ export function getEnvAndArgs({
// path to node & the .js file we're executing.
cliArgs = process.argv.filter((arg, i) => !(i < 2 && isAbsolute(arg)));
cliParsed = minimist(cliArgs);
debugLog('cliParsed.minimist', cliArgs);
}

return { cliArgs: cliParsed, envKeys };
return { cliArgs: cliParsed!, envKeys };
}
4 changes: 4 additions & 0 deletions test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import minimist from 'minimist';
console.log('process.argv', process.argv);
console.log('minimist', minimist(process.argv.slice(2)))

4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@

},
"include": [
"examples/**/*.ts",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.d.ts"
"src/**/*.d.ts",
"examples/**/*.ts",
// "client/**/*.ts",
// "client/**/*.tsx",
// "client/**/*.d.ts",
Expand Down