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

More cleanups #23359

Merged
merged 8 commits into from
Aug 30, 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: 3 additions & 3 deletions cli/jhipster-command.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,10 @@ export default class JHipsterCommand extends Command {
cmdString = `-${optionDefinition.alias}, `;
}
cmdString = `${cmdString}${longOption}`;
if (optionDefinition.type === String) {
cmdString = optionDefinition.required !== false ? `${cmdString} <value>` : `${cmdString} [value]`;
} else if (optionDefinition.type === Array) {
if (optionDefinition.type === Array) {
cmdString = optionDefinition.required !== false ? `${cmdString} <value...>` : `${cmdString} [value...]`;
} else if (optionDefinition.type && optionDefinition.type !== Boolean) {
cmdString = optionDefinition.required !== false ? `${cmdString} <value>` : `${cmdString} [value]`;
}
const option = new Option(cmdString, optionDefinition.description + additionalDescription)
.default(optionDefinition.default)
Expand Down
3 changes: 1 addition & 2 deletions generators/app/__snapshots__/generator.spec.mts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ Options:
--search-engine <value> Provide search engine for the application when skipping server side generation
--blueprint <value> DEPRECATED: Specify a generator blueprint to use for the sub generators
--blueprints <value> A comma separated list of one or more generator blueprints to use for the sub generators, e.g. --blueprints kotlin,vuejs
--creation-timestamp <value> Project creation timestamp (used for reproducible builds)
--incremental-changelog Creates incremental database changelogs
--recreate-initial-changelog Recreate the initial database changelog based on the current config
--legacy-db-names Generate database names with jhipster 6 compatibility.
Expand All @@ -56,7 +55,7 @@ Options:
--project-version <value> project version to use, this option is not persisted (env: JHI_PROJECT_VERSION)
--message-broker <value> message broker
--with-generated-flag Add a GeneratedByJHipster annotation to all generated java classes and interfaces
--prettier-tab-width Default tab width for prettier
--prettier-tab-width <value> Default tab width for prettier
--with-admin-ui Generate administrative user interface
--skip-git Skip git repository initialization
--monorepository Use monorepository
Expand Down
10 changes: 2 additions & 8 deletions generators/app/generator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import chalk from 'chalk';
import _ from 'lodash';

import BaseApplicationGenerator from '../base-application/index.mjs';
import { checkNode } from './support/index.mjs';
import { checkNode, loadStoredAppOptions } from './support/index.mjs';
import cleanupOldFilesTask from './cleanup.mjs';
import prompts from './prompts.mjs';
import statistics from '../statistics.mjs';
Expand Down Expand Up @@ -166,12 +166,6 @@ export default class JHipsterAppGenerator extends BaseApplicationGenerator {
type: String,
});

// This adds support for a `--creation-timestamp` flag which can be used create reproducible builds
this.option('creation-timestamp', {
description: 'Project creation timestamp (used for reproducible builds)',
type: String,
});

this.option('incremental-changelog', {
description: 'Creates incremental database changelogs',
type: Boolean,
Expand Down Expand Up @@ -268,7 +262,7 @@ export default class JHipsterAppGenerator extends BaseApplicationGenerator {
}

async beforeQueue() {
this.loadStoredAppOptions();
loadStoredAppOptions.call(this);
this.loadRuntimeOptions();

await this.dependsOnJHipster(GENERATOR_BOOTSTRAP_APPLICATION_BASE);
Expand Down
21 changes: 6 additions & 15 deletions generators/app/support/config.mts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import _ from 'lodash';
import { NODE_VERSION } from '../../generator-constants.mjs';
import { applicationTypes, authenticationTypes, databaseTypes, testFrameworkTypes } from '../../../jdl/index.js';
import { getHipster, parseCreationTimestamp, upperFirstCamelCase } from '../../base/support/index.mjs';
import { getHipster, upperFirstCamelCase } from '../../base/support/index.mjs';
import { getDBTypeFromDBValue } from '../../server/support/index.mjs';
import detectLanguage from '../../languages/support/detect-language.mjs';

Expand All @@ -14,7 +14,10 @@ const { CASSANDRA, NO: NO_DATABASE } = databaseTypes;
* Load common options to be stored.
* @deprecated
*/
export const loadStoredAppOptions = ({ options, sharedData, jhipsterConfig, log }) => {
export function loadStoredAppOptions(
this: any,
{ options = this.options, sharedData = this.sharedData, jhipsterConfig = this.jhipsterConfig, log = this.log } = {},
) {
// Parse options only once.
if (sharedData.get('optionsParsed')) return;
sharedData.set('optionsParsed', true);
Expand Down Expand Up @@ -121,18 +124,6 @@ export const loadStoredAppOptions = ({ options, sharedData, jhipsterConfig, log
}
}

if (options.creationTimestamp) {
const creationTimestamp = parseCreationTimestamp(options.creationTimestamp);
if (creationTimestamp) {
sharedData.get('configOptions').creationTimestamp = creationTimestamp;
if (jhipsterConfig.creationTimestamp === undefined) {
jhipsterConfig.creationTimestamp = creationTimestamp;
}
} else {
log?.warn(`Error parsing creationTimestamp ${options.creationTimestamp}.`);
}
}

if (options.pkType) {
jhipsterConfig.pkType = options.pkType;
}
Expand Down Expand Up @@ -167,7 +158,7 @@ export const loadStoredAppOptions = ({ options, sharedData, jhipsterConfig, log
options.skipInstall = true;
}
}
};
}

/**
* Load app configs into application.
Expand Down
3 changes: 2 additions & 1 deletion generators/base-application/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type { BaseApplication, CommonClientServerApplication } from './types.mjs
import { getEntitiesFromDir } from './support/index.mjs';
import { SpringBootSourceType } from '../server/types.mjs';
import { ClientSourceType } from '../client/types.mjs';
import { LanguageSourceType } from '../languages/types.js';

const { upperFirst } = _;

Expand Down Expand Up @@ -63,7 +64,7 @@ const {

const asPriority = BaseGenerator.asPriority;

export type BaseApplicationSource = Record<string, (...args: any[]) => any> & SpringBootSourceType & ClientSourceType;
export type BaseApplicationSource = Record<string, (...args: any[]) => any> & SpringBootSourceType & ClientSourceType & LanguageSourceType;

export type JHipsterApplication = BaseApplication & Partial<CommonClientServerApplication>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { expect } from 'chai';
import { basicHelpers as helpers, result as runResult } from '../../test/support/index.mjs';

import Base from './index.mjs';
import { parseChangelog } from './support/timestamp.mjs';
import { createJHipsterLogger } from './support/logger.mjs';
import { parseChangelog } from '../base/support/timestamp.mjs';
import { createJHipsterLogger } from '../base/support/logger.mjs';

const BaseGenerator: any = Base.prototype;

Expand Down
66 changes: 63 additions & 3 deletions generators/base-core/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import YeomanGenerator, { type ComposeOptions, type Storage } from 'yeoman-gener
import latestVersion from 'latest-version';
import SharedData from '../base/shared-data.mjs';
import { CUSTOM_PRIORITIES, PRIORITY_NAMES, PRIORITY_PREFIX } from '../base/priorities.mjs';
import { createJHipster7Context, joinCallbacks, Logger } from '../base/support/index.mjs';
import { createJHipster7Context, formatDateForChangelog, joinCallbacks, Logger } from '../base/support/index.mjs';

import type {
JHipsterGeneratorOptions,
Expand Down Expand Up @@ -141,12 +141,14 @@ export default class CoreGenerator extends YeomanGenerator<JHipsterGeneratorOpti
hide: true,
});

this.parseJHipsterOptions(command.options);

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

/* Options parsing must be executed after forcing jhipster storage namespace */
this.parseJHipsterOptions(command.options);

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

Expand Down Expand Up @@ -318,6 +320,55 @@ export default class CoreGenerator extends YeomanGenerator<JHipsterGeneratorOpti
this.options.positionalArguments = [];
}

/**
* Generate a date to be used by Liquibase changelogs.
*
* @param {Boolean} [reproducible=true] - Set true if the changelog date can be reproducible.
* Set false to create a changelog date incrementing the last one.
* @return {String} Changelog date.
*/
dateFormatForLiquibase(reproducible = this.sharedData.get('reproducible')) {
// Use started counter or use stored creationTimestamp if creationTimestamp option is passed
const creationTimestamp =
this.sharedData.get('creationTimestamp') ?? this.options.creationTimestamp ? this.config.get('creationTimestamp') : undefined;
let now = new Date();
// Miliseconds is ignored for changelogDate.
now.setMilliseconds(0);
// Run reproducible timestamp when regenerating the project with with-entities option.
if (reproducible || creationTimestamp) {
if (this.sharedData.get('reproducibleLiquibaseTimestamp')) {
// Counter already started.
now = this.sharedData.get('reproducibleLiquibaseTimestamp');
} else {
// Create a new counter
const newCreationTimestamp = creationTimestamp ?? this.config.get('creationTimestamp');
now = newCreationTimestamp ? new Date(newCreationTimestamp as any) : now;
now.setMilliseconds(0);
}
now.setMinutes(now.getMinutes() + 1);
this.sharedData.set('reproducibleLiquibaseTimestamp', now);

// Reproducible build can create future timestamp, save it.
const lastLiquibaseTimestamp = this.jhipsterConfig.lastLiquibaseTimestamp;
if (!lastLiquibaseTimestamp || now.getTime() > lastLiquibaseTimestamp) {
this.config.set('lastLiquibaseTimestamp', now.getTime());
}
} else {
// Get and store lastLiquibaseTimestamp, a future timestamp can be used
let lastLiquibaseTimestamp = this.jhipsterConfig.lastLiquibaseTimestamp;
if (lastLiquibaseTimestamp) {
lastLiquibaseTimestamp = new Date(lastLiquibaseTimestamp);
if (lastLiquibaseTimestamp >= now) {
now = lastLiquibaseTimestamp;
now.setSeconds(now.getSeconds() + 1);
now.setMilliseconds(0);
}
}
this.jhipsterConfig.lastLiquibaseTimestamp = now.getTime();
}
return formatDateForChangelog(now);
}

/**
* Alternative templatePath that fetches from the blueprinted generator, instead of the blueprint.
*/
Expand Down Expand Up @@ -813,6 +864,15 @@ templates: ${JSON.stringify(existingTemplates, null, 2)}`;
});
}

/**
* Merge value to an existing json and write to destination
*/
mergeDestinationJson(filepath: string, value: Record<string | number, any>) {
this.editFile(filepath, { create: true }, content => {
return JSON.stringify(merge(content ? JSON.parse(content) : {}, value), null, 2);
});
}

/**
* Shallow clone or convert dependencies to placeholder if needed.
*/
Expand Down
1 change: 1 addition & 0 deletions generators/base/__snapshots__/generator.spec.mts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Options:
--experimental Enable experimental features. Please note that these features may be unstable and may undergo breaking changes at any time
-d, --debug Enable debugger
--skip-jhipster-dependencies Don't write jhipster dependencies to package.json.
--creation-timestamp <value> Project creation timestamp (used for reproducible builds)
-h, --help display help for command

Commands:
Expand Down
2 changes: 1 addition & 1 deletion generators/base/api.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type ApplicationWithConfig = {

export type JHipsterGeneratorOptions = BaseOptions & {
applicationWithConfig?: ApplicationWithConfig;
creationTimestamp?: string;
positionalArguments?: unknown[];
jhipsterContext?: any;
skipYoResolve?: boolean;
Expand All @@ -19,7 +20,6 @@ export type JHipsterGeneratorOptions = BaseOptions & {
applicationWithEntities?: any;
blueprints?: string;
blueprint?: any;
configOptions: any;
reproducible?: boolean;
applicationId?: string;
sharedData: any;
Expand Down
6 changes: 6 additions & 0 deletions generators/base/command.mts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* limitations under the License.
*/
import { JHipsterCommandDefinition } from '../base/api.mjs';
import { parseCreationTimestamp } from './support/timestamp.mjs';

const command: JHipsterCommandDefinition = {
options: {
Expand Down Expand Up @@ -50,6 +51,11 @@ const command: JHipsterCommandDefinition = {
type: Boolean,
scope: 'storage',
},
creationTimestamp: {
description: 'Project creation timestamp (used for reproducible builds)',
type: parseCreationTimestamp,
scope: 'storage',
},
},
};

Expand Down
Loading
Loading