Skip to content

Commit

Permalink
chore(lint): add prefer-destructuring ESLint rule
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Oct 20, 2020
1 parent 637fecf commit a195eb4
Show file tree
Hide file tree
Showing 25 changed files with 55 additions and 45 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ module.exports = {
'multiline-comment-style': [2, 'separate-lines'],
'no-else-return': [2, { allowElseIf: false }],
'no-var': 2,
'prefer-destructuring': 2,

// This version of eslint-plugin-unicorn requires Node 10
// TODO: remove after dropping Node 8 support
Expand Down
2 changes: 1 addition & 1 deletion src/commands/deploy.js
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ class DeployCommand extends Command {

const deployFolder = await getDeployFolder({ flags, config, site, siteData, log })
const functionsFolder = getFunctionsFolder({ flags, config, site, siteData })
const configPath = site.configPath
const { configPath } = site

log(
prettyjson.render({
Expand Down
2 changes: 1 addition & 1 deletion src/commands/env/unset.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class EnvUnsetCommand extends Command {
const { args, flags } = this.parse(EnvUnsetCommand)
const { api, site } = this.netlify
const siteId = site.id
const name = args.name
const { name } = args

if (!siteId) {
this.log('No site id found, please run inside a site folder or `netlify link`')
Expand Down
5 changes: 4 additions & 1 deletion src/commands/functions/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ module.exports = FunctionsCreateCommand
async function getNameFromArgs(args, flags, defaultName) {
if (flags.name && args.name) throw new Error('function name specified in both flag and arg format, pick one')
let name
// eslint-disable-next-line prefer-destructuring
if (flags.name && !args.name) name = flags.name
// use flag if exists
// eslint-disable-next-line prefer-destructuring
else if (!flags.name && args.name) name = args.name

// if neither are specified, prompt for it
Expand All @@ -89,6 +91,7 @@ async function getNameFromArgs(args, flags, defaultName) {
// this has some nuance i have ignored, eg crossenv and i18n concerns
},
])
// eslint-disable-next-line prefer-destructuring
name = responses.name
}
return name
Expand Down Expand Up @@ -203,7 +206,7 @@ function ensureFunctionDirExists(flags, config) {
// Download files from a given github URL
async function downloadFromURL(flags, args, functionsDir) {
const folderContents = await readRepoURL(flags.url)
const functionName = flags.url.split('/').slice(-1)[0]
const [functionName] = flags.url.split('/').slice(-1)
const nameToUse = await getNameFromArgs(args, flags, functionName)
const fnFolder = path.join(functionsDir, nameToUse)
if (fs.existsSync(fnFolder + '.js') && fs.lstatSync(fnFolder + '.js').isFile()) {
Expand Down
6 changes: 3 additions & 3 deletions src/commands/functions/invoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@ class FunctionsInvokeCommand extends Command {
if (eventTriggeredFunctions.has(functionToTrigger)) {
/** handle event triggered fns */
// https://www.netlify.com/docs/functions/#event-triggered-functions
const parts = functionToTrigger.split('-')
if (parts[0] === 'identity') {
const [name, event] = functionToTrigger.split('-')
if (name === 'identity') {
// https://www.netlify.com/docs/functions/#identity-event-functions
body.event = parts[1]
body.event = event
body.user = {
id: '1111a1a1-a11a-1111-aa11-aaa11111a11a',
aud: '',
Expand Down
8 changes: 4 additions & 4 deletions src/commands/link.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ class LinkCommand extends Command {
if (results.length === 0) {
this.error(new Error(`No sites found named ${flags.name}`))
}
siteData = results[0]
state.set('siteId', siteData.id)
const [firstSiteData] = results
state.set('siteId', firstSiteData.id)

this.log(`Linked to ${siteData.name} in ${path.relative(path.join(process.cwd(), '..'), state.path)}`)
this.log(`Linked to ${firstSiteData.name} in ${path.relative(path.join(process.cwd(), '..'), state.path)}`)

await track('sites_linked', {
siteId: (siteData && siteData.id) || siteId,
siteId: (firstSiteData && firstSiteData.id) || siteId,
linkType: 'manual',
kind: 'byName',
})
Expand Down
10 changes: 5 additions & 5 deletions src/commands/sites/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class SitesCreateCommand extends Command {

let accountSlug = flags['account-slug']
if (!accountSlug) {
const results = await inquirer.prompt([
const { accountSlug: accountSlugInput } = await inquirer.prompt([
{
type: 'list',
name: 'accountSlug',
Expand All @@ -39,10 +39,10 @@ class SitesCreateCommand extends Command {
})),
},
])
accountSlug = results.accountSlug
accountSlug = accountSlugInput
}

const name = flags.name
const { name } = flags
let userName
let site

Expand All @@ -64,7 +64,7 @@ class SitesCreateCommand extends Command {
console.log(
`Choose a unique site name (e.g. ${siteSuggestion}.netlify.app) or leave it blank for a random name. You can update the site name later.`
)
const results = await inquirer.prompt([
const { name: nameInput } = await inquirer.prompt([
{
type: 'input',
name: 'name',
Expand All @@ -73,7 +73,7 @@ class SitesCreateCommand extends Command {
validate: (input) => /^[a-zA-Z\d-]+$/.test(input) || 'Only alphanumeric characters and hyphens are allowed',
},
])
name = results.name
name = nameInput
}

const body = {}
Expand Down
3 changes: 2 additions & 1 deletion src/function-builder-detectors/netlify-lambda.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ module.exports = function () {
const script = scripts[key]
const match = script.match(/netlify-lambda build (\S+)/)
if (match) {
settings.src = match[1]
const [, src] = match
settings.src = src
settings.npmScript = key
break
}
Expand Down
2 changes: 1 addition & 1 deletion src/functions-templates/js/fauna-crud/delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const client = new faunadb.Client({
})

exports.handler = async (event) => {
const id = event.id
const { id } = event
console.log(`Function 'delete' invoked. delete id: ${id}`)
return client
.query(q.Delete(q.Ref(`classes/items/${id}`)))
Expand Down
9 changes: 6 additions & 3 deletions src/functions-templates/js/fauna-crud/fauna-crud.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ exports.handler = async (event, context) => {
}
// e.g. GET /.netlify/functions/fauna-crud/123456
if (segments.length === 1) {
event.id = segments[0]
const [id] = segments
event.id = id
return require('./read').handler(event, context)
}
return {
Expand All @@ -25,7 +26,8 @@ exports.handler = async (event, context) => {
case 'PUT':
// e.g. PUT /.netlify/functions/fauna-crud/123456 with a body of key value pair objects, NOT strings
if (segments.length === 1) {
event.id = segments[0]
const [id] = segments
event.id = id
return require('./update').handler(event, context)
}
return {
Expand All @@ -36,7 +38,8 @@ exports.handler = async (event, context) => {
case 'DELETE':
// e.g. DELETE /.netlify/functions/fauna-crud/123456
if (segments.length === 1) {
event.id = segments[0]
const [id] = segments
event.id = id
return require('./delete').handler(event, context)
}
return {
Expand Down
2 changes: 1 addition & 1 deletion src/functions-templates/js/fauna-crud/read.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const client = new faunadb.Client({
})

exports.handler = async (event) => {
const id = event.id
const { id } = event
console.log(`Function 'read' invoked. Read id: ${id}`)
return client
.query(q.Get(q.Ref(`classes/items/${id}`)))
Expand Down
2 changes: 1 addition & 1 deletion src/functions-templates/js/fauna-crud/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const client = new faunadb.Client({

exports.handler = async (event) => {
const data = JSON.parse(event.body)
const id = event.id
const { id } = event
console.log(`Function 'update' invoked. update id: ${id}`)
return client
.query(q.Update(q.Ref(`classes/items/${id}`), { data }))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
const fetch = require('node-fetch')
const { EMAIL_TOKEN } = process.env
exports.handler = async (event) => {
const email = JSON.parse(event.body).payload.email
const { email } = JSON.parse(event.body).payload
console.log(`Recieved a submission: ${email}`)
return fetch('https://api.buttondown.email/v1/subscribers', {
method: 'POST',
Expand Down
2 changes: 1 addition & 1 deletion src/functions-templates/js/url-shortener/get-route.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const request = require('request')

module.exports = function handler(event, context, callback) {
// which URL code are we trying to retrieve?
const code = event.queryStringParameters.code
const { code } = event.queryStringParameters

// where is the data?
const url =
Expand Down
2 changes: 1 addition & 1 deletion src/lib/exec-fetcher.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const packages = [
]

packages.forEach(({ packageName, execName, execArgs, pattern, extension }) => {
const log = console.log
const { log } = console

test(`${packageName} - should return true on empty directory`, async (t) => {
const { binPath } = t.context
Expand Down
2 changes: 1 addition & 1 deletion src/utils/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ class BaseCommand extends Command {
// Set user data
this.netlify.globalConfig.set(`users.${userID}`, userData)

const email = user.email
const { email } = user
await identify({
name: user.full_name,
email,
Expand Down
7 changes: 4 additions & 3 deletions src/utils/detect-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ module.exports.serverSettings = async (devConfig, flags, projectDir, log) => {
if (detectorResult) settingsArr.push(detectorResult)
}
if (settingsArr.length === 1) {
settings = settingsArr[0]
const [firstSettings] = settingsArr
settings = firstSettings
settings.args = chooseDefaultArgs(settings.possibleArgsArrs)
} else if (settingsArr.length > 1) {
/** multiple matching detectors, make the user choose */
Expand Down Expand Up @@ -174,7 +175,7 @@ module.exports.serverSettings = async (devConfig, flags, projectDir, log) => {
const DEFAULT_PORT = 8888

async function getStaticServerSettings(settings, flags, projectDir, log) {
let dist = settings.dist
let { dist } = settings
if (flags.dir) {
log(`${NETLIFYDEVWARN} Using simple static server because --dir flag was specified`)
dist = flags.dir
Expand Down Expand Up @@ -211,7 +212,7 @@ module.exports.loadDetector = loadDetector

function chooseDefaultArgs(possibleArgsArrs) {
// vast majority of projects will only have one matching detector
const args = possibleArgsArrs[0] // just pick the first one
const [args] = possibleArgsArrs // just pick the first one
if (!args) {
const { scripts } = JSON.parse(fs.readFileSync('package.json', { encoding: 'utf8' }))
const err = new Error(
Expand Down
2 changes: 1 addition & 1 deletion src/utils/init/config-github.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const version = require('../../../package.json').version
const { version } = require('../../../package.json')
const os = require('os')
const ghauth = require('../../utils/gh-auth')
const { Octokit } = require('@octokit/rest')
Expand Down
6 changes: 4 additions & 2 deletions src/utils/link/link-by-prompt.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ Run ${chalk.cyanBright('git remote -v')} to see a list of your git remotes.`)

// Matches a single site hooray!
if (matchingSites.length === 1) {
site = matchingSites[0]
const [firstSite] = matchingSites
site = firstSite
} else if (matchingSites.length > 1) {
// Matches multiple sites. Users must choose which to link.
console.log(`Found ${matchingSites.length} matching sites!`)
Expand Down Expand Up @@ -156,7 +157,8 @@ or run ${chalk.cyanBright('netlify sites:create')} to create a site.`)
}
site = selectedSite
} else {
site = matchingSites[0]
const [firstSite] = matchingSites
site = firstSite
}
break
}
Expand Down
7 changes: 4 additions & 3 deletions src/utils/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,11 @@ async function serveRedirect(req, res, proxy, match, options) {
}

const destStaticFile = await getStatic(dest.pathname, options.publicFolder)
let status
let statusValue
if (match.force || (!staticFile && ((!options.framework && destStaticFile) || isInternal(destURL)))) {
req.url = destStaticFile ? destStaticFile + dest.search : destURL
status = match.status
const { status } = match
statusValue = status
console.log(`${NETLIFYDEVLOG} Rewrote URL to`, req.url)
}

Expand All @@ -225,7 +226,7 @@ async function serveRedirect(req, res, proxy, match, options) {
return proxy.web(req, res, { target: urlForAddons })
}

return proxy.web(req, res, { ...options, status })
return proxy.web(req, res, { ...options, status: statusValue })
}

return proxy.web(req, res, options)
Expand Down
4 changes: 2 additions & 2 deletions src/utils/telemetry/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ function track(eventName, payload) {
}

let userId = properties.userID
let cliId = properties.cliId
let { cliId } = properties

if (!userId) {
userId = globalConfig.get('userId')
Expand Down Expand Up @@ -117,7 +117,7 @@ function identify(payload) {
}

let userId = data.userID
let cliId = data.cliId
let { cliId } = data

if (!userId) {
userId = globalConfig.get('userId')
Expand Down
4 changes: 1 addition & 3 deletions src/utils/telemetry/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ module.exports = function isValidEventName(eventName, config) {
if (!containsSeparators(eventName) || !matches) {
return formattingWarning(eventName)
}
const project = matches[1]
const object = matches[2]
const action = matches[3]
const [, project, object, action] = matches
let error
// if missing any parts of event, exit
if (!project || !object || !action) {
Expand Down
2 changes: 1 addition & 1 deletion tests/command.dev.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,7 @@ testMatrix.forEach(({ args }) => {
test(testName('should redirect requests to an external server', args), async (t) => {
await withSiteBuilder('site-redirects-file-to-external', async (builder) => {
const server = startExternalServer()
const port = server.address().port
const { port } = server.address()
builder.withRedirectsFile({
redirects: [{ from: '/api/*', to: `http://localhost:${port}/:splat`, status: 200 }],
})
Expand Down
6 changes: 3 additions & 3 deletions tests/command.env.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ if (process.env.IS_FORK !== 'true') {
})

test.serial('env:get --json should return empty object if var not set', async (t) => {
const key = getArgsFromState(ENV_VAR_STATES.get)[0]
const [key] = getArgsFromState(ENV_VAR_STATES.get)

const cliResponse = await callCli(['env:get', '--json', key], t.context.execOptions)
const json = JSON.parse(cliResponse)
Expand Down Expand Up @@ -166,7 +166,7 @@ if (process.env.IS_FORK !== 'true') {

test.serial('env:set --json should be able to set var with empty value', async (t) => {
const args = getArgsFromState(ENV_VAR_STATES.setEmpty)
const key = args[0]
const [key] = args

const cliResponse = await callCli(['env:set', '--json', ...args], t.context.execOptions)
const json = JSON.parse(cliResponse)
Expand All @@ -177,7 +177,7 @@ if (process.env.IS_FORK !== 'true') {
})

test.serial('env:unset --json should remove existing variable', async (t) => {
const key = getArgsFromState(ENV_VAR_STATES.unset)[0]
const [key] = getArgsFromState(ENV_VAR_STATES.unset)

const cliResponse = await callCli(['env:unset', '--json', key], t.context.execOptions)
const json = JSON.parse(cliResponse)
Expand Down
2 changes: 1 addition & 1 deletion tests/utils/create-live-test-site.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async function createLiveTestSite(siteName) {

const matches = /Site ID:\s+([a-zA-Z\d-]+)/m.exec(stripAnsi(cliResponse))
if (matches && Object.prototype.hasOwnProperty.call(matches, 1) && matches[1]) {
const siteId = matches[1]
const [, siteId] = matches
console.log(`Done creating site ${siteName} for account '${accountSlug}'. Site Id: ${siteId}`)
return siteId
}
Expand Down

0 comments on commit a195eb4

Please sign in to comment.