Skip to content

Commit

Permalink
add removeFiles to control
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima committed Jun 20, 2024
1 parent 18d68ab commit afa9b0b
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 17 deletions.
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>;
};
11 changes: 7 additions & 4 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
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

0 comments on commit afa9b0b

Please sign in to comment.