Skip to content

Commit

Permalink
fix: optimize loadParserOpts
Browse files Browse the repository at this point in the history
  • Loading branch information
armano2 committed Jan 30, 2021
1 parent f1bf2d2 commit 3a7ec9d
Showing 1 changed file with 14 additions and 20 deletions.
34 changes: 14 additions & 20 deletions @commitlint/load/src/utils/load-parser-opts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,10 @@ function isObjectLike(obj: unknown): obj is Record<string, unknown> {
return Boolean(obj) && typeof obj === 'object'; // typeof null === 'object'
}

function isPromiseLike(obj: unknown): obj is Promise<unknown> {
return isObjectLike(obj) && typeof (obj as any).then === 'function';
}

function isParserOptsFunction<T extends ParserPreset>(
obj: T
): obj is T & {
parserOpts: (
cb: (_: never, parserOpts: Record<string, unknown>) => unknown
) => Record<string, unknown> | undefined;
parserOpts: (...args: any[]) => any;
} {
return typeof obj.parserOpts === 'function';
}
Expand All @@ -27,9 +21,16 @@ export async function loadParserOpts(
// Await for the module, loaded with require
const parser = await pendingParser;

// Await parser opts if applicable
if (isPromiseLike(parser.parserOpts)) {
parser.parserOpts = ((await parser.parserOpts) as any).parserOpts;
// exit early, no opts to resolve
if (!parser.parserOpts) {
return parser;
}

// Pull nested parserOpts, might happen if overwritten with a module in main config
if (typeof parser.parserOpts === 'object') {
// Await parser opts if applicable
const opts = await parser.parserOpts;
parser.parserOpts = isObjectLike(opts) ? opts.parserOpts : undefined;
return parser;
}

Expand All @@ -40,10 +41,10 @@ export async function loadParserOpts(
parser.name.startsWith('conventional-changelog-')
) {
return new Promise((resolve) => {
const result = parser.parserOpts((_: never, opts) => {
const result = parser.parserOpts((_: never, opts: any) => {
resolve({
...parser,
parserOpts: opts.parserOpts,
parserOpts: opts?.parserOpts,
});
});

Expand All @@ -53,20 +54,13 @@ export async function loadParserOpts(
Promise.resolve(result).then((opts) => {
resolve({
...parser,
parserOpts: opts.parserOpts,
parserOpts: opts?.parserOpts,
});
});
}
return;
});
}

// Pull nested parserOpts, might happen if overwritten with a module in main config
if (
isObjectLike(parser.parserOpts) &&
typeof parser.parserOpts.parserOpts === 'object'
) {
parser.parserOpts = parser.parserOpts.parserOpts;
}
return parser;
}

0 comments on commit 3a7ec9d

Please sign in to comment.