Skip to content

Commit

Permalink
fix: assorted bugfixes and rule tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
SimeonC committed Jul 27, 2023
1 parent c58e32c commit 2aa346e
Show file tree
Hide file tree
Showing 14 changed files with 147 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export function buildBaseTypescript(
...rules,
...eslintTypescriptRules,
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-unsafe-enum-comparison': 'off',
'@typescript-eslint/prefer-nullish-coalescing': [
'error',
{
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-config/src/rules/namingConvention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export const namingRules: Linter.RulesRecord = {
format: ['PascalCase', 'camelCase'],
},
{
selector: ['classMethod', 'objectLiteralMethod'],
selector: ['function', 'classMethod', 'objectLiteralMethod'],
format: ['PascalCase', 'camelCase'],
},
{
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-config/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"rootDir": "src",
"outDir": "dist",
"paths": {},
"target": "es5",
"target": "es6",
"module": "commonjs"
},
"exclude": ["node_modules", "*.spec.ts"],
Expand Down
14 changes: 12 additions & 2 deletions packages/eslint-plugin/__tests__/forbiddenImports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ const ruleTester = new RuleTester({

const filename = './test_src/default.tsx';

ruleTester.run('forbiddenImports > lodash', rule, {
valid: [{ code: `import merge from 'lodash/merge';`, filename }],
ruleTester.run('forbiddenImports > valid other import formats', rule, {
valid: [
{ code: `import 'moment/locales/en';`, filename },
{ code: `import something from 'moment';`, filename },
{ code: `import { something } from 'moment';`, filename },
],
invalid: [
{
code: `import { merge } from 'lodash';`,
Expand All @@ -30,6 +34,12 @@ ruleTester.run('forbiddenImports > lodash', rule, {
},
],
},
],
});

ruleTester.run('forbiddenImports > lodash', rule, {
valid: [{ code: `import merge from 'lodash/merge';`, filename }],
invalid: [
{
code: `import { merge as _merge } from 'lodash';`,
output: `import _merge from 'lodash/merge';`,
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/forbiddenImports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export const forbiddenImports: TSESLint.RuleModule<typeof messageId> = {
defaultOptions: [],
create: (context) => ({
ImportDeclaration(node) {
if (node.specifiers.length === 0) return;
const importName = node.source.value || '';

const scope = context.getScope();
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"rootDir": "src",
"outDir": "dist",
"paths": {},
"target": "es5",
"target": "es6",
"module": "commonjs"
},
"exclude": ["node_modules", "*.spec.ts"],
Expand Down
8 changes: 6 additions & 2 deletions packages/nx/src/executors/quality/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ export default async function runExecutor(
const root = metadata.root || context.root;
try {
if (options.checkConfig) configCheck(root);
await packageCheck({ directory: root, shouldFix: options.fix });
return await lintRun(
const packageCheckResult = await packageCheck({
directory: root,
shouldFix: options.fix,
});
const lintResult = await lintRun(
{
...options,
noEslintrc: false,
Expand All @@ -36,6 +39,7 @@ export default async function runExecutor(
},
context,
);
return { success: lintResult.success && packageCheckResult.success };
} catch (e) {
console.log(e as Error);
return {
Expand Down
13 changes: 8 additions & 5 deletions packages/nx/src/executors/quality/package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,6 @@ export async function packageCheck({
directory: string;
shouldFix: boolean;
}) {
console.log(
chalk.cyan(
` ${icons.info} We recommend using \`npm-upgrade\` to manage dependencies.\n`,
),
);
const result = await processPackage({
packageDir: directory,
shouldWriteFile: shouldFix,
Expand All @@ -93,6 +88,14 @@ export async function packageCheck({
return Promise.resolve(appPackage);
},
});
if (result.success && result.error === 'no-file') {
return result;
}
console.log(
chalk.cyan(
` ${icons.info} We recommend using \`npm-upgrade\` to manage dependencies.\n`,
),
);
if (result.success) {
console.log(chalk.green(`${icons.check} Package dependencies validated`));
}
Expand Down
12 changes: 6 additions & 6 deletions packages/nx/src/generators/quality/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ function updateProjectConfig(tree: Tree, projectName: string) {
outputs: ['{options.outputFile}'],
options: {
lintFilePatterns: [
'{projectRoot}/src/**/*.ts',
'{projectRoot}/src/**/*.tsx',
'{projectRoot}/src/**/*.js',
'{projectRoot}/src/**/*.jsx',
'src/**/*.ts',
'src/**/*.tsx',
'src/**/*.js',
'src/**/*.jsx',
],
},
};
Expand Down Expand Up @@ -103,8 +103,8 @@ export async function qualityGenerator(
cwd: process.cwd(),
stdio: 'inherit',
});
await generateConfig(tree);
await generateIcons(tree);
await generateConfig(tree, schema);
await generateIcons(tree, schema);
await generateFileTypes(tree, schema);
await formatFiles(tree);
}
Expand Down
40 changes: 30 additions & 10 deletions packages/nx/src/generators/ts-carbon-icons/generator.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
import * as path from 'path';

import { Tree } from '@nx/devkit';
import { Tree, getProjects } from '@nx/devkit';
import {
detectInstalledVersion,
outputPrettyFile,
} from '@tablecheck/frontend-utils';

export async function tsCarbonIconsGenerator(tree: Tree) {
const projectRoot = tree.root;
export async function tsCarbonIconsGenerator(
tree: Tree,
schema: { project: string },
) {
const project = getProjects(tree).get(schema.project);
if (!project) {
console.warn(`Project ${schema.project} not found`);
return;
}
const projectRoot = path.join(tree.root, project.root);
try {
const carbonPackageJsonPath = detectInstalledVersion(
projectRoot,
'@carbon/icons-react',
'11',
);
let carbonPackageJsonPath: string;
try {
carbonPackageJsonPath = detectInstalledVersion(
projectRoot,
'@carbon/icons-react',
'11',
);
} catch (e) {
carbonPackageJsonPath = detectInstalledVersion(
tree.root,
'@carbon/icons-react',
'11',
);
}
// eslint-disable-next-line @typescript-eslint/no-var-requires -- await import throws segfault errors as this is common Js
const carbonIcons = require(path.join(
carbonPackageJsonPath,
Expand All @@ -22,7 +39,7 @@ export async function tsCarbonIconsGenerator(tree: Tree) {
const fileContent = `${Object.keys(carbonIcons).reduce(
(result, iconName) =>
`${result} declare export const ${iconName}: CarbonIcon;\n`,
`/* this file is generated during configuring typescript */
`// this file is generated with \`nx generate @tablecheck/nx:ts-carbon-icons ${schema.project}\`
declare module '@carbon/icons-react' {
declare export type CarbonIconSize = 16 | 20 | 24 | 32;
declare export type CarbonIcon = React.ForwardRefExoticComponent<
Expand All @@ -32,8 +49,11 @@ export async function tsCarbonIconsGenerator(tree: Tree) {
>;
`,
)}\n}`;
const definitionsPath = project.sourceRoot
? path.join(project.sourceRoot, 'definitions')
: 'definitions';
await outputPrettyFile(
path.join(projectRoot, 'src', 'definitions', 'carbonIcons.gen.d.ts'),
path.join(projectRoot, definitionsPath, 'carbonIcons.gen.d.ts'),
fileContent,
);
} catch (e) {
Expand Down
14 changes: 13 additions & 1 deletion packages/nx/src/generators/ts-carbon-icons/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,17 @@
"$id": "TsCarbonIcons",
"title": "Generate a typescript definition file for @carbon/icons",
"type": "object",
"properties": {}
"properties": {
"project": {
"type": "string",
"description": "The name of the project.",
"alias": "p",
"$default": {
"$source": "projectName"
},
"x-prompt": "What is the name of the project for the generator?",
"x-priority": "important"
}
},
"required": ["project"]
}
57 changes: 47 additions & 10 deletions packages/nx/src/generators/ts-node-config/generator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as path from 'path';

import { Tree } from '@nx/devkit';
import { Tree, getProjects } from '@nx/devkit';
import {
detectInstalledVersion,
outputPrettyFile,
Expand Down Expand Up @@ -34,14 +34,44 @@ function buildTypes(configValue: unknown): string {
}
}

export async function tsNodeConfigGenerator(tree: Tree) {
const projectRoot = tree.root;
function getConfigBasePath(root: string, projectRoot: string) {
const projectConfigPath = path.join(projectRoot, 'config');
if (fs.existsSync(projectConfigPath)) {
return projectConfigPath;
}
const rootConfigPath = path.join(root, 'config');
if (fs.existsSync(rootConfigPath)) {
return rootConfigPath;
}
throw new Error(
`No config directory found at ${projectConfigPath} or ${rootConfigPath} for project ${projectRoot}`,
);
}

export async function tsNodeConfigGenerator(
tree: Tree,
schema: { project: string },
) {
const project = getProjects(tree).get(schema.project);
if (!project) {
console.warn(`Project ${schema.project} not found`);
return;
}
const projectRoot = path.join(tree.root, project.root);
try {
detectInstalledVersion(projectRoot, 'config', '*');
try {
detectInstalledVersion(projectRoot, 'config', '*');
} catch (e) {
detectInstalledVersion(tree.root, 'config', '*');
}

const defaultConfigFilePath = path.join(projectRoot, 'config/default.json');
const devConfigFilePath = path.join(projectRoot, 'config/development.json');
if (!fs.existsSync(defaultConfigFilePath)) return;
const configBasePath = getConfigBasePath(tree.root, projectRoot);
const defaultConfigFilePath = path.join(configBasePath, 'default.json');
const devConfigFilePath = path.join(configBasePath, 'development.json');
if (!fs.existsSync(defaultConfigFilePath)) {
console.info('No default config found, skipping config generation');
return;
}

const defaultConfigJson = fs.readJsonSync(defaultConfigFilePath) as Record<
string,
Expand All @@ -50,8 +80,10 @@ export async function tsNodeConfigGenerator(tree: Tree) {
const devConfigJson = (
fs.existsSync(devConfigFilePath) ? fs.readJSONSync(devConfigFilePath) : {}
) as Record<string, unknown>;
const fileContent = `declare module '@tablecheck/scripts' {
// this file is autobuilt with \`nx generate @tablecheck/nx:ts-node-config\`, all changes here will be overwritten
const fileContent = `declare module 'config' {
// this file is generated with \`nx generate @tablecheck/nx:ts-node-config ${
schema.project
}\`
interface DefaultConfig ${buildTypes(defaultConfigJson)}
export interface DevelopmentConfig extends DefaultConfig ${buildTypes(
devConfigJson,
Expand All @@ -60,9 +92,14 @@ export async function tsNodeConfigGenerator(tree: Tree) {
global {
const CONFIG: DevelopmentConfig;
}
const config: DevelopmentConfig;
export default config;
}`;
const definitionsPath = project.sourceRoot
? path.join(project.sourceRoot, 'definitions')
: 'definitions';
await outputPrettyFile(
path.join(projectRoot, 'src', 'definitions', 'nodeConfig.gen.d.ts'),
path.join(projectRoot, definitionsPath, 'nodeConfig.gen.d.ts'),
fileContent,
);
} catch (e) {
Expand Down
14 changes: 13 additions & 1 deletion packages/nx/src/generators/ts-node-config/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,17 @@
"$id": "TsNodeConfig",
"title": "Generate a typescript definition file for node-config default.json",
"type": "object",
"properties": {}
"properties": {
"project": {
"type": "string",
"description": "The name of the project.",
"alias": "p",
"$default": {
"$source": "projectName"
},
"x-prompt": "What is the name of the project for the generator?",
"x-priority": "important"
}
},
"required": ["project"]
}
7 changes: 7 additions & 0 deletions packages/utils/src/packageJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export function getPackageJson(directory = process.cwd()) {
return fs.readJsonSync(path.join(directory, 'package.json')) as PackageJson;
}

export function hasPackageJson(directory = process.cwd()) {
return fs.existsSync(path.join(directory, 'package.json'));
}

export function detectInstalledVersion(
cwd: string,
packageName: string,
Expand Down Expand Up @@ -153,6 +157,9 @@ export async function processPackage({
shouldWriteFile: boolean;
}) {
try {
if (!hasPackageJson(packageDir)) {
return { success: true, error: 'no-file' };
}
const packageContent = getPackageJson(packageDir);
let didSucceed = true;
let processingError: Error | undefined;
Expand Down

0 comments on commit 2aa346e

Please sign in to comment.