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

adjusts to generate-sample #24193

Merged
merged 2 commits into from
Nov 12, 2023
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
6 changes: 5 additions & 1 deletion .blueprint/generate-sample/generator.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { extname } from 'path';
import { transform } from '@yeoman/transform';
import BaseGenerator from '../../generators/base/index.mjs';
import command from './command.mjs';
import { generateSample } from './support/generate-sample.js';
Expand Down Expand Up @@ -48,7 +49,10 @@ export default class extends BaseGenerator {
});

// Cleanup mem-fs files. Reload them from disk.
await this.pipeline({ refresh: true, filter: () => true, pendingFiles: false });
await this.pipeline(
{ refresh: true, pendingFiles: false },
transform(() => {}),
);

let generatorOptions = {};
if (sample.sample.workspaces && sample.sample.workspaces !== 'false') {
Expand Down
1 change: 1 addition & 0 deletions generators/base-application/support/index.mts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ export { default as prepareField } from './prepare-field.mjs';
export * from './prepare-field.mjs';
export { default as prepareRelationship } from './prepare-relationship.mjs';
export * from './relationship.mjs';
export * from './update-application-entities-transform.mjs';
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { readdir } from 'fs/promises';
import { loadFile } from 'mem-fs';
import type { MemFsEditorFile } from 'mem-fs-editor';
import { Minimatch } from 'minimatch';
import { transform } from 'p-transform';
import { basename, join } from 'path';
import { GENERATOR_JHIPSTER } from '../../generator-constants.mjs';

export const updateApplicationEntitiesTransform = ({
destinationPath,
throwOnMissingConfig = true,
}: {
destinationPath: string;
throwOnMissingConfig?: boolean;
}) => {
let yoRcFileInMemory: MemFsEditorFile | undefined;
const entities: string[] = [];
const yoRcFilePath = join(destinationPath, '.yo-rc.json');
const entitiesMatcher = new Minimatch(`${destinationPath}/.jhipster/*.json`);

return transform<MemFsEditorFile>(
file => {
if (file.path === yoRcFilePath) {
yoRcFileInMemory = file;
return undefined;
}
if (entitiesMatcher.match(file.path)) {
entities.push(basename(file.path).replace('.json', ''));
}
return file;
},
async function () {
try {
entities.push(...(await readdir(join(destinationPath, '.jhipster'))).map(file => file.replace('.json', '')));
} catch {
// Directory does not exist
}
if (entities.length > 0) {
// The mem-fs instance requires another file instance to emit a change event
const yoRcFile: MemFsEditorFile = loadFile(yoRcFilePath) as any;
// Prefer in-memory file if it exists
const yoRcFileContents = yoRcFileInMemory?.contents ?? yoRcFile.contents;
if (yoRcFileContents) {
const contents = JSON.parse(yoRcFileContents.toString());
if (contents[GENERATOR_JHIPSTER]) {
contents[GENERATOR_JHIPSTER].entities = [...new Set([...(contents[GENERATOR_JHIPSTER].entities ?? []), ...entities])];
yoRcFile.contents = Buffer.from(JSON.stringify(contents, null, 2));
yoRcFileInMemory = yoRcFile;
} else if (throwOnMissingConfig) {
throw new Error(`File ${yoRcFile!.path} is not a valid JHipster configuration file`);
}
} else if (throwOnMissingConfig) {
throw new Error(`File ${yoRcFile!.path} has no contents`);
}
}
if (yoRcFileInMemory) {
this.push(yoRcFileInMemory);
}
},
);
};
48 changes: 22 additions & 26 deletions generators/jdl/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import statistics from '../statistics.mjs';
import { addApplicationIndex, allNewApplications, customizeForMicroservices } from './internal/index.mjs';
import { mergeYoRcContent } from '../../jdl/index.js';
import { normalizeBlueprintName } from '../base/internal/blueprint.mjs';
import { updateApplicationEntitiesTransform } from '../base-application/support/update-application-entities-transform.mjs';

const { upperFirst } = _;

Expand Down Expand Up @@ -102,8 +103,11 @@ export default class JdlGenerator extends BaseGenerator {
return this.delegateTasksToBlueprint(() => this.initializing);
}

get loading() {
return this.asLoadingTaskGroup({
get configuring() {
return this.asConfiguringTaskGroup({
insight() {
statistics.sendSubGenEvent('generator', 'import-jdl');
},
async downloadJdlFiles() {
if (this.jdlFiles) {
this.jdlFiles = await Promise.all(
Expand All @@ -130,18 +134,6 @@ export default class JdlGenerator extends BaseGenerator {
this.jdlContents.push(this.readDestination(jdlFile)?.toString() ?? '');
}
},
});
}

get [BaseGenerator.LOADING]() {
return this.delegateTasksToBlueprint(() => this.loading);
}

get default() {
return this.asDefaultTaskGroup({
insight() {
statistics.sendSubGenEvent('generator', 'import-jdl');
},
async parseJDL() {
const configuration = {
applicationName: this.options.baseName ?? (this.existingProject ? this.jhipsterConfig.baseName : undefined),
Expand All @@ -167,6 +159,15 @@ export default class JdlGenerator extends BaseGenerator {
...applicationsWithEntities.filter((app: ApplicationWithEntitiesAndPath) => app.config.applicationType !== 'gateway'),
];
},
configure() {
const nrApplications = this.applications.length;
const allNew = allNewApplications(this.applications);
const interactiveFallback = !allNew;

this.interactive = this.interactive ?? interactiveFallback;
this.force = this.options.force ?? (nrApplications > 0 && allNew) ? true : undefined;
this.reproducible = allNew;
},
customizeApplication() {
for (const app of this.applications) {
app.config.entities = app.entities.map(entity => entity.name);
Expand All @@ -182,18 +183,13 @@ export default class JdlGenerator extends BaseGenerator {
addApplicationIndex(this.applications);
customizeForMicroservices(this.exportedApplicationsWithEntities);
},
configure() {
const nrApplications = this.applications.length;
const allNew = allNewApplications(this.applications);
const interactiveFallback = !allNew;

this.interactive = this.interactive ?? interactiveFallback;
this.force = this.options.force ?? (nrApplications > 0 && allNew) ? true : undefined;
this.reproducible = allNew;
},
generateJson() {
async generateJson() {
if (this.applications.length === 0) {
this.writeConfig({ entities: this.exportedEntities });
await this.env.sharedFs.pipeline(
{ refresh: true },
updateApplicationEntitiesTransform({ destinationPath: this.destinationPath(), throwOnMissingConfig: false }),
);
} else {
this.writeConfig(...this.applications.map(app => (this.ignoreApplication ? { ...app, config: undefined } : app)));
}
Expand Down Expand Up @@ -239,8 +235,8 @@ export default class JdlGenerator extends BaseGenerator {
});
}

get [BaseGenerator.DEFAULT]() {
return this.delegateTasksToBlueprint(() => this.default);
get [BaseGenerator.CONFIGURING]() {
return this.delegateTasksToBlueprint(() => this.configuring);
}

get end() {
Expand Down
33 changes: 24 additions & 9 deletions generators/jdl/generator.spec.mts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ describe(`generator - ${generator}`, () => {
});

it('should write expected files', () => {
expect(runResult.getSnapshot()).toEqual({ '.yo-rc.json': expect.any(Object), '.jhipster/Foo.json': expect.any(Object) });
expect(runResult.getSnapshot()).toEqual({
'.jhipster/Foo.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});

Expand All @@ -127,7 +129,9 @@ describe(`generator - ${generator}`, () => {
});

it('should write expected files', () => {
expect(runResult.getSnapshot()).toEqual({ '.yo-rc.json': expect.any(Object), '.jhipster/Foo.json': expect.any(Object) });
expect(runResult.getSnapshot()).toEqual({
'.jhipster/Foo.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});
});
Expand Down Expand Up @@ -312,7 +316,9 @@ describe(`generator - ${generator}`, () => {
});

it('should write expected files', () => {
expect(runResult.getSnapshot()).toEqual({ '.yo-rc.json': expect.any(Object), '.jhipster/Foo.json': expect.any(Object) });
expect(runResult.getSnapshot()).toEqual({
'.jhipster/Foo.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});

Expand All @@ -327,7 +333,9 @@ describe(`generator - ${generator}`, () => {
});

it('should match files snapshot', () => {
expect(runResult.getSnapshot()).toEqual({ '.yo-rc.json': expect.any(Object), '.jhipster/Foo.json': expect.any(Object) });
expect(runResult.getSnapshot()).toEqual({
'.jhipster/Foo.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});
});
Expand All @@ -344,7 +352,9 @@ describe(`generator - ${generator}`, () => {
});

it('should write expected files', () => {
expect(runResult.getSnapshot()).toEqual({ '.yo-rc.json': expect.any(Object) });
expect(runResult.getSnapshot()).toEqual({
'.yo-rc.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});
});
Expand All @@ -361,7 +371,10 @@ describe(`generator - ${generator}`, () => {
});

it('should write expected files', () => {
expect(runResult.getSnapshot()).toEqual({ '.yo-rc.json': expect.any(Object), '.jhipster/Foo.json': expect.any(Object) });
expect(runResult.getSnapshot()).toEqual({
'.yo-rc.json': expect.objectContaining({ contents: expect.stringMatching(/"entities": \[\s*"Foo"\s*]/g) }),
'.jhipster/Foo.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});

Expand All @@ -377,7 +390,9 @@ describe(`generator - ${generator}`, () => {
});

it('should write entity files', () => {
expect(runResult.getSnapshot()).toEqual({ '.jhipster/Foo.json': expect.any(Object) });
expect(runResult.getSnapshot()).toEqual({
'.jhipster/Foo.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});
});
Expand Down Expand Up @@ -411,8 +426,8 @@ describe(`generator - ${generator}`, () => {

it('should write expected files', () => {
expect(runResult.getSnapshot()).toEqual({
'jhipster/.jhipster/Foo.json': expect.any(Object),
'jhipster2/.jhipster/Bar.json': expect.any(Object),
'jhipster/.jhipster/Foo.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
'jhipster2/.jhipster/Bar.json': expect.objectContaining({ contents: expect.any(String), stateCleared: 'modified' }),
});
});
});
Expand Down