Skip to content

Commit

Permalink
rewamp logguer
Browse files Browse the repository at this point in the history
  • Loading branch information
Tcharl committed Jan 20, 2023
1 parent 4f1f890 commit 99d3eb9
Show file tree
Hide file tree
Showing 13 changed files with 73 additions and 84 deletions.
4 changes: 2 additions & 2 deletions generators/azure-spring-cloud/generator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -175,14 +175,14 @@ ${chalk.red('az extension add --name spring-cloud')}`
}
});
if (this.azureSpringCloudResourceGroupName === '') {
this.log.info(
this.logguer.info(
`Your default Azure resource group is not set up. We recommend doing it using the command
'${chalk.yellow('az configure --defaults group=<resource group name>')}`
);
this.azureSpringCloudResourceGroupName = '';
}
if (this.azureSpringCloudServiceName === '') {
this.log.info(
this.logguer.info(
`Your default Azure Spring Cloud service name is not set up. We recommend doing it using the command
'${chalk.yellow('az configure --defaults spring-cloud=<service instance name>')}`
);
Expand Down
2 changes: 1 addition & 1 deletion generators/base/generator-base-blueprint.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ export default class JHipsterBaseBlueprintGenerator extends JHipsterBaseGenerato
const blueprintJhipsterVersion = blueprintPackageJson.dependencies && blueprintPackageJson.dependencies['generator-jhipster'];
if (blueprintJhipsterVersion) {
if (!semver.valid(blueprintJhipsterVersion) && !semver.validRange(blueprintJhipsterVersion)) {
this.info(`Blueprint ${blueprintPkgName} contains generator-jhipster dependency with non comparable version`);
this.logguer.info(`Blueprint ${blueprintPkgName} contains generator-jhipster dependency with non comparable version`);
return;
}
if (semver.satisfies(mainGeneratorJhipsterVersion, blueprintJhipsterVersion)) {
Expand Down
13 changes: 1 addition & 12 deletions generators/base/generator-base-private.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export default class PrivateBase extends Generator {
const source = this.destinationPath(from);
const dest = this.destinationPath(to);
if (source && dest && shelljs.test('-f', source)) {
this.info(`Renaming the file - ${source} to ${dest}`);
this.logguer.info(`Renaming the file - ${source} to ${dest}`);
return !shelljs.exec(`git mv -f ${source} ${dest}`).code;
}
return true;
Expand Down Expand Up @@ -301,15 +301,4 @@ export default class PrivateBase extends Generator {
const formPath = [...prefix, ...reference.path].join("', '");
return `'${formPath}'`;
}

/**
* @private
*
* Print entity json representation.
*
* @param {object} entity
*/
debugEntity(entity) {
this.log(stringify(entity));
}
}
53 changes: 14 additions & 39 deletions generators/base/generator-base.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1246,37 +1246,10 @@ export default class JHipsterBaseGenerator extends PrivateBase {
* @param {string} msg - message to print
*/
error(msg) {
if (this._debug && this._debug.enabled) {
this._debug(`${chalk.red.bold('ERROR!')} ${msg}`);
}
this.logguer.error();
throw new Error(`${msg}`);
}

/**
* Print a warning message.
*
* @param {string} msg - message to print
*/
warning(msg) {
const warn = `${chalk.yellow.bold('WARNING!')} ${msg}`;
this.log(warn);
if (this._debug && this._debug.enabled) {
this._debug(warn);
}
}

/**
* Print an info message.
*
* @param {string} msg - message to print
*/
info(msg) {
this.log.info(msg);
if (this._debug && this._debug.enabled) {
this._debug(`${chalk.green('INFO!')} ${msg}`);
}
}

/**
* Print a success message.
*
Expand All @@ -1298,7 +1271,7 @@ export default class JHipsterBaseGenerator extends PrivateBase {
const keyStoreFile = `${keystoreFolder}/keystore.p12`;

if (this.fs.exists(keyStoreFile)) {
this.log(chalk.cyan(`\nKeyStore '${keyStoreFile}' already exists. Leaving unchanged.\n`));
this.logguer.log(chalk.cyan(`\nKeyStore '${keyStoreFile}' already exists. Leaving unchanged.\n`));
} else {
try {
shelljs.mkdir('-p', keystoreFolder);
Expand Down Expand Up @@ -1335,7 +1308,7 @@ export default class JHipsterBaseGenerator extends PrivateBase {
if (code !== 0) {
this.logguer.warn("\nFailed to create a KeyStore with 'keytool'", code);
} else {
this.log(chalk.green(`\nKeyStore '${keyStoreFile}' generated successfully.\n`));
this.logguer.info(chalk.green(`\nKeyStore '${keyStoreFile}' generated successfully.\n`));
}
done();
}
Expand All @@ -1347,24 +1320,26 @@ export default class JHipsterBaseGenerator extends PrivateBase {
* Prints a JHipster logo.
*/
printJHipsterLogo() {
this.log(chalk.white(`Application files will be generated in folder: ${chalk.yellow(process.cwd())}`));
this.logguer.log(chalk.white(`Application files will be generated in folder: ${chalk.yellow(process.cwd())}`));
if (process.cwd() === this.getUserHome()) {
this.log(chalk.red.bold('\n️⚠️ WARNING ⚠️ You are in your HOME folder!'));
this.log(chalk.red('This can cause problems, you should always create a new directory and run the jhipster command from here.'));
this.log(chalk.white(`See the troubleshooting section at ${chalk.yellow('https://www.jhipster.tech/installation/')}`));
this.logguer.log(chalk.red.bold('\n️⚠️ WARNING ⚠️ You are in your HOME folder!'));
this.logguer.log(
chalk.red('This can cause problems, you should always create a new directory and run the jhipster command from here.')
);
this.logguer.log(chalk.white(`See the troubleshooting section at ${chalk.yellow('https://www.jhipster.tech/installation/')}`));
}
this.log(
this.logguer.log(
chalk.green(' _______________________________________________________________________________________________________________\n')
);
this.log(
this.logguer.log(
chalk.white(` Documentation for creating an application is at ${chalk.yellow('https://www.jhipster.tech/creating-an-app/')}`)
);
this.log(
this.logguer.log(
chalk.white(
` If you find JHipster useful, consider sponsoring the project at ${chalk.yellow('https://opencollective.com/generator-jhipster')}`
)
);
this.log(
this.logguer.log(
chalk.green(' _______________________________________________________________________________________________________________\n')
);
}
Expand Down Expand Up @@ -1516,7 +1491,7 @@ export default class JHipsterBaseGenerator extends PrivateBase {
buildCmd = `./${buildCmd}`;
}
buildCmd += ` -P${profile}`;
this.log(`Running command: '${chalk.bold(buildCmd)}'`);
this.logguer.info(`Running command: '${chalk.bold(buildCmd)}'`);
return {
stdout: exec(buildCmd, { maxBuffer: 1024 * 10000 }, cb).stdout,
buildCmd,
Expand Down
2 changes: 1 addition & 1 deletion generators/base/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ export default class BaseGenerator extends JHipsterBaseBlueprintGenerator {
validateCheckResult(result: CheckResult, { printInfo = false, throwOnError = true } = {}) {
// Don't print check info by default for cleaner outputs.
if (printInfo && result.info) {
this.info(result.info);
this.logguer.info(result.info);
}
if (result.warning) {
this.logguer.warn(result.warning);
Expand Down
35 changes: 31 additions & 4 deletions generators/base/support/logging.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,20 @@ import chalk from 'chalk';

/**
* formats the message to be displayed in the console.
* @param message the debug message to format.
* @param message the info message to format.
*/
const formatWarningMessageHeader = message => {
return `${chalk.yellow.bold('WARNING!')} ${message}`;
};

const formatErrorMessageHeader = message => {
return `${chalk.red.bold('ERROR!')} ${message}`;
};

const formatInfoMessageHeader = message => {
return `${chalk.green('INFO!')} ${message}`;
};

/**
* Checks if the configOptions or generatorOptions contains the debug flag.
* @param configOptions the jh configOptions
Expand Down Expand Up @@ -94,13 +102,32 @@ export class Logguer {
logDebug(this.isDebugEnabled, this.yeomanLogguer, this.yeomanDebug, msg, ...args);
}

warn(msg) {
const warn = formatWarningMessageHeader(msg);
printMessageUsingGeneratorLogger(this.yeomanLogguer, warn);
if (this.isDebugEnabled) {
printMessageAndArgumentsUsingInternalDebugger(this.yeomanDebug, warn);
}
}

info(msg) {
console.info(`${chalk.green.bold('INFO!')} ${msg}`);
const info = formatInfoMessageHeader(msg);
printMessageUsingGeneratorLogger(this.yeomanLogguer, info);
if (this.isDebugEnabled) {
printMessageAndArgumentsUsingInternalDebugger(this.yeomanDebug, info);
}
}

warn(msg) {
const warn = formatWarningMessageHeader(msg);
log(msg) {
printMessageUsingGeneratorLogger(this.yeomanLogguer, msg);
}

error(msg) {
const warn = formatErrorMessageHeader(msg);
printMessageUsingGeneratorLogger(this.yeomanLogguer, warn);
if (this.isDebugEnabled) {
printMessageAndArgumentsUsingInternalDebugger(this.yeomanDebug, warn);
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion generators/liquibase/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export default class DatabaseChangelogGenerator extends BaseApplication<SpringBo
if (this.options.help) {
return;
}
this.info(`Creating changelog for entities ${this.options.entities}`);
this.logguer.info(`Creating changelog for entities ${this.options.entities}`);
this.configOptions.oldSharedEntities = this.configOptions.oldSharedEntities || [];
}

Expand Down
14 changes: 7 additions & 7 deletions generators/server/generator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -311,13 +311,13 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator {
loadEnvironmentVariables({ application }) {
application.defaultPackaging = process.env.JHI_WAR === '1' ? 'war' : 'jar';
if (application.defaultPackaging === 'war') {
this.info(`Using ${application.defaultPackaging} as default packaging`);
this.logguer.info(`Using ${application.defaultPackaging} as default packaging`);
}

const JHI_PROFILE = process.env.JHI_PROFILE;
application.defaultEnvironment = (JHI_PROFILE || '').includes('dev') ? 'dev' : 'prod';
if (JHI_PROFILE) {
this.info(`Using ${application.defaultEnvironment} as default profile`);
this.logguer.info(`Using ${application.defaultEnvironment} as default profile`);
}
},

Expand All @@ -336,7 +336,7 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator {
application.JAVA_COMPATIBLE_VERSIONS = JAVA_COMPATIBLE_VERSIONS;

if (this.projectVersion) {
this.info(`Using projectVersion: ${application.jhipsterDependenciesVersion}`);
this.logguer.info(`Using projectVersion: ${application.jhipsterDependenciesVersion}`);
application.projectVersion = this.projectVersion;
} else {
application.projectVersion = '0.0.1-SNAPSHOT';
Expand All @@ -346,7 +346,7 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator {
application.jhipsterDependenciesVersion = 'JHIPSTER_DEPENDENCIES_VERSION';
} else if (this.jhipsterDependenciesVersion) {
application.jhipsterDependenciesVersion = this.jhipsterDependenciesVersion;
this.info(`Using jhipsterDependenciesVersion: ${application.jhipsterDependenciesVersion}`);
this.logguer.info(`Using jhipsterDependenciesVersion: ${application.jhipsterDependenciesVersion}`);
} else {
application.jhipsterDependenciesVersion = JHIPSTER_DEPENDENCIES_VERSION;
}
Expand Down Expand Up @@ -484,7 +484,7 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator {
if (entityConfig.changelogDate === undefined) {
const currentDate = this.dateFormatForLiquibase();
if (entityStorage.existed) {
this.info(`changelogDate is missing in .jhipster/${entityConfig.name}.json, using ${currentDate} as fallback`);
this.logguer.info(`changelogDate is missing in .jhipster/${entityConfig.name}.json, using ${currentDate} as fallback`);
}
entityConfig.changelogDate = currentDate;
}
Expand Down Expand Up @@ -544,7 +544,7 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator {
);
}
if (relationship.useJPADerivedIdentifier) {
this.info('Option useJPADerivedIdentifier is deprecated, use id instead');
this.logguer.info('Option useJPADerivedIdentifier is deprecated, use id instead');
relationship.id = true;
}
});
Expand Down Expand Up @@ -794,7 +794,7 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator {
}

if (config.enableHibernateCache && [NO_CACHE, MEMCACHED].includes(config.cacheProvider)) {
this.info(`Disabling hibernate cache for cache provider ${config.cacheProvider}`);
this.logguer.info(`Disabling hibernate cache for cache provider ${config.cacheProvider}`);
config.enableHibernateCache = false;
}

Expand Down
21 changes: 10 additions & 11 deletions generators/upgrade/generator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const FIRST_CLI_SUPPORTED_VERSION = '4.5.1'; // The first version in which CLI s
* @param {function} callback[optional] - a callback function to be called once process complete, The call back will receive code, stdout and stderr
* @return {object} when in synchronous mode, this returns a ShellString. Otherwise, this returns the child process object.
*/
function gitExec(args, options = {}, callback) {
function gitExec(logguer, args, options = {}, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
Expand All @@ -62,9 +62,8 @@ function gitExec(args, options = {}, callback) {
args = [args];
}
const command = `git ${args.join(' ')}`;
if (options.trace) {
console.info(command);
}

logguer.debug(command);
if (callback) {
return shelljs.exec(command, options, callback);
}
Expand Down Expand Up @@ -148,7 +147,7 @@ export default class UpgradeGenerator extends BaseGenerator {

_rmRf(file) {
const absolutePath = path.resolve(file);
this.info(`Removing ${absolutePath}`);
this.logguer.info(`Removing ${absolutePath}`);
shelljs.rm('-rf', absolutePath);
}

Expand Down Expand Up @@ -193,7 +192,7 @@ export default class UpgradeGenerator extends BaseGenerator {
}
const skipChecksOption = this.skipChecks ? '--skip-checks' : '';
const regenerateCmd = `${generatorCommand} --with-entities --force --skip-install --skip-git --ignore-errors --no-insight ${skipChecksOption}`;
this.info(regenerateCmd);
this.logguer.info(regenerateCmd);
try {
childProcess.execSync(regenerateCmd, { stdio: 'inherit' });
this.success(`Successfully regenerated application with JHipster ${jhipsterVersion}${blueprintInfo}`);
Expand All @@ -216,7 +215,7 @@ export default class UpgradeGenerator extends BaseGenerator {
_regenerate(jhipsterVersion, blueprintInfo) {
this._generate(jhipsterVersion, blueprintInfo);
const keystore = `${SERVER_MAIN_RES_DIR}config/tls/keystore.p12`;
this.info(`Removing ${keystore}`);
this.logguer.info(`Removing ${keystore}`);
this._rmRf(keystore);
this._gitCommitAll(`Generated with JHipster ${jhipsterVersion}${blueprintInfo}`);
}
Expand All @@ -239,7 +238,7 @@ export default class UpgradeGenerator extends BaseGenerator {
const devDependencyParam = '--save-dev';
const noPackageLockParam = '--no-package-lock';
const generatorCommand = `${commandPrefix} ${npmPackage}@${version} ${devDependencyParam} ${noPackageLockParam} --ignore-scripts --legacy-peer-deps`;
this.info(generatorCommand);
this.logguer.info(generatorCommand);

const npmIntall = shelljs.exec(generatorCommand, { silent: this.silent });
if (npmIntall.code === 0) this.success(`Installed ${npmPackage}@${version}`);
Expand Down Expand Up @@ -518,10 +517,10 @@ export default class UpgradeGenerator extends BaseGenerator {
install() {
if (!this.skipInstall) {
this.log('Installing dependencies, please wait...');
this.info('Removing the node_modules directory');
this.logguer.info('Removing the node_modules directory');
this._rmRf('node_modules');
const installCommand = 'npm install';
this.info(installCommand);
this.logguer.info(installCommand);

const pkgInstall = shelljs.exec(installCommand, { silent: this.silent });
if (pkgInstall.code !== 0) {
Expand Down Expand Up @@ -559,6 +558,6 @@ export default class UpgradeGenerator extends BaseGenerator {
* @return {object} when in synchronous mode, this returns a ShellString. Otherwise, this returns the child process object.
*/
gitExec(args, options, callback) {
return gitExec(args, options, callback);
return gitExec(this.logguer, args, options, callback);
}
}
2 changes: 0 additions & 2 deletions generators/upgrade/upgrade.spec.mts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

describe('generator - upgrade', function () {
this.timeout(400000);

describe('default application', () => {
let runResult;

Expand Down
Loading

0 comments on commit 99d3eb9

Please sign in to comment.