From e04fe96fd978d0e39c0877590b4ff66eac6f8d64 Mon Sep 17 00:00:00 2001 From: Kunal Kundu Date: Wed, 22 Sep 2021 19:16:38 +0530 Subject: [PATCH 1/2] refactor: replace log,exit in utils of init,addons command --- src/lib/http-agent.js | 5 +++-- src/utils/addons/prepare.js | 16 ++++++++-------- src/utils/command.js | 13 ++++++------- src/utils/dot-env.js | 5 ++--- src/utils/init/config-github.js | 26 ++++++++++++-------------- src/utils/init/config-manual.js | 14 ++++++-------- src/utils/init/node-version.js | 3 ++- src/utils/init/utils.js | 23 +++++++---------------- 8 files changed, 46 insertions(+), 59 deletions(-) diff --git a/src/lib/http-agent.js b/src/lib/http-agent.js index c47073f4134..14df0f82065 100644 --- a/src/lib/http-agent.js +++ b/src/lib/http-agent.js @@ -3,7 +3,7 @@ const { URL } = require('url') const { HttpsProxyAgent } = require('https-proxy-agent') const waitPort = require('wait-port') -const { log } = require('../utils/command-helpers') +const { log, exit: exit_ } = require('../utils/command-helpers') const { NETLIFYDEVERR, NETLIFYDEVWARN } = require('../utils/logo') const fs = require('./fs') @@ -28,7 +28,8 @@ const DEFAULT_HTTPS_PORT = 443 // 50 seconds const AGENT_PORT_TIMEOUT = 50 -const getAgent = async ({ httpProxy, certificateFile, exit }) => { +// a stub utility is used in tests for exit +const getAgent = async ({ httpProxy, certificateFile, exit = exit_ }) => { if (!httpProxy) { return } diff --git a/src/utils/addons/prepare.js b/src/utils/addons/prepare.js index 5e542c5e358..beffeb8eef3 100644 --- a/src/utils/addons/prepare.js +++ b/src/utils/addons/prepare.js @@ -1,13 +1,13 @@ const chalk = require('chalk') -const { log, error } = 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: { @@ -82,7 +82,7 @@ const getAddons = async ({ api, siteId }) => { } const prepareAddonCommand = async ({ context, addonName, validation }) => { - const { netlify, warn, exit } = context + const { netlify } = context const { api, site } = netlify const siteId = site.id if (!siteId) { @@ -100,7 +100,7 @@ const prepareAddonCommand = async ({ context, addonName, validation }) => { 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.js b/src/utils/command.js index a5862ec2c26..a490f86e446 100644 --- a/src/utils/command.js +++ b/src/utils/command.js @@ -9,7 +9,7 @@ const API = require('netlify') const { getAgent } = require('../lib/http-agent') -const { pollForToken, log, getToken, getCwd, argv, normalizeConfig, chalk } = require('./command-helpers') +const { pollForToken, log, exit, error, getToken, getCwd, argv, normalizeConfig, chalk } = require('./command-helpers') const getGlobalConfig = require('./get-global-config') const openBrowser = require('./open-browser') const StateConfig = require('./state-config') @@ -49,7 +49,6 @@ class BaseCommand extends TrackedCommand { const { flags } = this.parse(BaseCommand) const agent = await getAgent({ - exit: this.exit, httpProxy: flags.httpProxy, certificateFile: flags.httpProxyCertificateFilename, }) @@ -100,8 +99,8 @@ class BaseCommand extends TrackedCommand { scheme, offline, }) - } catch (error) { - const isUserError = error.type === 'userError' + } catch (error_) { + const isUserError = error_.type === 'userError' // If we're failing due to an error thrown by us, it might be because the token we're using is invalid. // To account for that, we try to retrieve the config again, this time without a token, to avoid making @@ -113,9 +112,9 @@ class BaseCommand extends TrackedCommand { return this.getConfig({ cwd, offline: true, state, token }) } - const message = isUserError ? error.message : error.stack + const message = isUserError ? error_.message : error_.stack console.error(message) - this.exit(1) + exit(1) } } @@ -197,7 +196,7 @@ class BaseCommand extends TrackedCommand { const accessToken = await pollForToken({ api: this.netlify.api, ticket, - exitWithError: this.error, + exitWithError: error, }) const { id: userId, full_name: name, email } = await this.netlify.api.getCurrentUser() diff --git a/src/utils/dot-env.js b/src/utils/dot-env.js index 80ccfb5a8ec..e2cda12d9c3 100644 --- a/src/utils/dot-env.js +++ b/src/utils/dot-env.js @@ -6,9 +6,8 @@ const { isFileAsync, readFileAsync } = require('../lib/fs') const { warn: warn_ } = require('./command-helpers') -const loadDotEnvFiles = async function ({ projectDir, warnLog }) { - // a stub utility is used in tests - const warn = warnLog || warn_ +// a stub utility is used in tests for warn +const loadDotEnvFiles = async function ({ projectDir, warn = warn_ }) { const dotenvFiles = ['.env', '.env.development'] const results = await Promise.all( dotenvFiles.map(async (file) => { diff --git a/src/utils/init/config-github.js b/src/utils/init/config-github.js index 1e5fe8fd9e7..d7b49738abf 100644 --- a/src/utils/init/config-github.js +++ b/src/utils/init/config-github.js @@ -1,7 +1,7 @@ const { Octokit } = require('@octokit/rest') const chalk = require('chalk') -const { log } = require('../command-helpers') +const { log, error: failAndExit } = require('../command-helpers') const ghauth = require('../gh-auth') const { getBuildSettings, saveNetlifyToml, formatErrorMessage, createDeployKey, setupSite } = require('./utils') @@ -35,9 +35,9 @@ const getGitHubClient = ({ token }) => { return octokit } -const addDeployKey = async ({ api, octokit, repoOwner, repoName, failAndExit }) => { +const addDeployKey = async ({ api, octokit, repoOwner, repoName }) => { log('Adding deploy key to repository...') - const key = await createDeployKey({ api, failAndExit }) + const key = await createDeployKey({ api }) try { await octokit.repos.createDeployKey({ title: 'Netlify Deploy Key', @@ -58,7 +58,7 @@ const addDeployKey = async ({ api, octokit, repoOwner, repoName, failAndExit }) } } -const getGitHubRepo = async ({ octokit, repoOwner, repoName, failAndExit }) => { +const getGitHubRepo = async ({ octokit, repoOwner, repoName }) => { try { const { data } = await octokit.repos.get({ owner: repoOwner, @@ -90,7 +90,7 @@ const hookExists = async ({ deployHook, octokit, repoOwner, repoName }) => { } } -const addDeployHook = async ({ deployHook, octokit, repoOwner, repoName, failAndExit }) => { +const addDeployHook = async ({ deployHook, octokit, repoOwner, repoName }) => { const exists = await hookExists({ deployHook, octokit, repoOwner, repoName }) if (!exists) { try { @@ -148,7 +148,7 @@ const upsertHook = async ({ ntlHooks, event, api, siteId, token }) => { }) } -const addNotificationHooks = async ({ failAndExit, siteId, api, token }) => { +const addNotificationHooks = async ({ siteId, api, token }) => { log(`Creating Netlify GitHub Notification Hooks...`) let ntlHooks @@ -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 { netlify } = context const { api, globalConfig, @@ -190,14 +190,13 @@ 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([ - addDeployKey({ api, octokit, repoOwner, repoName, failAndExit }), - getGitHubRepo({ octokit, repoOwner, repoName, failAndExit }), + addDeployKey({ api, octokit, repoOwner, repoName }), + getGitHubRepo({ octokit, repoOwner, repoName }), ]) const repo = { @@ -215,13 +214,12 @@ module.exports = async function configGithub({ context, siteId, repoOwner, repoN const updatedSite = await setupSite({ api, - failAndExit, siteId, repo, configPlugins: config.plugins, pluginsToInstall, }) - await addDeployHook({ deployHook: updatedSite.deploy_hook, octokit, repoOwner, repoName, failAndExit }) + await addDeployHook({ deployHook: updatedSite.deploy_hook, octokit, repoOwner, repoName }) log() - await addNotificationHooks({ failAndExit, siteId, api, token }) + await addNotificationHooks({ siteId, api, token }) } diff --git a/src/utils/init/config-manual.js b/src/utils/init/config-manual.js index 1127c2b8456..739791c69ef 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 { 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 }) + const deployKey = await createDeployKey({ api }) + await addDeployKey({ deployKey }) const repoPath = await getRepoPath({ repoData }) const repo = { @@ -88,7 +87,6 @@ module.exports = async function configManual({ context, siteId, repoData }) { const updatedSite = await setupSite({ api, - failAndExit, siteId, repo, configPlugins: config.plugins, 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..fe6474de8be 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 { error: failAndExit, 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) @@ -248,7 +240,7 @@ const formatErrorMessage = ({ message, error }) => { const formatTitle = (title) => chalk.cyan(title) -const createDeployKey = async ({ api, failAndExit }) => { +const createDeployKey = async ({ api }) => { try { const deployKey = await api.createDeployKey() return deployKey @@ -258,7 +250,7 @@ const createDeployKey = async ({ api, failAndExit }) => { } } -const updateSite = async ({ siteId, api, failAndExit, options }) => { +const updateSite = async ({ siteId, api, options }) => { try { const updatedSite = await api.updateSite({ siteId, body: options }) return updatedSite @@ -268,11 +260,10 @@ const updateSite = async ({ siteId, api, failAndExit, options }) => { } } -const setupSite = async ({ api, failAndExit, siteId, repo, configPlugins, pluginsToInstall }) => { +const setupSite = async ({ api, siteId, repo, configPlugins, pluginsToInstall }) => { const updatedSite = await updateSite({ siteId, api, - failAndExit, // merge existing plugins with new ones options: { repo, plugins: [...getUIPlugins(configPlugins), ...pluginsToInstall] }, }) From f8978312dd6ff46011e7f45643afe064df94b918 Mon Sep 17 00:00:00 2001 From: Kunal Kundu Date: Thu, 23 Sep 2021 18:45:03 +0530 Subject: [PATCH 2/2] fix: remove exit,warn selection in loadDotEnvFiles & getAgent --- src/lib/http-agent.js | 5 ++--- src/utils/command.js | 14 +++++++++++++- src/utils/dev.js | 2 +- src/utils/dot-env.js | 5 +---- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/lib/http-agent.js b/src/lib/http-agent.js index 14df0f82065..c47073f4134 100644 --- a/src/lib/http-agent.js +++ b/src/lib/http-agent.js @@ -3,7 +3,7 @@ const { URL } = require('url') const { HttpsProxyAgent } = require('https-proxy-agent') const waitPort = require('wait-port') -const { log, exit: exit_ } = require('../utils/command-helpers') +const { log } = require('../utils/command-helpers') const { NETLIFYDEVERR, NETLIFYDEVWARN } = require('../utils/logo') const fs = require('./fs') @@ -28,8 +28,7 @@ const DEFAULT_HTTPS_PORT = 443 // 50 seconds const AGENT_PORT_TIMEOUT = 50 -// a stub utility is used in tests for exit -const getAgent = async ({ httpProxy, certificateFile, exit = exit_ }) => { +const getAgent = async ({ httpProxy, certificateFile, exit }) => { if (!httpProxy) { return } diff --git a/src/utils/command.js b/src/utils/command.js index a490f86e446..4e0402b884a 100644 --- a/src/utils/command.js +++ b/src/utils/command.js @@ -9,7 +9,18 @@ const API = require('netlify') const { getAgent } = require('../lib/http-agent') -const { pollForToken, log, exit, error, getToken, getCwd, argv, normalizeConfig, chalk } = require('./command-helpers') +const { + pollForToken, + log, + exit, + warn, + error, + getToken, + getCwd, + argv, + normalizeConfig, + chalk, +} = require('./command-helpers') const getGlobalConfig = require('./get-global-config') const openBrowser = require('./open-browser') const StateConfig = require('./state-config') @@ -51,6 +62,7 @@ class BaseCommand extends TrackedCommand { const agent = await getAgent({ httpProxy: flags.httpProxy, certificateFile: flags.httpProxyCertificateFilename, + warn, }) const apiOpts = { ...apiUrlOpts, agent } const globalConfig = await getGlobalConfig() diff --git a/src/utils/dev.js b/src/utils/dev.js index b40e0893fda..354a716625d 100644 --- a/src/utils/dev.js +++ b/src/utils/dev.js @@ -131,7 +131,7 @@ const getEnvSourceName = (source) => { // dot-env files and the process itself, and injects into `process.env`. const injectEnvVariables = async ({ env, site }) => { const environment = new Map(Object.entries(env)) - const dotEnvFiles = await loadDotEnvFiles({ projectDir: site.root }) + const dotEnvFiles = await loadDotEnvFiles({ projectDir: site.root, warn }) 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 e2cda12d9c3..1022d4aa22b 100644 --- a/src/utils/dot-env.js +++ b/src/utils/dot-env.js @@ -4,10 +4,7 @@ const dotenv = require('dotenv') const { isFileAsync, readFileAsync } = require('../lib/fs') -const { warn: warn_ } = require('./command-helpers') - -// a stub utility is used in tests for warn -const loadDotEnvFiles = async function ({ projectDir, warn = warn_ }) { +const loadDotEnvFiles = async function ({ projectDir, warn }) { const dotenvFiles = ['.env', '.env.development'] const results = await Promise.all( dotenvFiles.map(async (file) => {