Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate blueprints to ESLint v9 #26491

Merged
merged 3 commits into from
Jun 20, 2024
Merged
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
18 changes: 7 additions & 11 deletions generators/base-core/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,16 +172,14 @@ export default class CoreGenerator extends YeomanGenerator<JHipsterGeneratorOpti
...features,
});

let jhipsterOldVersion = null;
if (!this.options.help) {
/* Force config to use 'generator-jhipster' namespace. */
this._config = this._getStorage('generator-jhipster');

/* JHipster config using proxy mode used as a plain object instead of using get/set. */
this.jhipsterConfig = this.config.createProxy();

jhipsterOldVersion = this.jhipsterConfig.jhipsterVersion ?? null;
this.sharedData = this.createSharedData({ jhipsterOldVersion, help: this.options.help }) as any;
this.sharedData = this.createSharedData({ help: this.options.help }) as any;

/* Options parsing must be executed after forcing jhipster storage namespace and after sharedData have been populated */
this.parseJHipsterOptions(command.options);
Expand Down Expand Up @@ -1255,13 +1253,7 @@ templates: ${JSON.stringify(existingTemplates, null, 2)}`;
return this.options.sharedData.applications?.[this.calculateApplicationId(applicationFolder)];
}

private createSharedData({
jhipsterOldVersion,
help,
}: {
jhipsterOldVersion: string | null;
help?: boolean;
}): SharedData<BaseApplication> {
private createSharedData({ help }: { help?: boolean }): SharedData<BaseApplication> {
const applicationId = this.options.applicationId ?? this.calculateApplicationId(this.destinationPath());
if (this.options.sharedData.applications === undefined) {
this.options.sharedData.applications = {};
Expand All @@ -1272,6 +1264,10 @@ templates: ${JSON.stringify(existingTemplates, null, 2)}`;
}
const { ignoreNeedlesError } = this.options;

return new SharedData<BaseApplication>(sharedApplications[applicationId], { jhipsterOldVersion, ignoreNeedlesError });
return new SharedData<BaseApplication>(
sharedApplications[applicationId],
{ destinationPath: this.destinationPath(), memFs: this.env.sharedFs, log: this.log, logCwd: this.env.logCwd },
{ ignoreNeedlesError },
);
}
}
71 changes: 70 additions & 1 deletion generators/base/shared-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,37 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { existsSync, readFileSync, statSync } from 'fs';
import { rm } from 'fs/promises';
import { isAbsolute, join, relative } from 'path';
import { lt as semverLessThan } from 'semver';
import { defaults } from 'lodash-es';
import { MemFsEditor, create } from 'mem-fs-editor';
import { type BaseApplication } from '../base-application/types.js';
import { type Control } from './types.js';
import { GENERATOR_JHIPSTER } from '../generator-constants.js';

export default class SharedData<ApplicationType extends BaseApplication = BaseApplication> {
_storage: any;
_editor: MemFsEditor;
_log: any;
_logCwd: string;

constructor(storage, initialControl: Partial<Control> = {}) {
constructor(storage, { memFs, destinationPath, log, logCwd }, initialControl: Partial<Control> = {}) {
if (!storage) {
throw new Error('Storage is required for SharedData');
}

this._editor = create(memFs);
this._log = log;
this._logCwd = logCwd;

let jhipsterOldVersion;
if (existsSync(join(destinationPath, '.yo-rc.json'))) {
jhipsterOldVersion = JSON.parse(readFileSync(join(destinationPath, '.yo-rc.json'), 'utf-8').toString())[GENERATOR_JHIPSTER]
?.jhipsterVersion;
}

// Backward compatibility sharedData
this._storage = storage;

Expand All @@ -44,6 +64,55 @@ export default class SharedData<ApplicationType extends BaseApplication = BaseAp
nodeDependencies: {},
customizeTemplatePaths: [],
});

let customizeRemoveFiles: Array<(file: string) => string | undefined> = [];
const removeFiles = async (assertions: { removedInVersion?: string } | string, ...files: string[]) => {
if (typeof assertions === 'string') {
files = [assertions, ...files];
assertions = {};
}

for (const customize of customizeRemoveFiles) {
files = files.map(customize).filter(file => file) as string[];
}

const { removedInVersion } = assertions;
if (removedInVersion && jhipsterOldVersion && !semverLessThan(jhipsterOldVersion, removedInVersion)) {
return;
}

const absolutePaths = files.map(file => (isAbsolute(file) ? file : join(destinationPath, file)));
// Delete from memory fs to keep updated.
this._editor.delete(absolutePaths);
await Promise.all(
absolutePaths.map(async file => {
const relativePath = relative(logCwd, file);
try {
if (statSync(file).isFile()) {
this._log.info(`Removing legacy file ${relativePath}`);
await rm(file, { force: true });
}
} catch {
this._log.info(`Could not remove legacy file ${relativePath}`);
}
}),
);
};

defaults(this._storage.control, {
jhipsterOldVersion,
removeFiles,
customizeRemoveFiles: [],
cleanupFiles: async (cleanup: Record<string, string[]>) => {
await Promise.all(
Object.entries(cleanup).map(async ([version, files]) => {
await removeFiles({ removedInVersion: version }, ...files);
}),
);
},
});

customizeRemoveFiles = this._storage.control.customizeRemoveFiles;
}

getSource() {
Expand Down
3 changes: 3 additions & 0 deletions generators/base/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ export type Control = {
reproducibleLiquibaseTimestamp?: Date;
filterEntitiesForClient?: (entity: Entity[]) => Entity[];
filterEntitiesAndPropertiesForClient?: (entity: Entity[]) => Entity[];
customizeRemoveFiles: Array<(file: string) => string | undefined>;
removeFiles: (options: { removedInVersion: string } | string, ...files: string[]) => Promise<void>;
cleanupFiles: (cleanup: Record<string, string[]>) => Promise<void>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ exports[`generator - generate-blueprint with all option should match snapshot 1`
".blueprint/generate-sample/templates/samples/sample.jdl": {
"stateCleared": "modified",
},
".eslintrc.json": {
"stateCleared": "modified",
},
".github/workflows/generator.yml": {
"stateCleared": "modified",
},
Expand All @@ -32,6 +29,9 @@ exports[`generator - generate-blueprint with all option should match snapshot 1`
"cli/cli.cjs": {
"stateCleared": "modified",
},
"eslint.config.js": {
"stateCleared": "modified",
},
"generators/angular/command.js": {
"stateCleared": "modified",
},
Expand Down Expand Up @@ -886,9 +886,6 @@ exports[`generator - generate-blueprint with default config should write files a
".blueprint/generate-sample/templates/samples/sample.jdl": {
"stateCleared": "modified",
},
".eslintrc.json": {
"stateCleared": "modified",
},
".github/workflows/generator.yml": {
"stateCleared": "modified",
},
Expand All @@ -901,6 +898,9 @@ exports[`generator - generate-blueprint with default config should write files a
"cli/cli.cjs": {
"stateCleared": "modified",
},
"eslint.config.js": {
"stateCleared": "modified",
},
"package.json": {
"stateCleared": "modified",
},
Expand Down
2 changes: 1 addition & 1 deletion generators/generate-blueprint/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ export const files = {
{
condition: ctx => !ctx[LOCAL_BLUEPRINT_OPTION],
templates: [
'.eslintrc.json',
'.github/workflows/generator.yml',
'.prettierignore.jhi.blueprint',
'eslint.config.js',
'README.md',
'tsconfig.json',
'vitest.config.ts',
Expand Down
13 changes: 8 additions & 5 deletions generators/generate-blueprint/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export default class extends BaseGenerator {
}

get preparing() {
return {
return this.asPreparingTaskGroup({
prepareCommands() {
this.application.commands = [];
this.application.nodeVersion = NODE_VERSION;
Expand All @@ -195,15 +195,18 @@ export default class extends BaseGenerator {
this.application.cliName = cliName ?? `jhipster-${baseName}`;
}
},
};
});
}

get [BaseGenerator.PREPARING]() {
return this.delegateTasksToBlueprint(() => this.preparing);
}

get writing() {
return {
return this.asWritingTaskGroup({
async cleanup({ control }) {
await control.cleanupFiles({ '8.5.1': ['.eslintrc.json'] });
},
async writing() {
this.application.sampleWritten = this.jhipsterConfig.sampleWritten;
await this.writeFiles({
Expand Down Expand Up @@ -243,7 +246,7 @@ export default class extends BaseGenerator {
subGeneratorStorage.set(WRITTEN, true);
}
},
};
});
}

get [BaseGenerator.WRITING]() {
Expand Down Expand Up @@ -280,8 +283,8 @@ export default class extends BaseGenerator {
devDependencies: {
'ejs-lint': `${mainDependencies['ejs-lint']}`,
eslint: `${mainDependencies.eslint}`,
globals: `${mainDependencies.globals}`,
'eslint-config-prettier': `${mainDependencies['eslint-config-prettier']}`,
'eslint-plugin-import': `${mainDependencies['eslint-plugin-import']}`,
'eslint-plugin-prettier': `${mainDependencies['eslint-plugin-prettier']}`,
vitest: mainDependencies.vitest,
prettier: `${mainDependencies.prettier}`,
Expand Down
2 changes: 2 additions & 0 deletions generators/generate-blueprint/resources/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"dependencies": {
"eslint": "9.5.0",
"globals": "15.6.0",
"vitest": "1.6.0"
}
}
35 changes: 0 additions & 35 deletions generators/generate-blueprint/templates/.eslintrc.json.ejs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
-%>
<&_ if (!fragment.section) { -&>
# blueprint rules:
**/templates/**/
generators/**/templates/**/
<&_ } -&>
33 changes: 33 additions & 0 deletions generators/generate-blueprint/templates/eslint.config.js.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<%#
Copyright 2013-2024 the original author or authors from the JHipster project.

This file is part of the JHipster project, see https://www.jhipster.tech/
for more information.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
import globals from 'globals';
import prettierRecommended from 'eslint-plugin-prettier/recommended';
import jhipsterRecommended from 'generator-jhipster/eslint/recommended';

export default [
{
languageOptions: {
globals: {
...globals.node,
},
},
},
jhipsterRecommended,
prettierRecommended,
];
3 changes: 2 additions & 1 deletion generators/languages/generator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ describe(`generator - ${generator}`, () => {
nativeLanguage: 'in',
languages: ['in'],
baseName: 'jhipster',
}),
})
.commitFiles(),
);
it('should migrate in language to id', () => {
runResult.assertJsonFileContent('.yo-rc.json', {
Expand Down
Loading