Skip to content

refactor: replace log,exit in utils of init,addons command #3382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions src/utils/addons/prepare.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
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`)
exit(1)
}
}

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()
Expand All @@ -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: {
Expand Down Expand Up @@ -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) {
Expand All @@ -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 }
Expand Down
25 changes: 18 additions & 7 deletions src/utils/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,18 @@ 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,
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')
Expand Down Expand Up @@ -49,9 +60,9 @@ class BaseCommand extends TrackedCommand {

const { flags } = this.parse(BaseCommand)
const agent = await getAgent({
exit: this.exit,
httpProxy: flags.httpProxy,
certificateFile: flags.httpProxyCertificateFilename,
warn,
})
const apiOpts = { ...apiUrlOpts, agent }
const globalConfig = await getGlobalConfig()
Expand Down Expand Up @@ -100,8 +111,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
Expand All @@ -113,9 +124,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)
}
}

Expand Down Expand Up @@ -197,7 +208,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()
Expand Down
2 changes: 1 addition & 1 deletion src/utils/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
6 changes: 1 addition & 5 deletions src/utils/dot-env.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ const dotenv = require('dotenv')

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_
const loadDotEnvFiles = async function ({ projectDir, warn }) {
const dotenvFiles = ['.env', '.env.development']
const results = await Promise.all(
dotenvFiles.map(async (file) => {
Expand Down
26 changes: 12 additions & 14 deletions src/utils/init/config-github.js
Original file line number Diff line number Diff line change
@@ -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')
Expand Down Expand Up @@ -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',
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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 = {
Expand All @@ -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 })
}
14 changes: 6 additions & 8 deletions src/utils/init/config-manual.js
Original file line number Diff line number Diff line change
@@ -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`)

Expand Down Expand Up @@ -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,
Expand All @@ -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 = {
Expand All @@ -88,7 +87,6 @@ module.exports = async function configManual({ context, siteId, repoData }) {

const updatedSite = await setupSite({
api,
failAndExit,
siteId,
repo,
configPlugins: config.plugins,
Expand Down
3 changes: 2 additions & 1 deletion src/utils/init/node-version.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '--'
Expand All @@ -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 =
Expand Down
23 changes: 7 additions & 16 deletions src/utils/init/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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] },
})
Expand Down