Skip to content

Commit

Permalink
refactor: replace inherited logging, exit utils in commands.functions… (
Browse files Browse the repository at this point in the history
#3347)

* refactor: replace inherited logging, exit utils in commands.functions and adjacent utils

* refactor: remove _ from empty catch blocks

Co-authored-by: ehmicky <ehmicky@users.noreply.github.com>
  • Loading branch information
tinfoil-knight and ehmicky authored Sep 16, 2021
1 parent 1ebd29a commit 8c87871
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 59 deletions.
6 changes: 3 additions & 3 deletions src/commands/functions/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand All @@ -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) {
Expand All @@ -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 })
Expand Down
29 changes: 12 additions & 17 deletions src/commands/functions/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,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')
Expand Down Expand Up @@ -215,7 +215,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([
Expand Down Expand Up @@ -243,7 +243,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')
}
}
Expand Down Expand Up @@ -279,7 +279,7 @@ const downloadFromURL = async function (context, flags, args, functionsDir) {

try {
mkdirRecursiveSync(fnFolder)
} catch (error) {
} catch {
// Ignore
}
await Promise.all(
Expand All @@ -289,8 +289,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_}`)
}
}),
)
Expand Down Expand Up @@ -365,7 +365,7 @@ const installDeps = async ({ functionPackageJson, functionPath, functionsDir })
const functionPackageLock = path.join(functionPath, 'package-lock.json')

fs.unlinkSync(functionPackageLock)
} catch (error) {
} catch {
// no-op
}
}
Expand All @@ -388,9 +388,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') {
Expand Down Expand Up @@ -450,7 +450,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) {
Expand Down Expand Up @@ -509,7 +509,6 @@ const installAddons = async function (context, functionAddons, fnPath) {
return
}

const { error } = context
const { api, site } = context.netlify
const siteId = site.id
if (!siteId) {
Expand All @@ -518,10 +517,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)}`)
Expand All @@ -532,7 +528,6 @@ const installAddons = async function (context, functionAddons, fnPath) {
siteId,
addonName,
siteData,
error,
})

await handleAddonDidInstall({ addonCreated, addonDidInstall, context, fnPath })
Expand Down
13 changes: 7 additions & 6 deletions src/commands/functions/invoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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}`)
}
}
}
Expand All @@ -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
Expand Down Expand Up @@ -270,7 +271,7 @@ const tryParseJSON = function (jsonString) {
if (parsedValue && typeof parsedValue === 'object') {
return parsedValue
}
} catch (error) {}
} catch {}

return false
}
24 changes: 12 additions & 12 deletions src/commands/functions/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand All @@ -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 || []
Expand All @@ -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
Expand Down
6 changes: 2 additions & 4 deletions src/commands/functions/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand All @@ -39,7 +38,6 @@ class FunctionsServeCommand extends Command {
config,
settings: { functions: functionsDir, functionsPort },
site,
warn,
errorExit,
siteUrl,
capabilities,
Expand Down
5 changes: 2 additions & 3 deletions src/lib/functions/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const bodyParser = require('body-parser')
const jwtDecode = require('jwt-decode')

const { log } = require('../../utils/command-helpers')
const { log, warn } = require('../../utils/command-helpers')
const { getInternalFunctionsDir } = require('../../utils/functions')
const { NETLIFYDEVERR, NETLIFYDEVLOG } = require('../../utils/logo')

Expand Down Expand Up @@ -108,7 +108,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')
Expand Down Expand Up @@ -144,7 +144,6 @@ const startFunctionsServer = async ({
config,
settings,
site,
warn,
errorExit,
siteUrl,
capabilities,
Expand Down
14 changes: 7 additions & 7 deletions src/utils/addons/prepare.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const chalk = require('chalk')

const { log } = require('../command-helpers')
const { log, error } = require('../command-helpers')

const ADDON_VALIDATION = {
EXISTS: 'EXISTS',
Expand Down Expand Up @@ -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 })
Expand All @@ -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 })
Expand All @@ -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 })
Expand All @@ -82,7 +82,7 @@ const getAddons = async ({ api, siteId, error }) => {
}

const prepareAddonCommand = async ({ context, addonName, validation }) => {
const { netlify, warn, error, exit } = context
const { netlify, warn, exit } = context
const { api, site } = netlify
const siteId = site.id
if (!siteId) {
Expand All @@ -93,8 +93,8 @@ 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
Expand Down
12 changes: 6 additions & 6 deletions src/utils/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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}'`)
Expand All @@ -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([
Expand 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,
Expand Down Expand Up @@ -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) => {
Expand Down
Loading

1 comment on commit 8c87871

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📊 Benchmark results

Package size: 352 MB

Please sign in to comment.