From 3103edba39e112e2d7b200c697fa2f06dbc69fe9 Mon Sep 17 00:00:00 2001 From: Kunal Kundu Date: Wed, 28 Jul 2021 17:46:50 +0530 Subject: [PATCH 1/2] refactor: warn, exit and error utils from oclif command class --- src/commands/addons/config.js | 6 +- src/commands/addons/create.js | 10 +-- src/commands/addons/delete.js | 8 +- src/commands/api.js | 12 +-- src/commands/build/index.js | 22 +++--- src/commands/deploy.js | 73 ++++++++----------- src/commands/dev/exec.js | 4 +- src/commands/dev/index.js | 18 ++--- src/commands/functions/create.js | 33 ++++----- src/commands/functions/invoke.js | 13 ++-- src/commands/functions/list.js | 24 +++--- src/commands/functions/serve.js | 6 +- src/commands/link.js | 28 +++---- src/commands/lm/setup.js | 9 ++- src/commands/open/admin.js | 20 ++--- src/commands/open/site.js | 16 ++-- src/commands/sites/create.js | 8 +- src/commands/sites/delete.js | 18 ++--- src/commands/status/hooks.js | 20 ++--- src/commands/status/index.js | 26 +++---- src/lib/api.js | 4 +- src/lib/functions/form-submissions-handler.js | 7 +- src/lib/functions/registry.js | 20 ++--- src/lib/functions/server.js | 7 +- src/lib/functions/utils.js | 3 +- src/utils/addons/prepare.js | 26 +++---- src/utils/command-helpers.js | 16 ++++ src/utils/deploy/deploy-site.js | 2 +- src/utils/dev.js | 12 +-- src/utils/dot-env.js | 5 +- src/utils/edge-handlers.js | 14 ++-- src/utils/init/config-github.js | 5 +- src/utils/init/config-manual.js | 11 ++- src/utils/init/node-version.js | 3 +- src/utils/init/utils.js | 16 +--- src/utils/link/link-by-prompt.js | 36 ++++----- 36 files changed, 274 insertions(+), 287 deletions(-) diff --git a/src/commands/addons/config.js b/src/commands/addons/config.js index 628efeca3ea..734b13838c7 100644 --- a/src/commands/addons/config.js +++ b/src/commands/addons/config.js @@ -9,7 +9,7 @@ const generatePrompts = require('../../utils/addons/prompts') const render = require('../../utils/addons/render') const { requiredConfigValues, missingConfigValues, updateConfigValues } = require('../../utils/addons/validation') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, error } = require('../../utils/command-helpers') const { parseRawFlags } = require('../../utils/parse-raw-flags') class AddonsConfigCommand extends Command { @@ -61,7 +61,6 @@ class AddonsConfigCommand extends Command { siteId, instanceId: addon.id, api, - error: this.error, }) return false } @@ -132,13 +131,12 @@ class AddonsConfigCommand extends Command { siteId, instanceId: addon.id, api, - error: this.error, }) } } } -const update = async function ({ addonName, currentConfig, newConfig, siteId, instanceId, api, error }) { +const update = async function ({ addonName, currentConfig, newConfig, siteId, instanceId, api }) { const codeDiff = diffValues(currentConfig, newConfig) if (!codeDiff) { log('No changes, exiting early') diff --git a/src/commands/addons/create.js b/src/commands/addons/create.js index ecf68023b91..ae7de2c7eed 100644 --- a/src/commands/addons/create.js +++ b/src/commands/addons/create.js @@ -7,10 +7,10 @@ const generatePrompts = require('../../utils/addons/prompts') const render = require('../../utils/addons/render') const { requiredConfigValues, missingConfigValues, updateConfigValues } = require('../../utils/addons/validation') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, error } = require('../../utils/command-helpers') const { parseRawFlags } = require('../../utils/parse-raw-flags') -const createAddon = async ({ api, siteId, addonName, config, siteData, error }) => { +const createAddon = async ({ api, siteId, addonName, config, siteData }) => { try { const response = await api.createServiceInstance({ siteId, @@ -38,7 +38,7 @@ class AddonsCreateCommand extends Command { validation: ADDON_VALIDATION.NOT_EXISTS, }) - const { error, netlify } = this + const { netlify } = this const { api, site } = netlify const siteId = site.id @@ -71,7 +71,7 @@ class AddonsCreateCommand extends Command { return false } - await createAddon({ api, siteId, addonName, config: newConfig, siteData, error }) + await createAddon({ api, siteId, addonName, config: newConfig, siteData }) return false } @@ -104,7 +104,7 @@ class AddonsCreateCommand extends Command { } } - await createAddon({ api, siteId, addonName, config: configValues, siteData, error }) + await createAddon({ api, siteId, addonName, config: configValues, siteData }) } } diff --git a/src/commands/addons/delete.js b/src/commands/addons/delete.js index 78c404bc9e4..13177446561 100644 --- a/src/commands/addons/delete.js +++ b/src/commands/addons/delete.js @@ -3,7 +3,7 @@ const inquirer = require('inquirer') const { prepareAddonCommand, ADDON_VALIDATION } = require('../../utils/addons/prepare') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, exit, error } = require('../../utils/command-helpers') const { parseRawFlags } = require('../../utils/parse-raw-flags') class AddonsDeleteCommand extends Command { @@ -26,7 +26,7 @@ class AddonsDeleteCommand extends Command { default: false, }) if (!wantsToDelete) { - this.exit() + exit() } } @@ -37,8 +37,8 @@ class AddonsDeleteCommand extends Command { instanceId: addon.id, }) log(`Addon "${addonName}" deleted`) - } catch (error) { - this.error(error.message) + } catch (error_) { + error(error_.message) } } } diff --git a/src/commands/api.js b/src/commands/api.js index af13f3ad70a..de0943792b1 100644 --- a/src/commands/api.js +++ b/src/commands/api.js @@ -5,7 +5,7 @@ const { methods } = require('netlify') const { isEmptyCommand } = require('../utils/check-command-inputs') const Command = require('../utils/command') -const { log, logJson } = require('../utils/command-helpers') +const { log, logJson, error, exit } = require('../utils/command-helpers') class APICommand extends Command { async run() { @@ -25,15 +25,15 @@ class APICommand extends Command { log() log('Above is a list of available API methods') log(`To run a method use "${chalk.cyanBright('netlify api methodName')}"`) - this.exit() + exit() } if (!apiMethod) { - this.error(`You must provide an API method. Run "netlify api --list" to see available methods`) + error(`You must provide an API method. Run "netlify api --list" to see available methods`) } if (!api[apiMethod] || typeof api[apiMethod] !== 'function') { - this.error(`"${apiMethod}"" is not a valid api method. Run "netlify api --list" to see available methods`) + error(`"${apiMethod}"" is not a valid api method. Run "netlify api --list" to see available methods`) } let payload @@ -45,8 +45,8 @@ class APICommand extends Command { try { const apiResponse = await api[apiMethod](payload) logJson(apiResponse) - } catch (error) { - this.error(error) + } catch (error_) { + error(error_) } } } diff --git a/src/commands/build/index.js b/src/commands/build/index.js index 5563c708529..342c5ef9d97 100644 --- a/src/commands/build/index.js +++ b/src/commands/build/index.js @@ -2,7 +2,7 @@ const { flags: flagsLib } = require('@oclif/command') const { getBuildOptions, runBuild } = require('../../lib/build') const Command = require('../../utils/command') -const { getToken } = require('../../utils/command-helpers') +const { error, exit, getToken } = require('../../utils/command-helpers') class BuildCommand extends Command { // Run Netlify Build @@ -19,23 +19,21 @@ class BuildCommand extends Command { token, flags, }) - if (!flags.offline) { - this.checkOptions(options) + checkOptions(options) } - const { exitCode } = await runBuild(options) - this.exit(exitCode) + exit(exitCode) } +} - checkOptions({ cachedConfig: { siteInfo = {} }, token }) { - if (!siteInfo.id) { - this.error('Could not find the site ID. Please run netlify link.', { exit: 1 }) - } +const checkOptions = ({ cachedConfig: { siteInfo = {} }, token }) => { + if (!siteInfo.id) { + error('Could not find the site ID. Please run netlify link.', { exit: 1 }) + } - if (!token) { - this.error('Could not find the access token. Please run netlify login.', { exit: 1 }) - } + if (!token) { + error('Could not find the access token. Please run netlify login.', { exit: 1 }) } } diff --git a/src/commands/deploy.js b/src/commands/deploy.js index 89340943872..f7d6df5116f 100644 --- a/src/commands/deploy.js +++ b/src/commands/deploy.js @@ -15,7 +15,7 @@ const { normalizeFunctionsConfig } = require('../lib/functions/config') const { getLogMessage } = require('../lib/log') const { startSpinner, stopSpinner } = require('../lib/spinner') const Command = require('../utils/command') -const { log, logJson, getToken } = require('../utils/command-helpers') +const { log, logJson, warn, exit, error, getToken } = require('../utils/command-helpers') const { deploySite } = require('../utils/deploy/deploy-site') const { deployEdgeHandlers } = require('../utils/edge-handlers') const { getInternalFunctionsDir } = require('../utils/functions') @@ -27,7 +27,7 @@ const SitesCreateCommand = require('./sites/create') const DEFAULT_DEPLOY_TIMEOUT = 1.2e6 -const triggerDeploy = async ({ api, siteId, siteData, error }) => { +const triggerDeploy = async ({ api, siteId, siteData }) => { try { const siteBuild = await api.createSiteBuild({ siteId }) log( @@ -70,7 +70,7 @@ const getDeployFolder = async ({ flags, config, site, siteData }) => { return deployFolder } -const validateDeployFolder = async ({ deployFolder, error }) => { +const validateDeployFolder = async ({ deployFolder }) => { let stat try { stat = await statAsync(deployFolder) @@ -106,7 +106,7 @@ const getFunctionsFolder = ({ flags, config, site, siteData }) => { return functionsFolder } -const validateFunctionsFolder = async ({ functionsFolder, error }) => { +const validateFunctionsFolder = async ({ functionsFolder }) => { let stat if (functionsFolder) { // we used to hard error if functions folder is specified but doesn't exist @@ -133,9 +133,9 @@ const validateFunctionsFolder = async ({ functionsFolder, error }) => { return stat } -const validateFolders = async ({ deployFolder, functionsFolder, error }) => { - const deployFolderStat = await validateDeployFolder({ deployFolder, error }) - const functionsFolderStat = await validateFunctionsFolder({ functionsFolder, error }) +const validateFolders = async ({ deployFolder, functionsFolder }) => { + const deployFolderStat = await validateDeployFolder({ deployFolder }) + const functionsFolderStat = await validateFunctionsFolder({ functionsFolder }) return { deployFolderStat, functionsFolderStat } } @@ -168,7 +168,7 @@ const SEC_TO_MILLISEC = 1e3 // 100 bytes const SYNC_FILE_LIMIT = 1e2 -const prepareProductionDeploy = async ({ siteData, api, exit }) => { +const prepareProductionDeploy = async ({ siteData, api }) => { if (isObject(siteData.published_deploy) && siteData.published_deploy.locked) { log(`\n${NETLIFYDEVERR} Deployments are "locked" for production context of this site\n`) const { unlockChoice } = await inquirer.prompt([ @@ -193,34 +193,34 @@ const hasErrorMessage = (actual, expected) => { return false } -const getJsonErrorMessage = (error) => get(error, 'json.message', '') +const getJsonErrorMessage = (error_) => get(error_, 'json.message', '') -const reportDeployError = ({ error, warn, failAndExit }) => { +const reportDeployError = ({ error_, failAndExit }) => { switch (true) { - case error.name === 'JSONHTTPError': { - const message = getJsonErrorMessage(error) + case error_.name === 'JSONHTTPError': { + const message = getJsonErrorMessage(error_) if (hasErrorMessage(message, 'Background Functions not allowed by team plan')) { return failAndExit(`\n${getLogMessage('functions.backgroundNotSupported')}`) } - warn(`JSONHTTPError: ${message} ${error.status}`) - warn(`\n${JSON.stringify(error, null, ' ')}\n`) - failAndExit(error) + warn(`JSONHTTPError: ${message} ${error_.status}`) + warn(`\n${JSON.stringify(error_, null, ' ')}\n`) + failAndExit(error_) return } - case error.name === 'TextHTTPError': { - warn(`TextHTTPError: ${error.status}`) - warn(`\n${error}\n`) - failAndExit(error) + case error_.name === 'TextHTTPError': { + warn(`TextHTTPError: ${error_.status}`) + warn(`\n${error_}\n`) + failAndExit(error_) return } - case hasErrorMessage(error.message, 'Invalid filename'): { - warn(error.message) - failAndExit(error) + case hasErrorMessage(error_.message, 'Invalid filename'): { + warn(error_.message) + failAndExit(error_) return } default: { - warn(`\n${JSON.stringify(error, null, ' ')}\n`) - failAndExit(error) + warn(`\n${JSON.stringify(error_, null, ' ')}\n`) + failAndExit(error_) } } } @@ -237,15 +237,12 @@ const runDeploy = async ({ functionsConfig, functionsFolder, alias, - warn, - error, - exit, }) => { let results let deployId try { if (deployToProduction) { - await prepareProductionDeploy({ siteData, api, exit }) + await prepareProductionDeploy({ siteData, api }) } else { log('Deploying to draft URL...') } @@ -261,8 +258,6 @@ const runDeploy = async ({ deployId, api, silent, - error, - warn, }) const internalFunctionsFolder = await getInternalFunctionsDir({ base: site.root }) @@ -281,14 +276,13 @@ const runDeploy = async ({ // pass an existing deployId to update deployId, filter: getDeployFilesFilter({ site, deployFolder }), - warn, rootDir: site.root, }) } catch (error_) { if (deployId) { - await cancelDeploy({ api, deployId, warn }) + await cancelDeploy({ api, deployId }) } - reportDeployError({ error: error_, warn, failAndExit: error }) + reportDeployError({ error_, failAndExit: error }) } const siteUrl = results.deploy.ssl_url || results.deploy.url @@ -317,12 +311,12 @@ const handleBuild = async ({ context, flags }) => { }) const { exitCode, newConfig } = await runBuild(options) if (exitCode !== 0) { - context.exit(exitCode) + exit(exitCode) } return newConfig } -const printResults = ({ flags, results, deployToProduction, exit }) => { +const printResults = ({ flags, results, deployToProduction }) => { const msgData = { Logs: `${results.logsUrl}`, 'Unique Deploy URL': results.deployUrl, @@ -369,7 +363,6 @@ const printResults = ({ flags, results, deployToProduction, exit }) => { class DeployCommand extends Command { async run() { const { flags } = this.parse(DeployCommand) - const { warn, error, exit } = this const { api, site } = this.netlify const alias = flags.alias || flags.branch @@ -426,7 +419,7 @@ class DeployCommand extends Command { const deployToProduction = flags.prod || (flags.prodIfUnlocked && !siteData.published_deploy.locked) if (flags.trigger) { - return triggerDeploy({ api, siteId, siteData, error }) + return triggerDeploy({ api, siteId, siteData }) } const newConfig = await handleBuild({ context: this, flags }) @@ -447,7 +440,6 @@ class DeployCommand extends Command { const { functionsFolderStat } = await validateFolders({ deployFolder, functionsFolder, - error, }) const functionsConfig = normalizeFunctionsConfig({ functionsConfig: config.functions, projectRoot: site.root }) const results = await runDeploy({ @@ -463,12 +455,9 @@ class DeployCommand extends Command { // pass undefined functionsFolder if doesn't exist functionsFolder: functionsFolderStat && functionsFolder, alias, - warn, - error, - exit, }) - printResults({ flags, results, deployToProduction, exit }) + printResults({ flags, results, deployToProduction }) if (flags.open) { const urlToOpen = deployToProduction ? results.siteUrl : results.deployUrl diff --git a/src/commands/dev/exec.js b/src/commands/dev/exec.js index 6ed36565131..39b760fdb0a 100644 --- a/src/commands/dev/exec.js +++ b/src/commands/dev/exec.js @@ -10,9 +10,9 @@ class ExecCommand extends Command { } async run() { - const { warn, netlify } = this + const { netlify } = this const { cachedConfig, site } = netlify - await injectEnvVariables({ env: cachedConfig.env, site, warn }) + await injectEnvVariables({ env: cachedConfig.env, site }) execa(this.argv[0], this.argv.slice(1), { stdio: 'inherit', diff --git a/src/commands/dev/index.js b/src/commands/dev/index.js index 5c44bb566f0..bb4c17d9234 100644 --- a/src/commands/dev/index.js +++ b/src/commands/dev/index.js @@ -12,7 +12,7 @@ const waitPort = require('wait-port') const { startFunctionsServer } = require('../../lib/functions/server') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, warn, exit } = require('../../utils/command-helpers') const { detectServerSettings } = require('../../utils/detect-server-settings') const { getSiteInformation, injectEnvVariables } = require('../../utils/dev') const { startLiveTunnel } = require('../../utils/live-tunnel') @@ -53,7 +53,7 @@ const isNonExistingCommandError = ({ command, error }) => { ) } -const startFrameworkServer = async function ({ settings, exit }) { +const startFrameworkServer = async function ({ settings }) { if (settings.useStaticServer) { return await startStaticServer({ settings }) } @@ -105,7 +105,7 @@ const startFrameworkServer = async function ({ settings, exit }) { if (!open) { throw new Error(`Timed out waiting for port '${settings.frameworkPort}' to be open`) } - } catch (error) { + } catch (_) { log(NETLIFYDEVERR, `Netlify Dev could not connect to localhost:${settings.frameworkPort}.`) log(NETLIFYDEVERR, `Please make sure your framework server is running on port ${settings.frameworkPort}`) exit(1) @@ -115,7 +115,7 @@ const startFrameworkServer = async function ({ settings, exit }) { // 10 minutes const FRAMEWORK_PORT_TIMEOUT = 6e5 -const startProxyServer = async ({ flags, settings, site, exit, addonsUrls }) => { +const startProxyServer = async ({ flags, settings, site, addonsUrls }) => { let url if (flags.edgeHandlers || flags.trafficMesh) { url = await startForwardProxy({ @@ -175,7 +175,7 @@ class DevCommand extends Command { async run() { log(`${NETLIFYDEV}`) - const { error: errorExit, warn, exit } = this + const { error: errorExit } = this const { flags } = this.parse(DevCommand) const { api, site, config, siteInfo } = this.netlify config.dev = { ...config.dev } @@ -194,12 +194,11 @@ class DevCommand extends Command { ) } - await injectEnvVariables({ env: this.netlify.cachedConfig.env, site, warn }) + await injectEnvVariables({ env: this.netlify.cachedConfig.env, site }) const { addonsUrls, siteUrl, capabilities, timeouts } = await getSiteInformation({ flags, api, site, - warn, error: errorExit, siteInfo, }) @@ -218,15 +217,14 @@ class DevCommand extends Command { config, settings, site, - warn, errorExit, siteUrl, capabilities, timeouts, }) - await startFrameworkServer({ settings, exit }) + await startFrameworkServer({ settings }) - let url = await startProxyServer({ flags, settings, site, exit, addonsUrls }) + let url = await startProxyServer({ flags, settings, site, addonsUrls }) const liveTunnelUrl = await handleLiveTunnel({ flags, site, api, settings }) url = liveTunnelUrl || url diff --git a/src/commands/functions/create.js b/src/commands/functions/create.js index e566fd68fa4..573220be034 100644 --- a/src/commands/functions/create.js +++ b/src/commands/functions/create.js @@ -16,7 +16,7 @@ const ora = require('ora') const { mkdirRecursiveSync } = require('../../lib/fs') const { getSiteData, getAddons, getCurrentAddon } = require('../../utils/addons/prepare') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, error } = require('../../utils/command-helpers') const { injectEnvVariables } = require('../../utils/dev') const { NETLIFYDEVLOG, NETLIFYDEVWARN, NETLIFYDEVERR } = require('../../utils/logo') const { readRepoURL, validateRepoURL } = require('../../utils/read-repo-url') @@ -203,7 +203,7 @@ const ensureFunctionDirExists = async function (context) { log(`${NETLIFYDEVLOG} functions directory not specified in netlify.toml or UI settings`) if (!siteId) { - context.error(`${NETLIFYDEVERR} No site id found, please run inside a site directory or \`netlify link\``) + error(`${NETLIFYDEVERR} No site id found, please run inside a site directory or \`netlify link\``) } const { functionsDir } = await inquirer.prompt([ @@ -231,7 +231,7 @@ const ensureFunctionDirExists = async function (context) { }) log(`${NETLIFYDEVLOG} functions directory ${chalk.magenta.inverse(functionsDirHolder)} updated in site settings`) - } catch (error) { + } catch (_) { throw error('Error updating site settings') } } @@ -267,7 +267,7 @@ const downloadFromURL = async function (context, flags, args, functionsDir) { try { mkdirRecursiveSync(fnFolder) - } catch (error) { + } catch (_) { // Ignore } await Promise.all( @@ -277,8 +277,8 @@ const downloadFromURL = async function (context, flags, args, functionsDir) { const finalName = path.basename(name, '.js') === functionName ? `${nameToUse}.js` : name const dest = fs.createWriteStream(path.join(fnFolder, finalName)) res.body.pipe(dest) - } catch (error) { - throw new Error(`Error while retrieving ${downloadUrl} ${error}`) + } catch (error_) { + throw new Error(`Error while retrieving ${downloadUrl} ${error_}`) } }), ) @@ -327,9 +327,9 @@ const scaffoldFromTemplate = async function (context, flags, args, functionsDir) flags.url = chosenurl.trim() try { await downloadFromURL(context, flags, args, functionsDir) - } catch (error) { - context.error(`$${NETLIFYDEVERR} Error downloading from URL: ${flags.url}`) - context.error(error) + } catch (error_) { + error(`$${NETLIFYDEVERR} Error downloading from URL: ${flags.url}`) + error(error_) process.exit(1) } } else if (chosentemplate === 'report') { @@ -358,7 +358,7 @@ const scaffoldFromTemplate = async function (context, flags, args, functionsDir) const createdFiles = await copy(pathToTemplate, functionPath, vars) createdFiles.forEach((filePath) => { if (filePath.endsWith('.netlify-function-template.js')) return - context.log(`${NETLIFYDEVLOG} ${chalk.greenBright('Created')} ${filePath}`) + log(`${NETLIFYDEVLOG} ${chalk.greenBright('Created')} ${filePath}`) fs.chmodSync(path.resolve(filePath), TEMPLATE_PERMISSIONS) if (filePath.includes('package.json')) hasPackageJSON = true }) @@ -385,7 +385,7 @@ const scaffoldFromTemplate = async function (context, flags, args, functionsDir) const TEMPLATE_PERMISSIONS = 0o777 -const createFunctionAddon = async function ({ api, addons, siteId, addonName, siteData, error }) { +const createFunctionAddon = async function ({ api, addons, siteId, addonName, siteData }) { try { const addon = getCurrentAddon({ addons, addonName }) if (addon && addon.id) { @@ -405,9 +405,9 @@ const createFunctionAddon = async function ({ api, addons, siteId, addonName, si } const injectEnvVariablesFromContext = async ({ context }) => { - const { warn, netlify } = context + const { netlify } = context const { cachedConfig, site } = netlify - await injectEnvVariables({ env: cachedConfig.env, site, warn }) + await injectEnvVariables({ env: cachedConfig.env, site }) } const handleOnComplete = async ({ context, onComplete }) => { @@ -444,7 +444,6 @@ const installAddons = async function (context, functionAddons, fnPath) { return } - const { error } = context const { api, site } = context.netlify const siteId = site.id if (!siteId) { @@ -453,10 +452,7 @@ const installAddons = async function (context, functionAddons, fnPath) { } log(`${NETLIFYDEVLOG} checking Netlify APIs...`) - const [siteData, siteAddons] = await Promise.all([ - getSiteData({ api, siteId, error }), - getAddons({ api, siteId, error }), - ]) + const [siteData, siteAddons] = await Promise.all([getSiteData({ api, siteId }), getAddons({ api, siteId })]) const arr = functionAddons.map(async ({ addonName, addonDidInstall }) => { log(`${NETLIFYDEVLOG} installing addon: ${chalk.yellow.inverse(addonName)}`) @@ -467,7 +463,6 @@ const installAddons = async function (context, functionAddons, fnPath) { siteId, addonName, siteData, - error, }) await handleAddonDidInstall({ addonCreated, addonDidInstall, context, fnPath }) diff --git a/src/commands/functions/invoke.js b/src/commands/functions/invoke.js index 6e650f45edc..64105dc9826 100644 --- a/src/commands/functions/invoke.js +++ b/src/commands/functions/invoke.js @@ -8,6 +8,7 @@ const inquirer = require('inquirer') const fetch = require('node-fetch') const Command = require('../../utils/command') +const { error } = require('../../utils/command-helpers') const { getFunctions, BACKGROUND } = require('../../utils/get-functions') const { NETLIFYDEVWARN } = require('../../utils/logo') @@ -38,7 +39,7 @@ class FunctionsInvokeCommand extends Command { const functionsDir = flags.functions || (config.dev && config.dev.functions) || config.functionsDirectory if (typeof functionsDir === 'undefined') { - this.error('functions directory is undefined, did you forget to set it in netlify.toml?') + error('functions directory is undefined, did you forget to set it in netlify.toml?') } if (!flags.port) @@ -126,8 +127,8 @@ class FunctionsInvokeCommand extends Command { ) const data = await response.text() console.log(data) - } catch (error) { - this.error(`Ran into an error invoking your function: ${error.message}`) + } catch (error_) { + error(`Ran into an error invoking your function: ${error_.message}`) } } } @@ -154,8 +155,8 @@ const processPayloadFromFlag = function (payloadString) { // eslint-disable-next-line node/global-require, import/no-dynamic-require payload = require(payloadpath) return payload - } catch (error) { - console.error(error) + } catch (error_) { + console.error(error_) } } // case 3: invalid string, invalid path @@ -270,7 +271,7 @@ const tryParseJSON = function (jsonString) { if (parsedValue && typeof parsedValue === 'object') { return parsedValue } - } catch (error) {} + } catch (_) {} return false } diff --git a/src/commands/functions/list.js b/src/commands/functions/list.js index aa4b5742476..04a1502e385 100644 --- a/src/commands/functions/list.js +++ b/src/commands/functions/list.js @@ -4,7 +4,7 @@ const { flags: flagsLib } = require('@oclif/command') const AsciiTable = require('ascii-table') const Command = require('../../utils/command') -const { log, logJson } = require('../../utils/command-helpers') +const { log, logJson, warn, error, exit } = require('../../utils/command-helpers') const { getFunctionsDir } = require('../../utils/functions') const { getFunctions } = require('../../utils/get-functions') @@ -18,23 +18,23 @@ class FunctionsListCommand extends Command { // copied from `netlify status` const siteId = site.id if (!siteId) { - this.warn('Did you run `netlify link` yet?') - this.error(`You don't appear to be in a folder that is linked to a site`) + warn('Did you run `netlify link` yet?') + error(`You don't appear to be in a folder that is linked to a site`) } let siteData try { siteData = await api.getSite({ siteId }) - } catch (error) { + } catch (error_) { // unauthorized - if (error.status === 401) { - this.warn(`Log in with a different account or re-link to a site you have permission for`) - this.error(`Not authorized to view the currently linked site (${siteId})`) + if (error_.status === 401) { + warn(`Log in with a different account or re-link to a site you have permission for`) + error(`Not authorized to view the currently linked site (${siteId})`) } // missing - if (error.status === 404) { - this.error(`The site this folder is linked to can't be found`) + if (error_.status === 404) { + error(`The site this folder is linked to can't be found`) } - this.error(error) + error(error_) } const deploy = siteData.published_deploy || {} const deployedFunctions = deploy.available_functions || [] @@ -53,12 +53,12 @@ class FunctionsListCommand extends Command { if (normalizedFunctions.length === 0) { log(`No functions found in ${functionsDir}`) - this.exit() + exit() } if (flags.json) { logJson(normalizedFunctions) - this.exit() + exit() } // Make table diff --git a/src/commands/functions/serve.js b/src/commands/functions/serve.js index e56d801ef36..f0bc6e0be89 100644 --- a/src/commands/functions/serve.js +++ b/src/commands/functions/serve.js @@ -13,18 +13,17 @@ class FunctionsServeCommand extends Command { async run() { const { flags } = this.parse(FunctionsServeCommand) - const { error: errorExit, warn, netlify } = this + const { error: errorExit, netlify } = this const { api, site, config, siteInfo } = netlify const functionsDir = getFunctionsDir({ flags, config }, join('netlify', 'functions')) - await injectEnvVariables({ env: this.netlify.cachedConfig.env, site, warn }) + await injectEnvVariables({ env: this.netlify.cachedConfig.env, site }) const { siteUrl, capabilities, timeouts } = await getSiteInformation({ flags, api, site, - warn, error: errorExit, siteInfo, }) @@ -39,7 +38,6 @@ class FunctionsServeCommand extends Command { config, settings: { functions: functionsDir, functionsPort }, site, - warn, errorExit, siteUrl, capabilities, diff --git a/src/commands/link.js b/src/commands/link.js index 26628ff36f3..6dbd2d34db9 100644 --- a/src/commands/link.js +++ b/src/commands/link.js @@ -6,7 +6,7 @@ const chalk = require('chalk') const { listSites } = require('../lib/api') const Command = require('../utils/command') -const { log } = require('../utils/command-helpers') +const { log, error, exit } = require('../utils/command-helpers') const ensureNetlifyIgnore = require('../utils/gitignore') const linkPrompt = require('../utils/link/link-by-prompt') const { track } = require('../utils/telemetry') @@ -26,7 +26,7 @@ class LinkCommand extends Command { let siteData try { siteData = await api.getSite({ siteId }) - } catch (error) { + } catch (_) { // silent api error } @@ -37,7 +37,7 @@ class LinkCommand extends Command { if (siteId && !siteData) { console.log(`"${siteId}" was not found in your Netlify account.`) console.log(`Please double check your siteID and which account you are logged into via \`netlify status\`.`) - return this.exit() + return exit() } // If already linked to site. exit and prompt for unlink @@ -52,11 +52,11 @@ class LinkCommand extends Command { if (flags.id) { try { siteData = await api.getSite({ site_id: flags.id }) - } catch (error) { - if (error.status === 404) { - this.error(new Error(`Site id ${flags.id} not found`)) + } catch (error_) { + if (error_.status === 404) { + error(new Error(`Site id ${flags.id} not found`)) } else { - this.error(error) + error(error_) } } @@ -70,7 +70,7 @@ class LinkCommand extends Command { kind: 'byId', }) - return this.exit() + return exit() } if (flags.name) { @@ -83,16 +83,16 @@ class LinkCommand extends Command { filter: 'all', }, }) - } catch (error) { - if (error.status === 404) { - this.error(new Error(`${flags.name} not found`)) + } catch (error_) { + if (error_.status === 404) { + error(new Error(`${flags.name} not found`)) } else { - this.error(error) + error(error_) } } if (results.length === 0) { - this.error(new Error(`No sites found named ${flags.name}`)) + error(new Error(`No sites found named ${flags.name}`)) } const [firstSiteData] = results state.set('siteId', firstSiteData.id) @@ -105,7 +105,7 @@ class LinkCommand extends Command { kind: 'byName', }) - return this.exit() + return exit() } siteData = await linkPrompt(this, flags) diff --git a/src/commands/lm/setup.js b/src/commands/lm/setup.js index f45cb29c212..4976c2ba6cc 100644 --- a/src/commands/lm/setup.js +++ b/src/commands/lm/setup.js @@ -3,6 +3,7 @@ const execa = require('execa') const Listr = require('listr') const Command = require('../../utils/command') +const { error } = require('../../utils/command-helpers') const { installPlatform } = require('../../utils/lm/install') const { checkHelperVersion } = require('../../utils/lm/requirements') const { printBanner } = require('../../utils/lm/ui') @@ -14,7 +15,7 @@ const installHelperIfMissing = async function ({ force }) { if (!version) { installHelper = true } - } catch (error) { + } catch (_) { installHelper = true } @@ -37,9 +38,9 @@ const provisionService = async function (siteId, api) { addon: addonName, body: {}, }) - } catch (error) { + } catch (error_) { // error is JSONHTTPError - throw new Error(error.json.error) + throw new Error(error_.json.error) } } @@ -62,7 +63,7 @@ class LmSetupCommand extends Command { try { helperInstalled = await installHelperIfMissing({ force: flags['force-install'] }) } catch (error_) { - this.error(error_) + error(error_) } } diff --git a/src/commands/open/admin.js b/src/commands/open/admin.js index c1724b59731..c3c33274dae 100644 --- a/src/commands/open/admin.js +++ b/src/commands/open/admin.js @@ -1,5 +1,5 @@ const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, warn, error, exit } = require('../../utils/command-helpers') const openBrowser = require('../../utils/open-browser') class OpenAdminCommand extends Command { @@ -11,7 +11,7 @@ class OpenAdminCommand extends Command { const siteId = site.id if (!siteId) { - this.warn(`No Site ID found in current directory. + warn(`No Site ID found in current directory. Run \`netlify link\` to connect to this folder to a site`) return false } @@ -21,26 +21,26 @@ Run \`netlify link\` to connect to this folder to a site`) siteData = await api.getSite({ siteId }) log(`Opening "${siteData.name}" site admin UI:`) log(`> ${siteData.admin_url}`) - } catch (error) { + } catch (error_) { // unauthorized - if (error.status === 401) { - this.warn(`Log in with a different account or re-link to a site you have permission for`) - this.error(`Not authorized to view the currently linked site (${siteId})`) + if (error_.status === 401) { + warn(`Log in with a different account or re-link to a site you have permission for`) + error(`Not authorized to view the currently linked site (${siteId})`) } // site not found - if (error.status === 404) { + if (error_.status === 404) { log() log('Please double check this ID and verify you are logged in with the correct account') log() log('To fix this, run `netlify unlink` then `netlify link` to reconnect to the correct site ID') log() - this.error(`Site "${siteId}" not found in account`) + error(`Site "${siteId}" not found in account`) } - this.error(error) + error(error_) } await openBrowser({ url: siteData.admin_url }) - this.exit() + exit() } } diff --git a/src/commands/open/site.js b/src/commands/open/site.js index d47d83174cc..02f75e993bd 100644 --- a/src/commands/open/site.js +++ b/src/commands/open/site.js @@ -1,5 +1,5 @@ const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, warn, error, exit } = require('../../utils/command-helpers') const openBrowser = require('../../utils/open-browser') class OpenAdminCommand extends Command { @@ -10,7 +10,7 @@ class OpenAdminCommand extends Command { const siteId = site.id if (!siteId) { - this.warn(`No Site ID found in current directory. + warn(`No Site ID found in current directory. Run \`netlify link\` to connect to this folder to a site`) return false } @@ -22,17 +22,17 @@ Run \`netlify link\` to connect to this folder to a site`) url = siteData.ssl_url || siteData.url log(`Opening "${siteData.name}" site url:`) log(`> ${url}`) - } catch (error) { + } catch (error_) { // unauthorized - if (error.status === 401) { - this.warn(`Log in with a different account or re-link to a site you have permission for`) - this.error(`Not authorized to view the currently linked site (${siteId})`) + if (error_.status === 401) { + warn(`Log in with a different account or re-link to a site you have permission for`) + error(`Not authorized to view the currently linked site (${siteId})`) } - this.error(error) + error(error_) } await openBrowser({ url }) - this.exit() + exit() } } diff --git a/src/commands/sites/create.js b/src/commands/sites/create.js index 8210a0cba73..b31df125fb7 100644 --- a/src/commands/sites/create.js +++ b/src/commands/sites/create.js @@ -8,7 +8,7 @@ const prettyjson = require('prettyjson') const { v4: uuidv4 } = require('uuid') const Command = require('../../utils/command') -const { log, logJson } = require('../../utils/command-helpers') +const { log, logJson, warn, error } = require('../../utils/command-helpers') const { getRepoData } = require('../../utils/get-repo-data') const { configureRepo } = require('../../utils/init/config') const { track } = require('../../utils/telemetry') @@ -93,12 +93,12 @@ class SitesCreateCommand extends Command { accountSlug, body, }) - } catch (error) { + } catch (error_) { if (error.status === 422) { - this.warn(`${name}.netlify.app already exists. Please try a different slug.`) + warn(`${name}.netlify.app already exists. Please try a different slug.`) await inputSiteName() } else { - this.error(`createSiteInTeam error: ${error.status}: ${error.message}`) + error(`createSiteInTeam error: ${error_.status}: ${error_.message}`) } } } diff --git a/src/commands/sites/delete.js b/src/commands/sites/delete.js index c15d292d1d0..e8a956eb4f4 100644 --- a/src/commands/sites/delete.js +++ b/src/commands/sites/delete.js @@ -3,7 +3,7 @@ const chalk = require('chalk') const inquirer = require('inquirer') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, error } = require('../../utils/command-helpers') const { parseRawFlags } = require('../../utils/parse-raw-flags') class SitesDeleteCommand extends Command { @@ -22,14 +22,14 @@ class SitesDeleteCommand extends Command { let siteData try { siteData = await api.getSite({ siteId }) - } catch (error) { - if (error.status === 404) { - this.error(`No site with id ${siteId} found. Please verify the siteId & try again.`) + } catch (error_) { + if (error_.status === 404) { + error(`No site with id ${siteId} found. Please verify the siteId & try again.`) } } if (!siteData) { - this.error(`Unable to process site`) + error(`Unable to process site`) } const rawFlags = parseRawFlags(raw) @@ -79,11 +79,11 @@ class SitesDeleteCommand extends Command { try { await api.deleteSite({ site_id: siteId }) - } catch (error) { - if (error.status === 404) { - this.error(`No site with id ${siteId} found. Please verify the siteId & try again.`) + } catch (error_) { + if (error_.status === 404) { + error(`No site with id ${siteId} found. Please verify the siteId & try again.`) } else { - this.error(`Delete Site error: ${error.status}: ${error.message}`) + error(`Delete Site error: ${error_.status}: ${error_.message}`) } } log(`Site "${siteId}" successfully deleted!`) diff --git a/src/commands/status/hooks.js b/src/commands/status/hooks.js index 0f8449cc4e9..83d92a3ce73 100644 --- a/src/commands/status/hooks.js +++ b/src/commands/status/hooks.js @@ -2,7 +2,7 @@ const { get } = require('dot-prop') const prettyjson = require('prettyjson') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, warn, error } = require('../../utils/command-helpers') class StatusHooksCommand extends Command { async run() { @@ -12,24 +12,24 @@ class StatusHooksCommand extends Command { const siteId = site.id if (!siteId) { - this.warn('Did you run `netlify link` yet?') - this.error(`You don't appear to be in a folder that is linked to a site`) + warn('Did you run `netlify link` yet?') + error(`You don't appear to be in a folder that is linked to a site`) } let siteData try { siteData = await api.getSite({ siteId }) - } catch (error) { + } catch (error_) { // unauthorized - if (error.status === 401) { - this.warn(`Log in with a different account or re-link to a site you have permission for`) - this.error(`Not authorized to view the currently linked site (${siteId})`) + if (error_.status === 401) { + warn(`Log in with a different account or re-link to a site you have permission for`) + error(`Not authorized to view the currently linked site (${siteId})`) } // missing - if (error.status === 404) { - this.error(`The site this folder is linked to can't be found`) + if (error_.status === 404) { + error(`The site this folder is linked to can't be found`) } - this.error(error) + error(error_) } const ntlHooks = await api.listHooksBySiteId({ siteId: siteData.id }) diff --git a/src/commands/status/index.js b/src/commands/status/index.js index 47a0bd434d1..1b8e6e9f88b 100644 --- a/src/commands/status/index.js +++ b/src/commands/status/index.js @@ -4,7 +4,7 @@ const clean = require('clean-deep') const prettyjson = require('prettyjson') const Command = require('../../utils/command') -const { log, logJson, getToken } = require('../../utils/command-helpers') +const { log, logJson, warn, error, exit, getToken } = require('../../utils/command-helpers') class StatusCommand extends Command { async run() { @@ -18,7 +18,7 @@ class StatusCommand extends Command { log(`Not logged in. Please log in to see site status.`) log() log('Login with "netlify login" command') - this.exit() + exit() } const siteId = site.id @@ -32,9 +32,9 @@ class StatusCommand extends Command { try { ;[accounts, user] = await Promise.all([api.listAccountsForUser(), api.getCurrentUser()]) - } catch (error) { - if (error.status === 401) { - this.error( + } catch (error_) { + if (error_.status === 401) { + error( 'Your session has expired. Please try to re-authenticate by running `netlify logout` and `netlify login`.', ) } @@ -59,23 +59,23 @@ class StatusCommand extends Command { log(prettyjson.render(cleanAccountData)) if (!siteId) { - this.warn('Did you run `netlify link` yet?') - this.error(`You don't appear to be in a folder that is linked to a site`) + warn('Did you run `netlify link` yet?') + error(`You don't appear to be in a folder that is linked to a site`) } let siteData try { siteData = await api.getSite({ siteId }) - } catch (error) { + } catch (error_) { // unauthorized if (error.status === 401) { - this.warn(`Log in with a different account or re-link to a site you have permission for`) - this.error(`Not authorized to view the currently linked site (${siteId})`) + warn(`Log in with a different account or re-link to a site you have permission for`) + error(`Not authorized to view the currently linked site (${siteId})`) } // missing - if (error.status === 404) { - this.error(`The site this folder is linked to can't be found`) + if (error_.status === 404) { + error(`The site this folder is linked to can't be found`) } - this.error(error) + error(error_) } // Json only logs out if --json flag is passed diff --git a/src/lib/api.js b/src/lib/api.js index af44cffc191..8adf7652d42 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -1,5 +1,7 @@ const fetch = require('node-fetch') +const { warn } = require('../utils/command-helpers') + const getHeaders = ({ token }) => ({ 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, @@ -69,7 +71,7 @@ const uploadEdgeHandlers = async ({ api, deployId, bundleBuffer, manifest }) => return true } -const cancelDeploy = async ({ api, deployId, warn }) => { +const cancelDeploy = async ({ api, deployId }) => { try { await api.cancelSiteDeploy({ deploy_id: deployId }) } catch (error) { diff --git a/src/lib/functions/form-submissions-handler.js b/src/lib/functions/form-submissions-handler.js index 0ef477a3b61..823a4a7ce38 100644 --- a/src/lib/functions/form-submissions-handler.js +++ b/src/lib/functions/form-submissions-handler.js @@ -5,10 +5,11 @@ const { parse: parseContentType } = require('content-type') const multiparty = require('multiparty') const getRawBody = require('raw-body') +const { warn } = require('../../utils/command-helpers') const { BACKGROUND } = require('../../utils/get-functions') const { capitalize } = require('../string') -const createFormSubmissionHandler = function ({ functionsRegistry, siteUrl, warn }) { +const createFormSubmissionHandler = function ({ functionsRegistry, siteUrl }) { return async function formSubmissionHandler(req, res, next) { if (req.url.startsWith('/.netlify/') || req.method !== 'POST') return next() @@ -20,7 +21,7 @@ const createFormSubmissionHandler = function ({ functionsRegistry, siteUrl, warn }) fakeRequest.headers = req.headers - const handlerName = getFormHandler({ functionsRegistry, warn }) + const handlerName = getFormHandler({ functionsRegistry }) if (!handlerName) { return next() } @@ -125,7 +126,7 @@ const createFormSubmissionHandler = function ({ functionsRegistry, siteUrl, warn } } -const getFormHandler = function ({ functionsRegistry, warn }) { +const getFormHandler = function ({ functionsRegistry }) { const handlers = ['submission-created', `submission-created${BACKGROUND}`] .map((name) => functionsRegistry.get(name)) .filter(Boolean) diff --git a/src/lib/functions/registry.js b/src/lib/functions/registry.js index a75e59ba644..65626c47a24 100644 --- a/src/lib/functions/registry.js +++ b/src/lib/functions/registry.js @@ -2,7 +2,7 @@ const { env } = require('process') const chalk = require('chalk') -const { log } = require('../../utils/command-helpers') +const { log, warn } = require('../../utils/command-helpers') const { NETLIFYDEVLOG, NETLIFYDEVERR } = require('../../utils/logo') const { mkdirRecursiveAsync } = require('../fs') const { getLogMessage } = require('../log') @@ -12,15 +12,11 @@ const runtimes = require('./runtimes') const { watchDebounced } = require('./watcher') class FunctionsRegistry { - constructor({ capabilities, config, errorExit, functionsDirectory, projectRoot, timeouts, warn }) { + constructor({ capabilities, config, errorExit, functionsDirectory, projectRoot, timeouts }) { this.capabilities = capabilities this.config = config this.errorExit = errorExit this.functionsDirectory = functionsDirectory - this.logger = { - log, - warn, - } this.projectRoot = projectRoot this.timeouts = timeouts @@ -68,19 +64,19 @@ class FunctionsRegistry { async buildFunctionAndWatchFiles(func, { verbose } = {}) { if (verbose) { - this.logger.log(`${NETLIFYDEVLOG} ${chalk.magenta('Reloading')} function ${chalk.yellow(func.name)}...`) + log(`${NETLIFYDEVLOG} ${chalk.magenta('Reloading')} function ${chalk.yellow(func.name)}...`) } const { error, srcFilesDiff } = await func.build({ cache: this.buildCache }) if (error) { - this.logger.log( + log( `${NETLIFYDEVERR} ${chalk.red('Failed')} reloading function ${chalk.yellow(func.name)} with error:\n${ error.message }`, ) } else if (verbose) { - this.logger.log(`${NETLIFYDEVLOG} ${chalk.green('Reloaded')} function ${chalk.yellow(func.name)}`) + log(`${NETLIFYDEVLOG} ${chalk.green('Reloaded')} function ${chalk.yellow(func.name)}`) } // If the build hasn't resulted in any files being added or removed, there @@ -135,13 +131,13 @@ class FunctionsRegistry { } if (func.isBackground && !this.capabilities.backgroundFunctions) { - this.logger.warn(getLogMessage('functions.backgroundNotSupported')) + warn(getLogMessage('functions.backgroundNotSupported')) } this.functions.set(name, func) this.buildFunctionAndWatchFiles(func) - this.logger.log(`${NETLIFYDEVLOG} ${chalk.green('Loaded')} function ${chalk.yellow(name)}.`) + log(`${NETLIFYDEVLOG} ${chalk.green('Loaded')} function ${chalk.yellow(name)}.`) } async scan(directories) { @@ -223,7 +219,7 @@ class FunctionsRegistry { async unregisterFunction(name) { this.functions.delete(name) - this.logger.log(`${NETLIFYDEVLOG} ${chalk.magenta('Removed')} function ${chalk.yellow(name)}.`) + log(`${NETLIFYDEVLOG} ${chalk.magenta('Removed')} function ${chalk.yellow(name)}.`) const watcher = this.functionWatchers.get(name) diff --git a/src/lib/functions/server.js b/src/lib/functions/server.js index 680d7e77f9b..a47da9aaea7 100644 --- a/src/lib/functions/server.js +++ b/src/lib/functions/server.js @@ -104,7 +104,7 @@ const createHandler = function ({ functionsRegistry }) { } } -const getFunctionsServer = async function ({ functionsRegistry, siteUrl, warn, prefix }) { +const getFunctionsServer = async function ({ functionsRegistry, siteUrl, prefix }) { // performance optimization, load express on demand // eslint-disable-next-line node/global-require const express = require('express') @@ -120,7 +120,7 @@ const getFunctionsServer = async function ({ functionsRegistry, siteUrl, warn, p }), ) app.use(bodyParser.raw({ limit: '6mb', type: '*/*' })) - app.use(createFormSubmissionHandler({ functionsRegistry, siteUrl, warn })) + app.use(createFormSubmissionHandler({ functionsRegistry, siteUrl })) app.use( expressLogging(console, { blacklist: ['/favicon.ico'], @@ -140,7 +140,6 @@ const startFunctionsServer = async ({ config, settings, site, - warn, errorExit, siteUrl, capabilities, @@ -157,7 +156,6 @@ const startFunctionsServer = async ({ functionsDirectory: settings.functions, projectRoot: site.root, timeouts, - warn, }) const internalFunctionsDir = await getInternalFunctionsDir({ base: site.root }) @@ -167,7 +165,6 @@ const startFunctionsServer = async ({ functionsRegistry, siteUrl, prefix, - warn, }) await startWebServer({ server, settings, errorExit }) diff --git a/src/lib/functions/utils.js b/src/lib/functions/utils.js index c5e09d84f12..ee09ee4e57e 100644 --- a/src/lib/functions/utils.js +++ b/src/lib/functions/utils.js @@ -1,5 +1,6 @@ const chalk = require('chalk') +const { warn } = require('../../utils/command-helpers') const { getLogMessage } = require('../log') const BASE_64_MIME_REGEXP = /image|audio|video|application\/pdf|application\/zip|applicaton\/octet-stream/i @@ -10,7 +11,7 @@ const DEFAULT_LAMBDA_OPTIONS = { const SECONDS_TO_MILLISECONDS = 1000 -const detectAwsSdkError = ({ error, warn }) => { +const detectAwsSdkError = ({ error }) => { const isAwsSdkError = error.errorMessage && error.errorMessage.includes("Cannot find module 'aws-sdk'") if (isAwsSdkError) { diff --git a/src/utils/addons/prepare.js b/src/utils/addons/prepare.js index c04f8cf85e5..beffeb8eef3 100644 --- a/src/utils/addons/prepare.js +++ b/src/utils/addons/prepare.js @@ -1,13 +1,13 @@ const chalk = require('chalk') -const { log } = require('../command-helpers') +const { log, warn, error, exit } = require('../command-helpers') const ADDON_VALIDATION = { EXISTS: 'EXISTS', NOT_EXISTS: 'NOT_EXISTS', } -const validateExists = ({ addon, addonName, siteData, exit }) => { +const validateExists = ({ addon, addonName, siteData }) => { if (!addon || !addon.id) { log(`Add-on ${addonName} doesn't exist for ${siteData.name}`) log(`> Run \`netlify addons:create ${addonName}\` to create an instance for this site`) @@ -15,7 +15,7 @@ const validateExists = ({ addon, addonName, siteData, exit }) => { } } -const validateNotExists = ({ addon, addonName, siteData, exit }) => { +const validateNotExists = ({ addon, addonName, siteData }) => { if (addon && addon.id) { log(`The "${addonName} add-on" already exists for ${siteData.name}`) log() @@ -30,14 +30,14 @@ const validateNotExists = ({ addon, addonName, siteData, exit }) => { const getCurrentAddon = ({ addons, addonName }) => addons.find((addon) => addon.service_slug === addonName) -const validateCurrentAddon = ({ addon, validation, addonName, siteData, warn, exit }) => { +const validateCurrentAddon = ({ addon, validation, addonName, siteData }) => { switch (validation) { case ADDON_VALIDATION.EXISTS: { - validateExists({ addon, addonName, siteData, exit }) + validateExists({ addon, addonName, siteData }) break } case ADDON_VALIDATION.NOT_EXISTS: { - validateNotExists({ addon, addonName, siteData, exit }) + validateNotExists({ addon, addonName, siteData }) break } default: { @@ -47,7 +47,7 @@ const validateCurrentAddon = ({ addon, validation, addonName, siteData, warn, ex } } -const getAddonManifest = async ({ api, addonName, error }) => { +const getAddonManifest = async ({ api, addonName }) => { let manifest try { manifest = await api.showServiceManifest({ addonName }) @@ -61,7 +61,7 @@ const getAddonManifest = async ({ api, addonName, error }) => { return manifest } -const getSiteData = async ({ api, siteId, error }) => { +const getSiteData = async ({ api, siteId }) => { let siteData try { siteData = await api.getSite({ siteId }) @@ -71,7 +71,7 @@ const getSiteData = async ({ api, siteId, error }) => { return siteData } -const getAddons = async ({ api, siteId, error }) => { +const getAddons = async ({ api, siteId }) => { let addons try { addons = await api.listServiceInstancesForSite({ siteId }) @@ -82,7 +82,7 @@ const getAddons = async ({ api, siteId, error }) => { } const prepareAddonCommand = async ({ context, addonName, validation }) => { - const { netlify, warn, error, exit } = context + const { netlify } = context const { api, site } = netlify const siteId = site.id if (!siteId) { @@ -93,14 +93,14 @@ const prepareAddonCommand = async ({ context, addonName, validation }) => { const [manifest, siteData, addons] = await Promise.all([ addonName ? getAddonManifest({ api, addonName, error }) : Promise.resolve(), - getSiteData({ api, siteId, error }), - getAddons({ api, siteId, error }), + getSiteData({ api, siteId }), + getAddons({ api, siteId }), ]) let addon if (addonName) { addon = getCurrentAddon({ addons, addonName }) - validateCurrentAddon({ addon, validation, addonName, siteData, warn, exit }) + validateCurrentAddon({ addon, validation, addonName, siteData }) } return { manifest, addons, addon, siteData } diff --git a/src/utils/command-helpers.js b/src/utils/command-helpers.js index 2efb7cde652..defb72eb9e8 100644 --- a/src/utils/command-helpers.js +++ b/src/utils/command-helpers.js @@ -1,6 +1,7 @@ const process = require('process') const { format, inspect } = require('util') +const Errors = require('@oclif/errors') const argv = require('minimist')(process.argv.slice(2)) const omit = require('omit.js').default @@ -91,6 +92,18 @@ const log = (message = '', ...args) => { process.stdout.write(`${format(message, ...args)}\n`) } +const warn = (message = '') => { + Errors.warn(message) +} + +const error = (message = '', options = {}) => { + Errors.error(message, options) +} + +const exit = (code = 0) => { + Errors.exit(code) +} + // When `build.publish` is not set by the user, the CLI behavior differs in // several ways. It detects it by checking if `build.publish` is `undefined`. // However, `@netlify/config` adds a default value to `build.publish`. @@ -106,6 +119,9 @@ module.exports = { pollForToken, log, logJson, + warn, + error, + exit, getToken, normalizeConfig, chalk, diff --git a/src/utils/deploy/deploy-site.js b/src/utils/deploy/deploy-site.js index 186e270f342..4a42fcf65e9 100644 --- a/src/utils/deploy/deploy-site.js +++ b/src/utils/deploy/deploy-site.js @@ -2,6 +2,7 @@ const cleanDeep = require('clean-deep') const tempy = require('tempy') const { rmdirRecursiveAsync } = require('../../lib/fs') +const { warn } = require('../command-helpers') const { DEFAULT_DEPLOY_TIMEOUT, @@ -40,7 +41,6 @@ const deploySite = async ( }, syncFileLimit = DEFAULT_SYNC_LIMIT, tmpDir = tempy.directory(), - warn, rootDir, } = {}, ) => { diff --git a/src/utils/dev.js b/src/utils/dev.js index c383e134511..63f49e15a10 100644 --- a/src/utils/dev.js +++ b/src/utils/dev.js @@ -8,7 +8,7 @@ const isEmpty = require('lodash/isEmpty') const { supportsBackgroundFunctions } = require('../lib/account') -const { log } = require('./command-helpers') +const { log, warn } = require('./command-helpers') const { loadDotEnvFiles } = require('./dot-env') const { NETLIFYDEVLOG } = require('./logo') @@ -73,7 +73,7 @@ const getAddonsInformation = ({ siteInfo, addons }) => { return { urls, env } } -const getSiteAccount = ({ siteInfo, accounts, warn }) => { +const getSiteAccount = ({ siteInfo, accounts }) => { const siteAccount = accounts.find((account) => account.slug === siteInfo.account_slug) if (!siteAccount) { warn(`Could not find account for site '${siteInfo.name}' with account slug '${siteInfo.account_slug}'`) @@ -88,7 +88,7 @@ const SYNCHRONOUS_FUNCTION_TIMEOUT = 10 // default 15 minutes for background functions const BACKGROUND_FUNCTION_TIMEOUT = 900 -const getSiteInformation = async ({ flags = {}, api, site, warn, error: failAndExit, siteInfo }) => { +const getSiteInformation = async ({ flags = {}, api, site, error: failAndExit, siteInfo }) => { if (site.id && !flags.offline) { validateSiteInfo({ site, siteInfo, failAndExit }) const [accounts, addons] = await Promise.all([ @@ -97,7 +97,7 @@ const getSiteInformation = async ({ flags = {}, api, site, warn, error: failAndE ]) const { urls: addonsUrls } = getAddonsInformation({ siteInfo, addons }) - const account = getSiteAccount({ siteInfo, accounts, warn }) + const account = getSiteAccount({ siteInfo, accounts }) return { addonsUrls, @@ -132,9 +132,9 @@ const getEnvSourceName = (source) => { // Takes a set of environment variables in the format provided by @netlify/config, augments it with variables from both // dot-env files and the process itself, and injects into `process.env`. -const injectEnvVariables = async ({ env, site, warn }) => { +const injectEnvVariables = async ({ env, site }) => { const environment = new Map(Object.entries(env)) - const dotEnvFiles = await loadDotEnvFiles({ projectDir: site.root, warn }) + const dotEnvFiles = await loadDotEnvFiles({ projectDir: site.root }) dotEnvFiles.forEach(({ file, env: fileEnv }) => { Object.keys(fileEnv).forEach((key) => { diff --git a/src/utils/dot-env.js b/src/utils/dot-env.js index 1022d4aa22b..d3f686585ce 100644 --- a/src/utils/dot-env.js +++ b/src/utils/dot-env.js @@ -4,7 +4,10 @@ const dotenv = require('dotenv') const { isFileAsync, readFileAsync } = require('../lib/fs') -const loadDotEnvFiles = async function ({ projectDir, warn }) { +const { warn: warn_ } = require('./command-helpers') + +const loadDotEnvFiles = async function ({ projectDir, warnLog }) { + const warn = warnLog || warn_ const dotenvFiles = ['.env', '.env.development'] const results = await Promise.all( dotenvFiles.map(async (file) => { diff --git a/src/utils/edge-handlers.js b/src/utils/edge-handlers.js index 83e49a50ecb..9207486b562 100644 --- a/src/utils/edge-handlers.js +++ b/src/utils/edge-handlers.js @@ -4,10 +4,12 @@ const { uploadEdgeHandlers, cancelDeploy } = require('../lib/api') const { statAsync, readFileAsyncCatchError } = require('../lib/fs') const { startSpinner, stopSpinner } = require('../lib/spinner') +const { error } = require('./command-helpers') + const MANIFEST_FILENAME = 'manifest.json' const EDGE_HANDLERS_FOLDER = '.netlify/edge-handlers' -const validateEdgeHandlerFolder = async ({ site, error }) => { +const validateEdgeHandlerFolder = async ({ site }) => { try { const resolvedFolder = path.resolve(site.root, EDGE_HANDLERS_FOLDER) const stat = await statAsync(resolvedFolder) @@ -22,7 +24,7 @@ const validateEdgeHandlerFolder = async ({ site, error }) => { } } -const readBundleAndManifest = async ({ edgeHandlersResolvedFolder, error }) => { +const readBundleAndManifest = async ({ edgeHandlersResolvedFolder }) => { const manifestPath = path.resolve(edgeHandlersResolvedFolder, MANIFEST_FILENAME) const { content: manifest, error: manifestError } = await readFileAsyncCatchError(manifestPath) if (manifestError) { @@ -50,8 +52,8 @@ const readBundleAndManifest = async ({ edgeHandlersResolvedFolder, error }) => { return { bundleBuffer, manifest: manifestJson } } -const deployEdgeHandlers = async ({ site, deployId, api, silent, error, warn }) => { - const edgeHandlersResolvedFolder = await validateEdgeHandlerFolder({ site, error }) +const deployEdgeHandlers = async ({ site, deployId, api, silent }) => { + const edgeHandlersResolvedFolder = await validateEdgeHandlerFolder({ site }) if (edgeHandlersResolvedFolder) { let spinner try { @@ -59,7 +61,7 @@ const deployEdgeHandlers = async ({ site, deployId, api, silent, error, warn }) ? null : startSpinner({ text: `Deploying Edge Handlers from directory ${edgeHandlersResolvedFolder}` }) - const { bundleBuffer, manifest } = await readBundleAndManifest({ edgeHandlersResolvedFolder, error }) + const { bundleBuffer, manifest } = await readBundleAndManifest({ edgeHandlersResolvedFolder }) // returns false if the bundle exists, true on success, throws on error const success = await uploadEdgeHandlers({ api, @@ -75,7 +77,7 @@ const deployEdgeHandlers = async ({ site, deployId, api, silent, error, warn }) } catch (error_) { const text = `Failed deploying Edge Handlers: ${error_.message}` stopSpinner({ spinner, text, error: true }) - await cancelDeploy({ api, deployId, warn }) + await cancelDeploy({ api, deployId }) // no need to report the error again error('') } diff --git a/src/utils/init/config-github.js b/src/utils/init/config-github.js index 655afa84766..b68886ad796 100644 --- a/src/utils/init/config-github.js +++ b/src/utils/init/config-github.js @@ -173,7 +173,7 @@ const addNotificationHooks = async ({ failAndExit, siteId, api, token }) => { } module.exports = async function configGithub({ context, siteId, repoOwner, repoName }) { - const { warn, error: failAndExit, netlify } = context + const { error: failAndExit, netlify } = context const { api, globalConfig, @@ -190,9 +190,8 @@ module.exports = async function configGithub({ context, siteId, repoOwner, repoN siteRoot, config, env, - warn, }) - await saveNetlifyToml({ repositoryRoot, config, configPath, baseDir, buildCmd, buildDir, functionsDir, warn }) + await saveNetlifyToml({ repositoryRoot, config, configPath, baseDir, buildCmd, buildDir, functionsDir }) const octokit = getGitHubClient({ token }) const [deployKey, githubRepo] = await Promise.all([ diff --git a/src/utils/init/config-manual.js b/src/utils/init/config-manual.js index 1127c2b8456..91593c71734 100644 --- a/src/utils/init/config-manual.js +++ b/src/utils/init/config-manual.js @@ -1,10 +1,10 @@ const inquirer = require('inquirer') -const { log } = require('../command-helpers') +const { log, exit } = require('../command-helpers') const { getBuildSettings, saveNetlifyToml, createDeployKey, setupSite } = require('./utils') -const addDeployKey = async ({ exit, deployKey }) => { +const addDeployKey = async ({ deployKey }) => { log('\nGive this Netlify SSH public key access to your repository:\n') log(`\n${deployKey.public_key}\n\n`) @@ -52,7 +52,7 @@ const addDeployHook = async ({ deployHook }) => { } module.exports = async function configManual({ context, siteId, repoData }) { - const { warn, error: failAndExit, exit, netlify } = context + const { error: failAndExit, netlify } = context const { api, config, @@ -66,12 +66,11 @@ module.exports = async function configManual({ context, siteId, repoData }) { siteRoot, config, env, - warn, }) - await saveNetlifyToml({ repositoryRoot, config, configPath, baseDir, buildCmd, buildDir, functionsDir, warn }) + await saveNetlifyToml({ repositoryRoot, config, configPath, baseDir, buildCmd, buildDir, functionsDir }) const deployKey = await createDeployKey({ api, failAndExit }) - await addDeployKey({ exit, deployKey }) + await addDeployKey({ deployKey }) const repoPath = await getRepoPath({ repoData }) const repo = { diff --git a/src/utils/init/node-version.js b/src/utils/init/node-version.js index 2dc46dd630a..f947dd2178a 100644 --- a/src/utils/init/node-version.js +++ b/src/utils/init/node-version.js @@ -3,6 +3,7 @@ const locatePath = require('locate-path') const nodeVersionAlias = require('node-version-alias') const { readFileAsync } = require('../../lib/fs') +const { warn } = require('../command-helpers') const DEFAULT_NODE_VERSION = '12.18.0' const NVM_FLAG_PREFIX = '--' @@ -11,7 +12,7 @@ const NVM_FLAG_PREFIX = '--' const normalizeConfiguredVersion = (version) => version.startsWith(NVM_FLAG_PREFIX) ? version.slice(NVM_FLAG_PREFIX.length) : version -const detectNodeVersion = async ({ baseDirectory, env, warn }) => { +const detectNodeVersion = async ({ baseDirectory, env }) => { try { const nodeVersionFile = await locatePath(['.nvmrc', '.node-version'], { cwd: baseDirectory }) const configuredVersion = diff --git a/src/utils/init/utils.js b/src/utils/init/utils.js index 4ba7cae2d48..9e3736dd2c5 100644 --- a/src/utils/init/utils.js +++ b/src/utils/init/utils.js @@ -9,6 +9,7 @@ const isEmpty = require('lodash/isEmpty') const { fileExistsAsync, writeFileAsync } = require('../../lib/fs') const { normalizeBackslash } = require('../../lib/path') +const { warn } = require('../command-helpers') const { getFrameworkInfo } = require('./frameworks') const { detectNodeVersion } = require('./node-version') @@ -131,9 +132,9 @@ const getPromptInputs = async ({ const getBaseDirectory = ({ repositoryRoot, siteRoot }) => path.normalize(repositoryRoot) === path.normalize(siteRoot) ? process.cwd() : siteRoot -const getBuildSettings = async ({ repositoryRoot, siteRoot, config, env, warn }) => { +const getBuildSettings = async ({ repositoryRoot, siteRoot, config, env }) => { const baseDirectory = getBaseDirectory({ repositoryRoot, siteRoot }) - const nodeVersion = await detectNodeVersion({ baseDirectory, env, warn }) + const nodeVersion = await detectNodeVersion({ baseDirectory, env }) const { frameworkName, frameworkBuildCommand, @@ -200,16 +201,7 @@ const getNetlifyToml = ({ ## more info on configuring this file: https://www.netlify.com/docs/netlify-toml-reference/ ` -const saveNetlifyToml = async ({ - repositoryRoot, - config, - configPath, - baseDir, - buildCmd, - buildDir, - functionsDir, - warn, -}) => { +const saveNetlifyToml = async ({ repositoryRoot, config, configPath, baseDir, buildCmd, buildDir, functionsDir }) => { const tomlPathParts = [repositoryRoot, baseDir, 'netlify.toml'].filter(Boolean) const tomlPath = path.join(...tomlPathParts) const exists = await fileExistsAsync(tomlPath) diff --git a/src/utils/link/link-by-prompt.js b/src/utils/link/link-by-prompt.js index e25e45f9889..cbee1e8b8f8 100644 --- a/src/utils/link/link-by-prompt.js +++ b/src/utils/link/link-by-prompt.js @@ -5,7 +5,7 @@ const inquirer = require('inquirer') const isEmpty = require('lodash/isEmpty') const { listSites } = require('../../lib/api') -const { log } = require('../command-helpers') +const { log, error } = require('../command-helpers') const { getRepoData } = require('../get-repo-data') const { track } = require('../telemetry') @@ -51,7 +51,7 @@ module.exports = async function linkPrompts(context, flags = {}) { const sites = await listSites({ api, options: { filter: 'all' } }) if (isEmpty(sites)) { - context.error( + error( new Error(`You don't have any sites yet. Run ${chalk.cyanBright('netlify sites:create')} to create a site.`), ) } @@ -94,7 +94,7 @@ Run ${chalk.cyanBright('git remote -v')} to see a list of your git remotes.`) }, ]) if (!selectedSite) { - context.error('No site selected') + error('No site selected') } site = selectedSite } @@ -118,16 +118,16 @@ Run ${chalk.cyanBright('git remote -v')} to see a list of your git remotes.`) api, options: { name: searchTerm, filter: 'all' }, }) - } catch (error) { - if (error.status === 404) { - context.error(`'${searchTerm}' not found`) + } catch (error_) { + if (error_.status === 404) { + error(`'${searchTerm}' not found`) } else { - context.error(error) + error(error_) } } if (isEmpty(matchingSites)) { - context.error(`No site names found containing '${searchTerm}'. + error(`No site names found containing '${searchTerm}'. Run ${chalk.cyanBright('netlify link')} again to try a new search, or run ${chalk.cyanBright('netlify sites:create')} to create a site.`) @@ -145,7 +145,7 @@ or run ${chalk.cyanBright('netlify sites:create')} to create a site.`) }, ]) if (!selectedSite) { - context.error('No site selected') + error('No site selected') } site = selectedSite } else { @@ -162,12 +162,12 @@ or run ${chalk.cyanBright('netlify sites:create')} to create a site.`) let sites try { sites = await listSites({ api, options: { maxPages: 1, filter: 'all' } }) - } catch (error) { - context.error(error) + } catch (error_) { + error(error_) } if (isEmpty(sites)) { - context.error(`You don't have any sites yet. Run ${chalk.cyanBright('netlify sites:create')} to create a site.`) + error(`You don't have any sites yet. Run ${chalk.cyanBright('netlify sites:create')} to create a site.`) } const { selectedSite } = await inquirer.prompt([ @@ -180,7 +180,7 @@ or run ${chalk.cyanBright('netlify sites:create')} to create a site.`) }, ]) if (!selectedSite) { - context.error('No site selected') + error('No site selected') } site = selectedSite break @@ -197,11 +197,11 @@ or run ${chalk.cyanBright('netlify sites:create')} to create a site.`) try { site = await api.getSite({ siteId }) - } catch (error) { - if (error.status === 404) { - context.error(new Error(`Site ID '${siteId}' not found`)) + } catch (error_) { + if (error_.status === 404) { + error(new Error(`Site ID '${siteId}' not found`)) } else { - context.error(error) + error(error_) } } break @@ -211,7 +211,7 @@ or run ${chalk.cyanBright('netlify sites:create')} to create a site.`) } if (!site) { - context.error(new Error(`No site found`)) + error(new Error(`No site found`)) } // Save site ID to config From 9a9674432746f4d546962735662c8d0f6013655c Mon Sep 17 00:00:00 2001 From: Kunal Kundu Date: Wed, 28 Jul 2021 18:09:06 +0530 Subject: [PATCH 2/2] refactor: leftover instances of exit utility --- src/commands/addons/auth.js | 4 ++-- src/commands/env/import.js | 4 ++-- src/commands/functions/build.js | 6 +++--- src/commands/login.js | 6 +++--- src/commands/logout.js | 6 +++--- src/commands/sites/delete.js | 6 +++--- src/commands/switch.js | 4 ++-- src/commands/unlink.js | 4 ++-- src/commands/watch.js | 4 ++-- src/utils/command.js | 3 ++- src/utils/link/link-by-prompt.js | 4 ++-- 11 files changed, 26 insertions(+), 25 deletions(-) diff --git a/src/commands/addons/auth.js b/src/commands/addons/auth.js index 3e4d2d958ba..b77633028c3 100644 --- a/src/commands/addons/auth.js +++ b/src/commands/addons/auth.js @@ -1,6 +1,6 @@ const { prepareAddonCommand, ADDON_VALIDATION } = require('../../utils/addons/prepare') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, exit } = require('../../utils/command-helpers') const openBrowser = require('../../utils/open-browser') class AddonsAuthCommand extends Command { @@ -25,7 +25,7 @@ class AddonsAuthCommand extends Command { log(addon.auth_url) log() await openBrowser({ url: addon.auth_url }) - this.exit() + exit() } } AddonsAuthCommand.aliases = ['addon:auth'] diff --git a/src/commands/env/import.js b/src/commands/env/import.js index fe483fa5dfb..432ff7df3b8 100644 --- a/src/commands/env/import.js +++ b/src/commands/env/import.js @@ -6,7 +6,7 @@ const dotenv = require('dotenv') const isEmpty = require('lodash/isEmpty') const Command = require('../../utils/command') -const { log, logJson } = require('../../utils/command-helpers') +const { log, logJson, exit } = require('../../utils/command-helpers') class EnvImportCommand extends Command { async run() { @@ -34,7 +34,7 @@ class EnvImportCommand extends Command { importedEnv = dotenv.parse(envFileContents) } catch (error) { log(error.message) - this.exit(1) + exit(1) } if (isEmpty(importedEnv)) { diff --git a/src/commands/functions/build.js b/src/commands/functions/build.js index 0245e5e36e4..0b88cd5d09d 100644 --- a/src/commands/functions/build.js +++ b/src/commands/functions/build.js @@ -4,7 +4,7 @@ const { zipFunctions } = require('@netlify/zip-it-and-ship-it') const { flags: flagsLib } = require('@oclif/command') const Command = require('../../utils/command') -const { log } = require('../../utils/command-helpers') +const { log, exit } = require('../../utils/command-helpers') const { getFunctionsDir } = require('../../utils/functions') const { NETLIFYDEVLOG, NETLIFYDEVERR } = require('../../utils/logo') @@ -19,7 +19,7 @@ class FunctionsBuildCommand extends Command { if (src === dst) { log(`${NETLIFYDEVERR} Source and destination for function build can't be the same`) - this.exit(1) + exit(1) } if (!src || !dst) { @@ -31,7 +31,7 @@ class FunctionsBuildCommand extends Command { log( `${NETLIFYDEVERR} Error: You must specify a destination functions folder with a --functions flag or a functions field in your config`, ) - this.exit(1) + exit(1) } fs.mkdirSync(dst, { recursive: true }) diff --git a/src/commands/login.js b/src/commands/login.js index 6713c259f89..1f94e19c425 100644 --- a/src/commands/login.js +++ b/src/commands/login.js @@ -2,7 +2,7 @@ const { flags: flagsLib } = require('@oclif/command') const chalk = require('chalk') const Command = require('../utils/command') -const { log, getToken } = require('../utils/command-helpers') +const { log, exit, getToken } = require('../utils/command-helpers') class LoginCommand extends Command { async run() { @@ -18,12 +18,12 @@ class LoginCommand extends Command { log() log(`To see all available commands run: ${chalk.cyanBright('netlify help')}`) log() - return this.exit() + return exit() } await this.expensivelyAuthenticate() - return this.exit() + return exit() } } diff --git a/src/commands/logout.js b/src/commands/logout.js index 908a35a4fa4..cf1eb11e260 100644 --- a/src/commands/logout.js +++ b/src/commands/logout.js @@ -1,5 +1,5 @@ const Command = require('../utils/command') -const { log, getToken } = require('../utils/command-helpers') +const { log, exit, getToken } = require('../utils/command-helpers') const { track } = require('../utils/telemetry') class LogoutCommand extends Command { @@ -10,7 +10,7 @@ class LogoutCommand extends Command { log(`Already logged out`) log() log('To login run "netlify login"') - this.exit() + exit() } await track('user_logout') @@ -23,7 +23,7 @@ class LogoutCommand extends Command { log() log('To logout completely, unset the environment variable') log() - this.exit() + exit() } log(`Logging you out of Netlify. Come back soon!`) diff --git a/src/commands/sites/delete.js b/src/commands/sites/delete.js index e8a956eb4f4..2b7e1dff84f 100644 --- a/src/commands/sites/delete.js +++ b/src/commands/sites/delete.js @@ -3,7 +3,7 @@ const chalk = require('chalk') const inquirer = require('inquirer') const Command = require('../../utils/command') -const { log, error } = require('../../utils/command-helpers') +const { log, error, exit } = require('../../utils/command-helpers') const { parseRawFlags } = require('../../utils/parse-raw-flags') class SitesDeleteCommand extends Command { @@ -51,7 +51,7 @@ class SitesDeleteCommand extends Command { }) log() if (!wantsToDelete) { - this.exit() + exit() } } @@ -71,7 +71,7 @@ class SitesDeleteCommand extends Command { default: false, }) if (!wantsToDelete) { - this.exit() + exit() } } diff --git a/src/commands/switch.js b/src/commands/switch.js index 025d11abd97..20763070238 100644 --- a/src/commands/switch.js +++ b/src/commands/switch.js @@ -2,7 +2,7 @@ const chalk = require('chalk') const inquirer = require('inquirer') const Command = require('../utils/command') -const { log } = require('../utils/command-helpers') +const { log, exit } = require('../utils/command-helpers') const LoginCommand = require('./login') @@ -35,7 +35,7 @@ class SwitchCommand extends Command { log(`You're now using ${chalk.bold(selectedAccount[1])}.`) } - return this.exit() + return exit() } } diff --git a/src/commands/unlink.js b/src/commands/unlink.js index bf3b7da6b67..5f25af87404 100644 --- a/src/commands/unlink.js +++ b/src/commands/unlink.js @@ -1,5 +1,5 @@ const Command = require('../utils/command') -const { log } = require('../utils/command-helpers') +const { log, exit } = require('../utils/command-helpers') const { track } = require('../utils/telemetry') class UnlinkCommand extends Command { @@ -9,7 +9,7 @@ class UnlinkCommand extends Command { if (!siteId) { log(`Folder is not linked to a Netlify site. Run 'netlify link' to link it`) - return this.exit() + return exit() } let siteData = {} diff --git a/src/commands/watch.js b/src/commands/watch.js index 4b9fa74db55..2199f717af5 100644 --- a/src/commands/watch.js +++ b/src/commands/watch.js @@ -5,7 +5,7 @@ const pWaitFor = require('p-wait-for') const prettyjson = require('prettyjson') const Command = require('../utils/command') -const { log } = require('../utils/command-helpers') +const { log, exit } = require('../utils/command-helpers') const InitCommand = require('./init') @@ -70,7 +70,7 @@ class SitesWatchCommand extends Command { throw new CLIError(error) } - this.exit() + exit() } } diff --git a/src/utils/command.js b/src/utils/command.js index 70dbbd0b671..67cb7c52db7 100644 --- a/src/utils/command.js +++ b/src/utils/command.js @@ -10,6 +10,7 @@ const API = require('netlify') const { getAgent } = require('../lib/http-agent') const { pollForToken, log, getToken, getCwd, argv, normalizeConfig, chalk } = require('./command-helpers') +const { exit } = require('./command-helpers') const getGlobalConfig = require('./get-global-config') const openBrowser = require('./open-browser') const StateConfig = require('./state-config') @@ -115,7 +116,7 @@ class BaseCommand extends TrackedCommand { const message = isUserError ? error.message : error.stack console.error(message) - this.exit(1) + exit(1) } } diff --git a/src/utils/link/link-by-prompt.js b/src/utils/link/link-by-prompt.js index cbee1e8b8f8..3f7b4fc2525 100644 --- a/src/utils/link/link-by-prompt.js +++ b/src/utils/link/link-by-prompt.js @@ -5,7 +5,7 @@ const inquirer = require('inquirer') const isEmpty = require('lodash/isEmpty') const { listSites } = require('../../lib/api') -const { log, error } = require('../command-helpers') +const { log, error, exit } = require('../command-helpers') const { getRepoData } = require('../get-repo-data') const { track } = require('../telemetry') @@ -70,7 +70,7 @@ Double check you are in the correct working directory and a remote origin repo i Run ${chalk.cyanBright('git remote -v')} to see a list of your git remotes.`) - context.exit() + exit() } // Matches a single site hooray!