Skip to content

Commit

Permalink
fix(executor): fix resolving custom formatters
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillip9587 committed Feb 9, 2024
1 parent ecd77ba commit 4112d41
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 29 deletions.
2 changes: 2 additions & 0 deletions nx-stylelint/src/executors/lint/executor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ describe('nx-stylelint:lint executor', () => {
logger.error = jest.fn();
logger.info = jest.fn();

console.warn = jest.fn();

mockResult = defaultMockResult;
});

Expand Down
13 changes: 6 additions & 7 deletions nx-stylelint/src/executors/lint/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import type { ExecutorContext } from '@nx/devkit';
import { logger } from '@nx/devkit';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import type { LinterResult } from 'stylelint';
import { loadFormatter } from '../../utils/formatter';
import { loadStylelint } from '../../utils/stylelint';
import type { Formatter, FormatterType, LinterResult } from 'stylelint';
import { importFormatter } from '../../utils/formatter';
import type { LintExecutorSchema } from './schema';

export async function lintExecutor(
Expand All @@ -15,9 +14,9 @@ export async function lintExecutor(

let stylelint: typeof import('stylelint');
try {
stylelint = await loadStylelint();
stylelint = await import('stylelint');
} catch (error) {
logger.error(error instanceof Error ? error.message : error);
logger.error('Unable to find Stylelint. Please ensure Stylelint is installed.');
return { success: false };
}

Expand All @@ -30,9 +29,9 @@ export async function lintExecutor(

if (!options.silent) logger.info(`\nLinting Styles "${projectName}"...`);

let resolvedFormatter;
let resolvedFormatter: FormatterType | Formatter;
try {
resolvedFormatter = loadFormatter(options.formatter, context.cwd);
resolvedFormatter = await importFormatter(options.formatter);
} catch (err) {
logger.error(`Invalid Formatter. More Details: \n`);
throw err;
Expand Down
2 changes: 2 additions & 0 deletions nx-stylelint/src/generators/configuration/generator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ describe('nx-stylelint:configuration generator', () => {

beforeAll(async () => {
logger.info = jest.fn();

console.warn = jest.fn();
});

beforeEach(async () => {
Expand Down
2 changes: 2 additions & 0 deletions nx-stylelint/src/generators/init/generator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ describe('nx-stylelint:init generator', () => {

beforeEach(() => {
tree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });

console.warn = jest.fn();
});

it('should add dependencies and create recommended root configuration', async () => {
Expand Down
10 changes: 10 additions & 0 deletions nx-stylelint/src/utils/formatter.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { formatters } from 'stylelint';
import { importFormatter } from './formatter';

describe('importFormatter()', () => {
it('should return stylelint core formatter key when given', async () => {
for (const formatterKey of Object.keys(formatters)) {
expect(await importFormatter(formatterKey)).toStrictEqual(formatterKey);
}
});
});
25 changes: 10 additions & 15 deletions nx-stylelint/src/utils/formatter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { join } from 'node:path';
import { existsSync } from 'node:fs';
import { isAbsolute, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import type { Formatter, FormatterType } from 'stylelint';
import { formatters } from 'stylelint';

Expand All @@ -10,21 +12,14 @@ export function isCoreFormatter(formatter: unknown): formatter is FormatterType
return formatterKeys.includes(formatter);
}

const npmPackageRegex = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;

export function loadFormatter(formatter: unknown, cwd: string): FormatterType | Formatter {
export async function importFormatter(formatter: unknown): Promise<FormatterType | Formatter> {
if (!formatter || typeof formatter !== 'string') throw new Error('Formatter must be a string!');
const normalizedFormatter: string = formatter.trim().replace(/\\/gu, '/');
if (isCoreFormatter(normalizedFormatter)) return normalizedFormatter;
if (isCoreFormatter(formatter)) return formatter;

const isNpmPackage = npmPackageRegex.test(normalizedFormatter);
let moduleOrFilePath = formatter;
if (existsSync(moduleOrFilePath)) moduleOrFilePath = resolve(moduleOrFilePath);

try {
return require(isNpmPackage ? normalizedFormatter : join(cwd, normalizedFormatter));
} catch (err) {
if (isNpmPackage && !normalizedFormatter.includes('@')) {
return require(join(cwd, normalizedFormatter));
}
throw err;
}
return await import(
isAbsolute(moduleOrFilePath) ? pathToFileURL(moduleOrFilePath).toString() : moduleOrFilePath
).then((m) => m.default);
}
7 changes: 0 additions & 7 deletions nx-stylelint/src/utils/stylelint.ts

This file was deleted.

0 comments on commit 4112d41

Please sign in to comment.