Skip to content

Commit

Permalink
fix(nx): generators correctly respect “dry-run”
Browse files Browse the repository at this point in the history
Without this change we would write the files even in dry-mode. This meant that the “preview” of the generate UI would change files!!
  • Loading branch information
SimeonC committed Dec 15, 2023
1 parent 8f9c849 commit 115e91e
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 41 deletions.
16 changes: 14 additions & 2 deletions packages/nx/src/generators/quality/eslintConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Tree } from '@nx/devkit';

import { getNxProjectRoot } from '../../utils/nx';
import { outputPrettyFile } from '../../utils/prettier';
import { createTempFiles } from '../../utils/tempFiles';

function getExtends(
eslintType:
Expand Down Expand Up @@ -58,7 +59,13 @@ export function generateEslintConfig(
if (schema.includeStorybook) {
ruleExtensions.push('@tablecheck/eslint-config/storybook');
}
const fileContent = `

const generateFiles = createTempFiles({
tree,
projectRoot,
cacheLocation: __dirname,
createFiles: (templatePath) => {
const fileContent = `
module.exports = {
extends: [${ruleExtensions.join(',')}],
parserOptions: {
Expand All @@ -80,5 +87,10 @@ module.exports = {
rules: {},
};
`;
outputPrettyFile(path.join(projectRoot, '.eslintrc.cjs'), fileContent);
outputPrettyFile(path.join(templatePath, '.eslintrc.cjs'), fileContent);
},
});
generateFiles({
overwriteExisting: true,
});
}
6 changes: 1 addition & 5 deletions packages/nx/src/generators/quality/generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { execSync } from 'child_process';
import * as path from 'path';

import {
Expand Down Expand Up @@ -58,14 +57,11 @@ export async function qualityGenerator(
{},
);
generateEslintConfig(tree, schema);
execSync('npx husky install', {
cwd: process.cwd(),
stdio: 'inherit',
});
generateConfig(tree, schema);
generateIcons(tree, schema);
await generateFileTypes(tree, schema);
await formatFiles(tree);
console.log('Run `npx husky install` to install git hooks');
}

export default qualityGenerator;
66 changes: 45 additions & 21 deletions packages/nx/src/generators/ts-carbon-icons/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Tree } from '@nx/devkit';
import { getNxProjectRoot } from '../../utils/nx';
import { detectInstalledVersion } from '../../utils/packageJson';
import { outputPrettyFile } from '../../utils/prettier';
import { createTempFiles } from '../../utils/tempFiles';

export function tsCarbonIconsGenerator(
tree: Tree,
Expand All @@ -29,27 +30,50 @@ export function tsCarbonIconsGenerator(
'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, '..'),
) as Record<string, never>;
const fileContent = `${Object.keys(carbonIcons).reduce(
(result, iconName) =>
`${result} declare export const ${iconName}: CarbonIcon;\n`,
`// 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<
{
size?: CarbonIconSize | \`\${CarbonIconSize}\` | (string & {}) | (number & {});
} & React.RefAttributes<SVGSVGElement>
>;
`,
)}\n}`;
outputPrettyFile(
path.join(projectSourceRoot, 'definitions', 'carbonIcons.gen.d.ts'),
fileContent,
);
const carbonVersion =
// eslint-disable-next-line @typescript-eslint/no-var-requires -- await import throws segfault errors as this is common Js
(require(carbonPackageJsonPath) as { version: string }).version;
const cacheContent = `@carbon/icons-react@${carbonVersion}\n${projectSourceRoot}`;
const relativeSourcePath = path.relative(projectRoot, projectSourceRoot);

const generateFiles = createTempFiles({
tree,
projectRoot,
cacheContent,
cacheLocation: __dirname,
createFiles: (templatePath) => {
// 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, '..'),
) as Record<string, never>;
outputPrettyFile(
path.join(
templatePath,
relativeSourcePath,
'definitions',
'carbonIcons.gen.d.ts',
),
`// 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<
{
size?: CarbonIconSize | \`\${CarbonIconSize}\` | (string & {}) | (number & {});
} & React.RefAttributes<SVGSVGElement>
>;
${Object.keys(carbonIcons)
.map((iconName) => ` declare export const ${iconName}: CarbonIcon;`)
.join('\n')}
}`,
);
},
});

generateFiles({
overwriteExisting: true,
});
} catch (e) {
console.warn(e);
}
Expand Down
42 changes: 29 additions & 13 deletions packages/nx/src/generators/ts-node-config/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import uniq from 'lodash/uniq';
import { getNxProjectRoot } from '../../utils/nx';
import { detectInstalledVersion } from '../../utils/packageJson';
import { outputPrettyFile } from '../../utils/prettier';
import { createTempFiles } from '../../utils/tempFiles';

function buildTypes(configValue: unknown): string {
if (Array.isArray(configValue))
Expand Down Expand Up @@ -66,15 +67,21 @@ export function tsNodeConfigGenerator(tree: Tree, schema: { project: string }) {
console.info('No default config found, skipping config generation');
return;
}

const defaultConfigJson = fs.readJsonSync(defaultConfigFilePath) as Record<
string,
unknown
>;
const devConfigJson = (
fs.existsSync(devConfigFilePath) ? fs.readJSONSync(devConfigFilePath) : {}
) as Record<string, unknown>;
const fileContent = `declare module 'config' {
const relativeSourcePath = path.relative(projectRoot, projectSourceRoot);
const generateFiles = createTempFiles({
tree,
projectRoot,
cacheLocation: __dirname,
createFiles: (templatePath) => {
const defaultConfigJson = fs.readJsonSync(
defaultConfigFilePath,
) as Record<string, unknown>;
const devConfigJson = (
fs.existsSync(devConfigFilePath)
? fs.readJSONSync(devConfigFilePath)
: {}
) as Record<string, unknown>;
const fileContent = `declare module 'config' {
// this file is generated with \`nx generate @tablecheck/nx:ts-node-config ${
schema.project
}\`
Expand All @@ -89,10 +96,19 @@ export function tsNodeConfigGenerator(tree: Tree, schema: { project: string }) {
const config: DevelopmentConfig;
export default config;
}`;
outputPrettyFile(
path.join(projectSourceRoot, 'definitions', 'nodeConfig.gen.d.ts'),
fileContent,
);
outputPrettyFile(
path.join(
templatePath,
relativeSourcePath,
'definitions',
'nodeConfig.gen.d.ts',
),
fileContent,
);
},
});

generateFiles({ overwriteExisting: true });
} catch (e) {
console.warn(e);
}
Expand Down
44 changes: 44 additions & 0 deletions packages/nx/src/utils/tempFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import * as path from 'path';

import { Tree, generateFiles } from '@nx/devkit';
import fs from 'fs-extra';

type GenerateFilesFunction = (
substitutions: Parameters<typeof generateFiles>[3],
) => void;

export function createTempFiles({
tree,
projectRoot,
cacheContent,
cacheLocation,
createFiles,
}: {
tree: Tree;
projectRoot: string;
cacheContent?: string;
cacheLocation: string;
createFiles: (templatePath: string) => void;
}): GenerateFilesFunction {
const cachePath = path.join(cacheLocation, '.cache');
const templatePath = path.join(cacheLocation, 'files');
const generateFunction: GenerateFilesFunction = (substitutions) =>
generateFiles(
tree,
templatePath,
path.relative(tree.root, projectRoot),
substitutions,
);
if (cacheContent) {
if (fs.existsSync(cachePath)) {
const cache = fs.readFileSync(cachePath, 'utf-8');
if (cache === cacheContent) {
return generateFunction;
}
}
fs.writeFileSync(cachePath, cacheContent);
}
fs.emptyDirSync(templatePath);
createFiles(templatePath);
return generateFunction;
}

0 comments on commit 115e91e

Please sign in to comment.