From 4da08996736c9a8f2b0a0193f7cca4b24f3fc6f1 Mon Sep 17 00:00:00 2001 From: Piotr Grzesik Date: Tue, 12 Oct 2021 10:16:55 +0200 Subject: [PATCH] refactor(CLI): Replace warnings with modern counterparts --- lib/classes/ConfigSchemaHandler/index.js | 48 ++++-- lib/classes/PluginManager.js | 26 ++- lib/cli/commands-schema/resolve-final.js | 2 +- lib/plugins/aws/deploy/lib/checkForChanges.js | 12 +- .../aws/deploy/lib/extendedValidate.js | 23 ++- lib/plugins/aws/deployFunction.js | 5 +- lib/plugins/aws/invokeLocal/index.js | 11 +- .../aws/lib/checkIfEcrRepositoryExists.js | 9 +- .../compile/events/apiGateway/lib/validate.js | 26 ++- .../aws/package/compile/events/cloudFront.js | 18 ++- .../aws/package/lib/generateCoreTemplate.js | 6 +- lib/plugins/aws/provider.js | 8 +- lib/utils/eventuallyUpdate.js | 43 ++--- test/unit/lib/classes/PluginManager.test.js | 20 --- .../aws/deploy/lib/checkForChanges.test.js | 2 +- .../events/apiGateway/lib/validate.test.js | 151 ------------------ .../package/compile/events/cloudFront.test.js | 36 ----- test/unit/lib/plugins/aws/provider.test.js | 9 +- 18 files changed, 167 insertions(+), 288 deletions(-) diff --git a/lib/classes/ConfigSchemaHandler/index.js b/lib/classes/ConfigSchemaHandler/index.js index 58d0620def9..4ae40493560 100644 --- a/lib/classes/ConfigSchemaHandler/index.js +++ b/lib/classes/ConfigSchemaHandler/index.js @@ -6,6 +6,7 @@ const ensurePlainObject = require('type/plain-object/ensure'); const schema = require('../../configSchema'); const ServerlessError = require('../../serverless-error'); const normalizeAjvErrors = require('./normalizeAjvErrors'); +const { legacy, log, style } = require('@serverless/utils/log'); const FUNCTION_NAME_PATTERN = '^[a-zA-Z0-9-_]+$'; const ERROR_PREFIX = 'Configuration error'; @@ -79,30 +80,41 @@ class ConfigSchemaHandler { if (!this.schema.properties.provider.properties.name) { configurationValidationResults.set(this.serverless.configurationInput, false); if (this.serverless.service.configValidationMode !== 'off') { - this.serverless.cli.log( + legacy.log( `${WARNING_PREFIX}: Unrecognized provider '${this.serverless.service.provider.name}'`, 'Serverless', { color: 'orange' } ); - this.serverless.cli.log(' '); - this.serverless.cli.log( + legacy.log(' '); + legacy.log( "You're relying on provider plugin which doesn't " + 'provide a validation schema for its config.', 'Serverless', { color: 'orange' } ); - this.serverless.cli.log( + legacy.log( 'Please report the issue at its bug tracker linking: ' + 'https://www.serverless.com/framework/docs/providers/aws/guide/plugins#extending-validation-schema', 'Serverless', { color: 'orange' } ); - this.serverless.cli.log( + legacy.log( 'You may turn off this message with "configValidationMode: off" setting', 'Serverless', { color: 'orange' } ); - this.serverless.cli.log(' '); + legacy.log(' '); + + log.warning( + [ + `You're relying on provider "${this.serverless.service.provider.name}" defined by a plugin which doesn't provide a validation schema for its config.`, + `Please report the issue at its bug tracker linking: ${style.link( + 'https://www.serverless.com/framework/docs/providers/aws/guide/plugins#extending-validation-schema' + )}`, + 'You may turn off this message with "configValidationMode: off" setting', + '', + ].join('\n') + ); } this.relaxProviderSchema(); @@ -139,24 +151,36 @@ class ConfigSchemaHandler { ); } else { if (messages.length === 1) { - this.serverless.cli.log(`${WARNING_PREFIX} ${messages[0]}`, 'Serverless', { + legacy.log(`${WARNING_PREFIX} ${messages[0]}`, 'Serverless', { color: 'orange', }); } else { - this.serverless.cli.log(`${WARNING_PREFIX}:`, 'Serverless', { + legacy.log(`${WARNING_PREFIX}:`, 'Serverless', { color: 'orange', }); for (const message of messages) { - this.serverless.cli.log(` ${message}`, 'Serverless', { color: 'orange' }); + legacy.log(` ${message}`, 'Serverless', { color: 'orange' }); } } - this.serverless.cli.log(' '); - this.serverless.cli.log( + legacy.log(' '); + legacy.log( 'Learn more about configuration validation here: http://slss.io/configuration-validation', 'Serverless', { color: 'orange' } ); - this.serverless.cli.log(' '); + legacy.log(' '); + + log.notice(); + log.warning( + [ + 'Invalid configuration encountered', + ...messages.map((message) => ` ${message}`), + '', + `Learn more about configuration validation here: ${style.link( + 'http://slss.io/configuration-validation' + )}`, + ].join('\n') + ); } } } diff --git a/lib/classes/PluginManager.js b/lib/classes/PluginManager.js index 39d5187b8be..02588a5cba7 100644 --- a/lib/classes/PluginManager.js +++ b/lib/classes/PluginManager.js @@ -133,7 +133,10 @@ class PluginManager { // don't load plugins twice if (this.plugins.some((plugin) => plugin instanceof Plugin)) { - this.serverless.cli.log(`WARNING: duplicate plugin ${Plugin.name} was not loaded\n`); + legacy.log(`WARNING: duplicate plugin ${Plugin.name} was not loaded\n`); + log.warning( + `Duplicate plugin definition found in your configuration. Plugin "${Plugin.name}" will not be loaded more than once.` + ); return null; } @@ -300,8 +303,9 @@ class PluginManager { // Handle command aliases (details.aliases || []).forEach((alias) => { if (process.env.SLS_DEBUG) { - this.serverless.cli.log(` -> @${alias}`); + legacy.log(` -> @${alias}`); } + log.get('lifecycle:command:register').debug(` -> @${alias}`); this.createCommandAlias(alias, key); }); return Object.assign({}, details, { key, pluginName, commands }); @@ -342,9 +346,12 @@ class PluginManager { if (this.deprecatedEvents[baseEvent]) { const redirectedEvent = this.deprecatedEvents[baseEvent]; if (process.env.SLS_DEBUG) { - this.serverless.cli.log(`WARNING: Plugin ${pluginName} uses deprecated hook ${event}, + legacy.log(`WARNING: Plugin ${pluginName} uses deprecated hook ${event}, use ${redirectedEvent} hook instead`); } + log.info( + `Plugin "${pluginName}" uses deprecated hook "${event}". Use "${redirectedEvent}" hook instead.` + ); if (redirectedEvent) { target = event.replace(baseEvent, redirectedEvent); } @@ -365,9 +372,10 @@ class PluginManager { )) { let options = resolverOrOptions; if (!options) { - this.serverless.cli.log( + legacy.log( `Warning! Ignoring falsy variableResolver for ${variablePrefix} in ${pluginName}.` ); + log.warning(`Ignoring falsy variableResolver for ${variablePrefix} in ${pluginName}.`); continue; } if (typeof resolverOrOptions === 'function') { @@ -606,8 +614,9 @@ class PluginManager { } catch (error) { if (error instanceof TerminateHookChain) { if (process.env.SLS_DEBUG) { - this.serverless.cli.log(`Terminate ${commandsArray.join(':')}`); + legacy.log(`Terminate ${commandsArray.join(':')}`); } + log.debug(`Terminate ${commandsArray.join(':')}`); return; } throw error; @@ -666,11 +675,16 @@ class PluginManager { for (const { hook } of this.hooks.error || []) await hook(commandException); } catch (errorHookException) { const errorHookExceptionMeta = tokenizeException(errorHookException); - this.serverless.cli.log( + legacy.log( `Warning: "error" hook crashed with: ${ errorHookExceptionMeta.stack || errorHookExceptionMeta.message }` ); + log.warning( + `The "error" hook crashed with:\n${ + errorHookExceptionMeta.stack || errorHookExceptionMeta.message + }` + ); } finally { await deferredBackendNotificationRequest; throw commandException; // eslint-disable-line no-unsafe-finally diff --git a/lib/cli/commands-schema/resolve-final.js b/lib/cli/commands-schema/resolve-final.js index 98150a9902c..4a5c2fe809c 100644 --- a/lib/cli/commands-schema/resolve-final.js +++ b/lib/cli/commands-schema/resolve-final.js @@ -131,7 +131,7 @@ module.exports = (loadedPlugins, { providerName }) => { ([plugin, optionNames]) => `${plugin.constructor.name} for "${Array.from(optionNames).join('", "')}"` ).join('\n - ')}\n\n` + - 'Please report this issue in issue tracker of the corresponding plugin.' + 'Please report this issue in issue tracker of the corresponding plugin.\n' ); } diff --git a/lib/plugins/aws/deploy/lib/checkForChanges.js b/lib/plugins/aws/deploy/lib/checkForChanges.js index ff61ac3ff29..ff18219863a 100644 --- a/lib/plugins/aws/deploy/lib/checkForChanges.js +++ b/lib/plugins/aws/deploy/lib/checkForChanges.js @@ -8,7 +8,7 @@ const BbPromise = require('bluebird'); const _ = require('lodash'); const normalizeFiles = require('../../lib/normalizeFiles'); const ServerlessError = require('../../../../serverless-error'); -const { legacy } = require('@serverless/utils/log'); +const { legacy, log } = require('@serverless/utils/log'); module.exports = { async checkForChanges() { @@ -108,14 +108,14 @@ module.exports = { return BbPromise.all(getFunctionResults).then((results) => { if (couldNotAccessFunction) { - this.serverless.cli.log( - [ - 'WARNING: Not authorized to perform: lambda:GetFunction for at least one of the lambda functions.', - ' Deployment will not be skipped even if service files did not change. ', - ].join(''), + legacy.log( + 'WARNING: Not authorized to perform: lambda:GetFunction for at least one of the lambda functions. Deployment will not be skipped even if service files did not change.', 'Serverless', { color: 'orange' } ); + log.warning( + 'Not authorized to perform: lambda:GetFunction for at least one of the lambda functions. Deployment will not be skipped even if service files did not change.' + ); } return results.reduce((currentMin, date) => { diff --git a/lib/plugins/aws/deploy/lib/extendedValidate.js b/lib/plugins/aws/deploy/lib/extendedValidate.js index 8a37be45d82..b601d066714 100644 --- a/lib/plugins/aws/deploy/lib/extendedValidate.js +++ b/lib/plugins/aws/deploy/lib/extendedValidate.js @@ -4,7 +4,7 @@ const path = require('path'); const _ = require('lodash'); const findReferences = require('../../utils/findReferences'); const ServerlessError = require('../../../../serverless-error'); -const { legacy } = require('@serverless/utils/log'); +const { legacy, log } = require('@serverless/utils/log'); module.exports = { extendedValidate() { @@ -46,13 +46,20 @@ module.exports = { if (functionObject.timeout > 30 && functionObject.events) { functionObject.events.forEach((event) => { if (Object.keys(event)[0] === 'http' && !event.http.async) { - const warnMessage = [ - `WARNING: Function ${functionName} has timeout of ${functionObject.timeout} `, - "seconds, however, it's attached to API Gateway so it's automatically ", - 'limited to 30 seconds.', - ].join(''); - - legacy.log(warnMessage); + legacy.log( + [ + `WARNING: Function ${functionName} has timeout of ${functionObject.timeout} `, + "seconds, however, it's attached to API Gateway so it's automatically ", + 'limited to 30 seconds.', + ].join('') + ); + log.warning( + [ + `Function ${functionName} has timeout of ${functionObject.timeout} `, + "seconds, however, it's attached to API Gateway so it's automatically ", + 'limited to 30 seconds.', + ].join('') + ); } }); } diff --git a/lib/plugins/aws/deployFunction.js b/lib/plugins/aws/deployFunction.js index 680b673dcc5..f778312a275 100644 --- a/lib/plugins/aws/deployFunction.js +++ b/lib/plugins/aws/deployFunction.js @@ -179,7 +179,10 @@ class AwsDeployFunction { 'DEPLOY_FUNCTION_CONFIGURATION_UPDATE_TIMED_OUT' ); } - this.serverless.cli.log( + legacy.log( + `Retrying configuration update for function: ${this.options.function}. Reason: ${err.message}` + ); + log.info( `Retrying configuration update for function: ${this.options.function}. Reason: ${err.message}` ); await wait(1000); diff --git a/lib/plugins/aws/invokeLocal/index.js b/lib/plugins/aws/invokeLocal/index.js index cda97f72a29..5dc93e04c7e 100644 --- a/lib/plugins/aws/invokeLocal/index.js +++ b/lib/plugins/aws/invokeLocal/index.js @@ -643,12 +643,11 @@ class AwsInvokeLocal { { shell: true } ); - // TODO: CONSIDER IT AS A WARNING - this.serverless.cli.log( - [ - 'In order to get human-readable output,', - ' please implement "toString()" method of your "ApiGatewayResponse" object.', - ].join('') + legacy.log( + 'In order to get human-readable output, please implement "toString()" method of your "ApiGatewayResponse" object.' + ); + log.warning( + 'In order to get human-readable output, please implement "toString()" method of your "ApiGatewayResponse" object.' ); java.stdout.on('data', (buf) => { diff --git a/lib/plugins/aws/lib/checkIfEcrRepositoryExists.js b/lib/plugins/aws/lib/checkIfEcrRepositoryExists.js index 3b7f18944b3..bcbffb350d6 100644 --- a/lib/plugins/aws/lib/checkIfEcrRepositoryExists.js +++ b/lib/plugins/aws/lib/checkIfEcrRepositoryExists.js @@ -1,5 +1,7 @@ 'use strict'; +const { legacy, log } = require('@serverless/utils/log'); + module.exports = { async checkIfEcrRepositoryExists() { const registryId = await this.provider.getAccountId(); @@ -16,11 +18,14 @@ module.exports = { } if (err.providerError && err.providerError.code === 'AccessDeniedException') { if (this.serverless.service.provider.ecr && this.serverless.service.provider.ecr.images) { - this.serverless.cli.log( - 'WARNING: Could not access ECR repository due to denied access, but there are images defined in `provider.ecr`. ECR repository removal will be skipped.', + legacy.log( + 'WARNING: Could not access ECR repository due to denied access, but there are images defined in "provider.ecr". ECR repository removal will be skipped.', 'Serverless', { color: 'orange' } ); + log.warning( + 'Could not access ECR repository due to denied access, but there are images defined in "provider.ecr". ECR repository removal will be skipped.' + ); } // Check if user has images defined and issue warning that we could not return false; diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js index a2c5ad8895a..5b99559e8d3 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js @@ -4,6 +4,7 @@ const _ = require('lodash'); const awsArnRegExs = require('../../../../../utils/arnRegularExpressions'); const resolveLambdaTarget = require('../../../../../utils/resolveLambdaTarget'); const ServerlessError = require('../../../../../../../serverless-error'); +const { legacy, log } = require('@serverless/utils/log'); const NOT_FOUND = -1; const DEFAULT_STATUS_CODES = { @@ -116,14 +117,15 @@ module.exports = { if (_.difference(keys, allowedKeys).length) { const requestWarningMessage = [ - `Warning! You're using the ${http.integration} in combination with a request`, + `You're using the ${http.integration} in combination with a request`, ` configuration in your function "${functionName}". Only the `, allowedKeys.map((value) => `request.${value}`).join(', '), ` configs are available in conjunction with ${http.integration}.`, ' Serverless will remove this configuration automatically', ' before deployment.', ].join(''); - this.serverless.cli.log(requestWarningMessage); + legacy.log(`Warning! ${requestWarningMessage}`); + log.warning(requestWarningMessage); for (const key of keys) { if (!allowedKeys.includes(key)) { delete http.request[key]; @@ -138,12 +140,20 @@ module.exports = { } } if (http.response) { - const warningMessage = [ - `Warning! You're using the ${http.integration} in combination with response`, - ` configuration in your function "${functionName}".`, - ' Serverless will remove this configuration automatically before deployment.', - ].join(''); - this.serverless.cli.log(warningMessage); + legacy.log( + [ + `Warning! You're using the ${http.integration} in combination with response`, + ` configuration in your function "${functionName}".`, + ' Serverless will remove this configuration automatically before deployment.', + ].join('') + ); + log.warning( + [ + `You're using the ${http.integration} in combination with response`, + ` configuration in your function "${functionName}".`, + ' Serverless will remove this configuration automatically before deployment.', + ].join('') + ); delete http.response; } diff --git a/lib/plugins/aws/package/compile/events/cloudFront.js b/lib/plugins/aws/package/compile/events/cloudFront.js index 63a1fd05a15..be6e9129fa8 100644 --- a/lib/plugins/aws/package/compile/events/cloudFront.js +++ b/lib/plugins/aws/package/compile/events/cloudFront.js @@ -4,6 +4,7 @@ const _ = require('lodash'); const url = require('url'); const chalk = require('chalk'); const ServerlessError = require('../../../../../serverless-error'); +const { legacy, log, style } = require('@serverless/utils/log'); const originLimits = { maxTimeout: 30, maxMemorySize: 10240 }; const viewerLimits = { maxTimeout: 5, maxMemorySize: 128 }; @@ -255,7 +256,8 @@ class AwsCompileCloudFrontEvents { "Don't forget to manually remove your Lambda@Edge functions ", 'once the CloudFront distribution removal is successfully propagated!', ].join(''); - this.serverless.cli.log(message, 'Serverless', { color: 'orange' }); + legacy.log(message, 'Serverless', { color: 'orange' }); + log.warning(message); } } } @@ -540,10 +542,13 @@ class AwsCompileCloudFrontEvents { }); unusedUserDefinedCachePolicies.forEach((unusedUserDefinedCachePolicy) => { - this.serverless.cli.log( + legacy.log( `WARNING: provider.cloudFront.cachePolicies.${unusedUserDefinedCachePolicy} ` + 'not used by any cloudFront event configuration' ); + log.warning( + `Setting "provider.cloudFront.cachePolicies.${unusedUserDefinedCachePolicy}" is not used by any cloudFront event configuration.` + ); }); // sort that first is without PathPattern if available @@ -645,14 +650,19 @@ class AwsCompileCloudFrontEvents { Object.assign(Resources, lambdaInvokePermissions); if (!Resources.IamRoleLambdaExecution) { - this.serverless.cli.log( + legacy.log( chalk.magenta('Remember to add required lambda@edge permissions to your execution role.') ); - this.serverless.cli.log( + legacy.log( chalk.magenta( 'https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-permissions.html' ) ); + log.notice( + `Remember to add required lambda@edge permissions to your execution role. Documentation: ${style.link( + 'https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-permissions.html' + )}` + ); } else { const lambdaAssumeStatement = Resources.IamRoleLambdaExecution.Properties.AssumeRolePolicyDocument.Statement.find( diff --git a/lib/plugins/aws/package/lib/generateCoreTemplate.js b/lib/plugins/aws/package/lib/generateCoreTemplate.js index 91eb7c9104f..925d7729016 100644 --- a/lib/plugins/aws/package/lib/generateCoreTemplate.js +++ b/lib/plugins/aws/package/lib/generateCoreTemplate.js @@ -3,6 +3,7 @@ const path = require('path'); const _ = require('lodash'); const ServerlessError = require('../../../../serverless-error'); +const { legacy, log } = require('@serverless/utils/log'); module.exports = { generateCoreTemplate() { @@ -93,9 +94,8 @@ module.exports = { if (bucketName) { if (isS3TransferAccelerationEnabled) { - const warningMessage = - 'Warning: S3 Transfer Acceleration will not be enabled on deploymentBucket.'; - this.serverless.cli.log(warningMessage); + legacy.log('Warning: S3 Transfer Acceleration will not be enabled on deploymentBucket.'); + log.warning('S3 Transfer Acceleration cannot be enabled on user provided S3 bucket'); } this.bucketName = bucketName; this.serverless.service.package.deploymentBucket = bucketName; diff --git a/lib/plugins/aws/provider.js b/lib/plugins/aws/provider.js index 988b908b6f8..917a15822a0 100644 --- a/lib/plugins/aws/provider.js +++ b/lib/plugins/aws/provider.js @@ -14,7 +14,6 @@ const path = require('path'); const spawnExt = require('child-process-ext/spawn'); const ServerlessError = require('../../serverless-error'); const awsRequest = require('../../aws/request'); -const oldLog = require('@serverless/utils/log'); const deepSortObjectByKey = require('../../utils/deepSortObjectByKey'); const { progress, legacy, log } = require('@serverless/utils/log'); @@ -1446,7 +1445,7 @@ class AwsProvider { // Emit a warning for misuses of the old signature including stage and region // TODO: Determine calling module and log that if (process.env.SLS_DEBUG && options != null && !_.isObject(options)) { - oldLog('WARNING: Inappropriate call of provider.request()'); + legacy.log('WARNING: Inappropriate call of provider.request()'); } const requestOptions = _.isObject(options) ? options : {}; const shouldCache = _.get(requestOptions, 'useCache', false); @@ -1888,11 +1887,14 @@ Object.defineProperties( legacy.log('Login to Docker succeeded!'); log.info('Login to Docker succeeded!'); if (stdBuffer.includes('password will be stored unencrypted')) { - this.serverless.cli.log( + legacy.log( 'WARNING: Docker authentication token will be stored unencrypted in docker config. Configure Docker credential helper to remove this warning.', 'Serverless', { color: 'orange' } ); + log.warning( + 'Docker authentication token will be stored unencrypted in docker config. Configure Docker credential helper to remove this warning.' + ); } } catch (err) { throw new ServerlessError( diff --git a/lib/utils/eventuallyUpdate.js b/lib/utils/eventuallyUpdate.js index 9b11eb8121a..96986922690 100644 --- a/lib/utils/eventuallyUpdate.js +++ b/lib/utils/eventuallyUpdate.js @@ -23,6 +23,7 @@ const pipeline = promisify(stream.pipeline); const npmInstallationDir = path.resolve(__dirname, '../../'); const serverlessTmpDir = path.resolve(os.tmpdir(), 'tmpdirs-serverless'); +const { legacy, log, style } = require('@serverless/utils/log'); const CHECK_INTERVAL = 1000 * 60 * 30; // 30 minutes @@ -30,13 +31,10 @@ const npmUpdate = async (serverless, { newVersion, tarballUrl, abortHandler }) = const npmPackageRoot = await isNpmPackageWritable(); if (!npmPackageRoot) { - serverless.cli.log( - `Auto update error: No write access to ${npmInstallationDir}`, - 'Serverless', - { - color: 'orange', - } - ); + legacy.log(`Auto update error: No write access to ${npmInstallationDir}`, 'Serverless', { + color: 'orange', + }); + log.warning(`Auto update error: No write access to ${npmInstallationDir}`); return null; } const tempInstallationDir = path.resolve(serverlessTmpDir, `npm-update-${newVersion}`); @@ -60,8 +58,11 @@ const npmUpdate = async (serverless, { newVersion, tarballUrl, abortHandler }) = await fse.remove(tempOldInstallationDir); }; } catch (error) { - if (!abortHandler.isAborted && process.env.SLS_DEBUG) { - serverless.cli.log(format('Auto update: Could not update npm installation: %O', error)); + if (!abortHandler.isAborted) { + if (process.env.SLS_DEBUG) { + legacy.log(format('Auto update: Could not update npm installation: %O', error)); + } + log.info('Auto update: Could not update npm installation: %O', error); } return null; } @@ -78,8 +79,11 @@ const standaloneUpdate = async (serverless, { newVersion, abortHandler }) => { await fsp.chmod(tempStandalonePath, 0o755); return () => fsp.rename(tempStandalonePath, standaloneUtils.path); } catch (error) { - if (!abortHandler.isAborted && process.env.SLS_DEBUG) { - serverless.cli.log(format('Auto update: Could not update npm installation: %O', error)); + if (!abortHandler.isAborted) { + if (process.env.SLS_DEBUG) { + legacy.log(format('Auto update: Could not update npm installation: %O', error)); + } + log.info('Auto update: Could not update npm installation: %O', error); } return null; } @@ -115,19 +119,19 @@ module.exports = async (serverless) => { try { versionRequest = await versionsRequest; } catch (error) { - if (!abortHandler.isAborted && process.env.SLS_DEBUG) { - serverless.cli.log( - format('Auto update: Could not resolve version info from npm: %O', error) - ); + if (!abortHandler.isAborted) { + if (process.env.SLS_DEBUG) { + legacy.log(format('Auto update: Could not resolve version info from npm: %O', error)); + } + log.debug('Auto update: Could not resolve version info from npm: %O', error); } return null; } try { return JSON.parse(versionRequest.body); } catch (error) { - serverless.cli.log( - format('Auto update: Unexpected response from npm: %s', versionRequest.body) - ); + legacy.log(format('Auto update: Unexpected response from npm: %s', versionRequest.body)); + log.debug('Auto update: Unexpected response from npm: %s', versionRequest.body); return null; } })(); @@ -162,7 +166,8 @@ module.exports = async (serverless) => { if (!updateTask) return; serverless.onExitPromise.then(async () => { await updateTask(); - serverless.cli.log(`Sucessfully updated to v${latestVersion}`); + legacy.log(`Sucessfully updated to v${latestVersion}`); + log.notice(style.aside(`Successfully updated to v${latestVersion}`)); }); } autoUpdateConfig.lastChecked = Date.now(); diff --git a/test/unit/lib/classes/PluginManager.test.js b/test/unit/lib/classes/PluginManager.test.js index bd7827bed60..cc89f44eeeb 100644 --- a/test/unit/lib/classes/PluginManager.test.js +++ b/test/unit/lib/classes/PluginManager.test.js @@ -989,32 +989,20 @@ describe('PluginManager', () => { /Command "deploy" cannot override an existing alias/ ); }); - - it('should log the alias when SLS_DEBUG is set', () => { - const consoleLogStub = sinon.stub(pluginManager.serverless.cli, 'log').returns(); - const synchronousPluginMockInstance = new SynchronousPluginMock(); - synchronousPluginMockInstance.commands.deploy.aliases = ['info']; - process.env.SLS_DEBUG = '*'; - pluginManager.loadCommands(synchronousPluginMockInstance); - expect(consoleLogStub).to.have.been.calledWith(' -> @info'); - }); }); describe('#loadHooks()', () => { let deprecatedPluginInstance; - let consoleLogStub; beforeEach(() => { deprecatedPluginInstance = new DeprecatedLifecycleEventsPluginMock(); pluginManager.deprecatedEvents = { 'deprecated:deprecated': 'new:new', }; - consoleLogStub = sinon.stub(pluginManager.serverless.cli, 'log').returns(); }); afterEach(() => { pluginManager.deprecatedEvents = {}; - pluginManager.serverless.cli.log.restore(); }); it('should replace deprecated events with the new ones', () => { @@ -1027,14 +1015,6 @@ describe('PluginManager', () => { expect(pluginManager.hooks['untouched:untouched'][0].pluginName).to.equal( 'DeprecatedLifecycleEventsPluginMock' ); - expect(consoleLogStub.calledOnce).to.equal(false); - }); - - it('should log a debug message about deprecated when using SLS_DEBUG', () => { - process.env.SLS_DEBUG = '1'; - pluginManager.loadHooks(deprecatedPluginInstance); - - expect(consoleLogStub.calledOnce).to.equal(true); }); }); diff --git a/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js b/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js index 91a9880a860..d75dbe81d07 100644 --- a/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js +++ b/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js @@ -1096,7 +1096,7 @@ describe('test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js', () => { expect(stdoutData).to.include( [ 'WARNING: Not authorized to perform: lambda:GetFunction for at least one of the lambda functions.', - ' Deployment will not be skipped even if service files did not change. ', + ' Deployment will not be skipped even if service files did not change.', ].join('') ); }); diff --git a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js index 46c67f46cc5..8cb9534b1d5 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js @@ -1095,123 +1095,6 @@ describe('#validate()', () => { expect(() => awsCompileApigEvents.validate()).to.throw(Error); }); - it('should show a warning message when using request / response config with HTTP-PROXY', () => { - awsCompileApigEvents.serverless.service.functions = { - first: { - events: [ - { - http: { - method: 'GET', - path: 'users/list', - integration: 'http-proxy', - request: { - uri: 'http://www.example.com', - template: { - 'template/1': '{ "stage" : "$context.stage" }', - 'template/2': '{ "httpMethod" : "$context.httpMethod" }', - }, - }, - response: { - template: "$input.path('$.foo')", - }, - }, - }, - ], - }, - }; - // initialize so we get the log method from the CLI in place - return serverless.init().then(() => { - const logStub = sinon.stub(serverless.cli, 'log'); - - awsCompileApigEvents.validate(); - - expect(logStub.calledTwice).to.be.equal(true); - expect(logStub.args[0][0].length).to.be.at.least(1); - }); - }); - - it('should not show a warning message when using request.parameter with HTTP-PROXY', () => { - awsCompileApigEvents.serverless.service.functions = { - first: { - events: [ - { - http: { - method: 'GET', - path: 'users/list', - integration: 'http-proxy', - request: { - uri: 'http://www.example.com', - parameters: { - querystrings: { - foo: true, - bar: false, - }, - paths: { - foo: true, - bar: false, - }, - headers: { - foo: true, - bar: false, - }, - }, - }, - }, - }, - ], - }, - }; - // initialize so we get the log method from the CLI in place - return serverless.init().then(() => { - const logStub = sinon.stub(serverless.cli, 'log'); - - awsCompileApigEvents.validate(); - - expect(logStub.called).to.be.equal(false); - }); - }); - - it('should remove non-parameter or uri request/response config with HTTP-PROXY', () => { - awsCompileApigEvents.serverless.service.functions = { - first: { - events: [ - { - http: { - method: 'GET', - path: 'users/list', - integration: 'http-proxy', - request: { - uri: 'http://www.example.com', - template: { - 'template/1': '{ "stage" : "$context.stage" }', - }, - parameters: { - paths: { - foo: true, - }, - }, - }, - response: {}, - }, - }, - ], - }, - }; - // initialize so we get the log method from the CLI in place - return serverless.init().then(() => { - // don't want to print the logs in this test - sinon.stub(serverless.cli, 'log'); - - const validated = awsCompileApigEvents.validate(); - expect(validated.events).to.be.an('Array').with.length(1); - expect(validated.events[0].http.response).to.equal(undefined); - expect(validated.events[0].http.request.uri).to.equal('http://www.example.com'); - expect(validated.events[0].http.request.parameters).to.deep.equal({ - 'method.request.path.foo': true, - }); - }); - }); - it('should support MOCK integration', () => { awsCompileApigEvents.serverless.service.functions = { first: { @@ -1253,40 +1136,6 @@ describe('#validate()', () => { expect(validated.events[0].http.async); }); - it('should show a warning message when using request / response config with LAMBDA-PROXY', () => { - awsCompileApigEvents.serverless.service.functions = { - first: { - events: [ - { - http: { - method: 'GET', - path: 'users/list', - integration: 'lambda-proxy', - request: { - template: { - 'template/1': '{ "stage" : "$context.stage" }', - 'template/2': '{ "httpMethod" : "$context.httpMethod" }', - }, - }, - response: { - template: "$input.path('$.foo')", - }, - }, - }, - ], - }, - }; - // initialize so we get the log method from the CLI in place - return serverless.init().then(() => { - const logStub = sinon.stub(serverless.cli, 'log'); - - awsCompileApigEvents.validate(); - - expect(logStub.calledTwice).to.be.equal(true); - expect(logStub.args[0][0].length).to.be.at.least(1); - }); - }); - it('should not show a warning message when using request.parameter with LAMBDA-PROXY', () => { awsCompileApigEvents.serverless.service.functions = { first: { diff --git a/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js b/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js index 808f2f3e42e..524c2a80456 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js @@ -1,7 +1,6 @@ 'use strict'; const chai = require('chai'); -const sandbox = require('sinon'); const AwsProvider = require('../../../../../../../../lib/plugins/aws/provider'); const AwsCompileCloudFrontEvents = require('../../../../../../../../lib/plugins/aws/package/compile/events/cloudFront'); const Serverless = require('../../../../../../../../lib/Serverless'); @@ -77,44 +76,9 @@ describe('AwsCompileCloudFrontEvents', () => { }, }; serverless.setProvider('aws', new AwsProvider(serverless, options)); - serverless.cli = { log: sandbox.spy() }; awsCompileCloudFrontEvents = new AwsCompileCloudFrontEvents(serverless, options); }); - describe('#constructor()', () => { - it('should use "before:remove:remove" hook to log a message before removing the service', () => { - serverless.processedInput.commands = ['remove']; - serverless.service.functions = { - first: { - events: [ - { - cloudFront: { - eventType: 'viewer-request', - origin: 's3://bucketname.s3.amazonaws.com/files', - }, - }, - ], - }, - }; - const awsCompileCloudFrontEventsRemoval = new AwsCompileCloudFrontEvents(serverless, options); - - awsCompileCloudFrontEventsRemoval.hooks['before:remove:remove'](); - expect(awsCompileCloudFrontEventsRemoval.serverless.cli.log).to.have.been.calledOnce; - expect(awsCompileCloudFrontEventsRemoval.serverless.cli.log.args[0][0]).to.include( - 'remove your Lambda@Edge functions' - ); - }); - }); - - describe('#logRemoveReminder()', () => { - it('should not log an info message if the users wants to remove the stack without a cloudFront event', () => { - serverless.processedInput.commands = ['remove']; - const awsCompileCloudFrontEventsRemoval = new AwsCompileCloudFrontEvents(serverless, options); - - expect(awsCompileCloudFrontEventsRemoval.serverless.cli.log).not.to.have.been.calledOnce; - }); - }); - describe('#validate()', () => { it('should throw if memorySize is greater than 128 for viewer-request or viewer-response functions', () => { awsCompileCloudFrontEvents.serverless.service.functions = { diff --git a/test/unit/lib/plugins/aws/provider.test.js b/test/unit/lib/plugins/aws/provider.test.js index 77fa349175a..a0fd91f4914 100644 --- a/test/unit/lib/plugins/aws/provider.test.js +++ b/test/unit/lib/plugins/aws/provider.test.js @@ -174,7 +174,14 @@ describe('AwsProvider', () => { .noCallThru() .load('../../../../../lib/plugins/aws/provider.js', { '../../aws/request': awsRequestStub, - '@serverless/utils/log': logStub, + '@serverless/utils/log': { + legacy: { + log: logStub, + }, + log: { + debug: sinon.stub(), + }, + }, }); awsProviderProxied = new AwsProviderProxyquired(serverless, options); });