Skip to content
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

Add prefer-template ESLint rule #1401

Merged
merged 1 commit into from
Oct 21, 2020
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
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ module.exports = {
'prefer-regex-literals': [2, { disallowRedundantWrapping: true }],
'prefer-rest-params': 2,
'prefer-spread': 2,
'prefer-template': 2,
'radix': [2, 'as-needed'],

// TODO: enable the following rules
Expand Down
2 changes: 1 addition & 1 deletion site/src/_layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ const depthPad = ({ to = '' }) =>
.slice(1).length) *
16

const Link = styled((props) => <NavLink {...props} is={RouterNavLink} w={1} pl={depthPad(props) - 4 + 'px'} />)(
const Link = styled((props) => <NavLink {...props} is={RouterNavLink} w={1} pl={`${depthPad(props) - 4}px`} />)(
[],
() => ({
'borderLeft': '4px solid',
Expand Down
16 changes: 8 additions & 8 deletions src/commands/functions/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,9 @@ async function pickTemplate() {
t.lang = lang
return {
// confusing but this is the format inquirer wants
name: `[${t.name}] ` + t.description,
name: `[${t.name}] ${t.description}`,
value: t,
short: lang + '-' + t.name,
short: `${lang}-${t.name}`,
}
})
return registry
Expand Down Expand Up @@ -207,7 +207,7 @@ async function downloadFromURL(context, flags, args, functionsDir) {
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()) {
if (fs.existsSync(`${fnFolder}.js`) && fs.lstatSync(`${fnFolder}.js`).isFile()) {
context.log(
`${NETLIFYDEVWARN}: A single file version of the function ${nameToUse} already exists at ${fnFolder}.js. Terminating without further action.`
)
Expand All @@ -223,12 +223,12 @@ async function downloadFromURL(context, flags, args, functionsDir) {
folderContents.map(({ name, download_url: downloadUrl }) => {
return fetch(downloadUrl)
.then((res) => {
const finalName = path.basename(name, '.js') === functionName ? nameToUse + '.js' : name
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}`)
throw new Error(`Error while retrieving ${downloadUrl} ${error}`)
})
})
)
Expand Down Expand Up @@ -278,7 +278,7 @@ async function scaffoldFromTemplate(context, flags, args, functionsDir) {
try {
await downloadFromURL(context, flags, args, functionsDir)
} catch (error) {
context.error(`$${NETLIFYDEVERR} Error downloading from URL: ` + flags.url)
context.error(`$${NETLIFYDEVERR} Error downloading from URL: ${flags.url}`)
context.error(error)
process.exit(1)
}
Expand Down Expand Up @@ -314,7 +314,7 @@ async function scaffoldFromTemplate(context, flags, args, functionsDir) {
fs.unlinkSync(path.join(functionPath, '.netlify-function-template.js'))
// rename the root function file if it has a different name from default
if (name !== templateName) {
fs.renameSync(path.join(functionPath, templateName + '.js'), path.join(functionPath, name + '.js'))
fs.renameSync(path.join(functionPath, `${templateName}.js`), path.join(functionPath, `${name}.js`))
}
// npm install
if (hasPackageJSON) {
Expand Down Expand Up @@ -374,7 +374,7 @@ async function installAddons(context, functionAddons = [], fnPath) {
])

const arr = functionAddons.map(async ({ addonName, addonDidInstall }) => {
log(`${NETLIFYDEVLOG} installing addon: ` + chalk.yellow.inverse(addonName))
log(`${NETLIFYDEVLOG} installing addon: ${chalk.yellow.inverse(addonName)}`)
try {
const addonCreated = await createFunctionAddon({
api,
Expand Down
4 changes: 2 additions & 2 deletions src/commands/functions/invoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ class FunctionsInvokeCommand extends Command {
body = { ...body, ...payload }

// fetch
fetch(`http://localhost:${port}/.netlify/functions/${functionToTrigger}` + formatQstring(flags.querystring), {
fetch(`http://localhost:${port}/.netlify/functions/${functionToTrigger}${formatQstring(flags.querystring)}`, {
method: 'post',
headers,
body: JSON.stringify(body),
Expand All @@ -143,7 +143,7 @@ class FunctionsInvokeCommand extends Command {

function formatQstring(querystring) {
if (querystring) {
return '?' + querystring
return `?${querystring}`
}
return ''
}
Expand Down
2 changes: 1 addition & 1 deletion src/functions-templates/js/fauna-graphql/fauna-graphql.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const handler = async function (event, context) {
}
}
const b64encodedSecret = Buffer.from(
process.env.FAUNADB_SERVER_SECRET + ':' // weird but they
`${process.env.FAUNADB_SERVER_SECRET}:` // weird but they
).toString('base64')
const headers = { Authorization: `Basic ${b64encodedSecret}` }

Expand Down
2 changes: 1 addition & 1 deletion src/functions-templates/js/fauna-graphql/sync-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function createFaunaGraphQL() {
const dataString = fs.readFileSync(path.join(__dirname, 'schema.graphql')).toString() // name of your schema file

// encoded authorization header similar to https://www.npmjs.com/package/request#http-authentication
const token = Buffer.from(process.env.FAUNADB_SERVER_SECRET + ':').toString('base64')
const token = Buffer.from(`${process.env.FAUNADB_SERVER_SECRET}:`).toString('base64')

const options = {
method: 'POST',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ async function getSchema(endpoint) {
// process.env.URL is one of many build env variables:
// https://www.netlify.com/docs/continuous-deployment/#build-environment-variables
// Netlify Dev only supports URL and DEPLOY URL for now
const uri = process.env.URL + '/.netlify/functions/' + endpoint
const uri = `${process.env.URL}/.netlify/functions/${endpoint}`
const link = createHttpLink({ uri, fetch })
const schema = await introspectSchema(link)
const executableSchema = makeRemoteExecutableSchema({ schema, link })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const handler = async (event) => {
content: filter.clean(request.event.data.new.content),
}
try {
await axios.post(hgeEndpoint + '/v1alpha1/graphql', { query, variables })
await axios.post(`${hgeEndpoint}/v1alpha1/graphql`, { query, variables })
return { statusCode: 200, body: 'success' }
} catch (error) {
return { statusCode: 500, body: error.toString() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,11 @@ module.exports = function handler(event, context, callback) {
.catch((error) => {
callback(null, {
statusCode: 500,
body: 'Internal Server Error: ' + error,
body: `Internal Server Error: ${error}`,
})
})
} catch (error) {
callback(null, { statusCode: 500, body: 'Internal Server Error: ' + error })
callback(null, { statusCode: 500, body: `Internal Server Error: ${error}` })
}
})
}
4 changes: 2 additions & 2 deletions src/functions-templates/js/url-shortener/generate-route.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const Hashids = require('hashids')

module.exports = function handler(event, context, callback) {
// Set the root URL according to the Netlify site we are within
const rootURL = process.env.URL + '/'
const rootURL = `${process.env.URL}/`

// get the details of what we are creating
let destination = event.queryStringParameters.to
Expand All @@ -17,7 +17,7 @@ module.exports = function handler(event, context, callback) {

// ensure that a protocol was provided
if (!destination.includes('://')) {
destination = 'http://' + destination
destination = `http://${destination}`
}

// prepare a payload to post
Expand Down
8 changes: 2 additions & 6 deletions src/functions-templates/js/url-shortener/get-route.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ module.exports = function handler(event, context, callback) {
const { code } = event.queryStringParameters

// where is the data?
const url =
'https://api.netlify.com/api/v1/forms/' +
process.env.ROUTES_FORM_ID +
'/submissions/?access_token=' +
process.env.API_AUTH
const url = `https://api.netlify.com/api/v1/forms/${process.env.ROUTES_FORM_ID}/submissions/?access_token=${process.env.API_AUTH}`

request(url, function onResponse(err, response, body) {
// look for this code in our stash
Expand All @@ -21,7 +17,7 @@ module.exports = function handler(event, context, callback) {
for (const item in routes) {
// return the result when we find the match
if (routes[item].data.code === code) {
console.log('We searched for ' + code + ' and we found ' + routes[item].data.destination)
console.log(`We searched for ${code} and we found ${routes[item].data.destination}`)
return callback(null, {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
Expand Down
2 changes: 1 addition & 1 deletion src/utils/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ class BaseCommand extends Command {
return
}
message = typeof message === 'string' ? message : inspect(message)
process.stdout.write(format(message, ...args) + '\n')
process.stdout.write(`${format(message, ...args)}\n`)
}

/* Modified flag parser to support global --auth, --json, & --silent flags */
Expand Down
2 changes: 1 addition & 1 deletion src/utils/detect-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ function formatSettingsArrForInquirer(settingsArr) {
setting.possibleArgsArrs.map((args) => ({
name: `[${chalk.yellow(setting.framework)}] ${setting.command} ${args.join(' ')}`,
value: { ...setting, args },
short: setting.framework + '-' + args.join(' '),
short: `${setting.framework}-${args.join(' ')}`,
}))
)
)
Expand Down
21 changes: 9 additions & 12 deletions src/utils/gh-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ async function getGitHubToken({ opts, log }) {
if (parameters.token) {
deferredResolve(parameters)
res.end(
"<html><head><script>if(history.replaceState){history.replaceState({},'','/')}</script><style>html{font-family:sans-serif;background:#0e1e25}body{overflow:hidden;position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;width:100vw;}h3{margin:0}.card{position:relative;display:flex;flex-direction:column;width:75%;max-width:364px;padding:24px;background:white;color:rgb(14,30,37);border-radius:8px;box-shadow:0 2px 4px 0 rgba(14,30,37,.16);}</style></head>" +
"<body><div class=card><h3>Logged In</h3><p>You're now logged into Netlify CLI with your " +
parameters.provider +
' credentials. Please close this window.</p></div>'
`${
"<html><head><script>if(history.replaceState){history.replaceState({},'','/')}</script><style>html{font-family:sans-serif;background:#0e1e25}body{overflow:hidden;position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;width:100vw;}h3{margin:0}.card{position:relative;display:flex;flex-direction:column;width:75%;max-width:364px;padding:24px;background:white;color:rgb(14,30,37);border-radius:8px;box-shadow:0 2px 4px 0 rgba(14,30,37,.16);}</style></head>" +
"<body><div class=card><h3>Logged In</h3><p>You're now logged into Netlify CLI with your "
}${parameters.provider} credentials. Please close this window.</p></div>`
)
server.close()
return
Expand All @@ -79,13 +79,10 @@ async function getGitHubToken({ opts, log }) {
})

const webUI = process.env.NETLIFY_WEB_UI || 'https://app.netlify.com'
const url =
webUI +
'/cli?' +
querystring.encode({
host: 'http://localhost:' + port,
provider: 'github',
})
const url = `${webUI}/cli?${querystring.encode({
host: `http://localhost:${port}`,
provider: 'github',
})}`

await openBrowser({ url, log })

Expand Down Expand Up @@ -119,7 +116,7 @@ async function getGitHubToken({ opts, log }) {
})

const response = await octokit.oauthAuthorizations.createAuthorization({
note: opts.note + ' (' + new Date().toJSON() + ')',
note: `${opts.note} (${new Date().toJSON()})`,
note_url: 'https://cli.netlify.com/',
scopes: opts.scopes,
headers: {
Expand Down
4 changes: 2 additions & 2 deletions src/utils/init/config-github.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const fs = require('fs')
const chalk = require('chalk')
const { makeNetlifyTOMLtemplate } = require('./netlify-toml-template')

const UA = 'Netlify CLI ' + version
const UA = `Netlify CLI ${version}`

module.exports = configGithub
async function configGithub(ctx, site, repo) {
Expand Down Expand Up @@ -58,7 +58,7 @@ async function configGithub(ctx, site, repo) {
if (build && build.publish) {
defaultBuildDir = build.publish
}
if (build && build.functions) console.log('Netlify functions folder is ' + chalk.yellow(build.functions))
if (build && build.functions) console.log(`Netlify functions folder is ${chalk.yellow(build.functions)}`)
const { buildCmd, buildDir } = await inquirer.prompt([
{
type: 'input',
Expand Down
2 changes: 1 addition & 1 deletion src/utils/live-tunnel.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async function createTunnel({ siteId, netlifyApiToken, log }) {
)
process.exit(1)
}
log(`${NETLIFYDEVLOG} Creating Live Tunnel for ` + siteId)
log(`${NETLIFYDEVLOG} Creating Live Tunnel for ${siteId}`)
const url = `https://api.netlify.com/api/v1/live_sessions?site_id=${siteId}`

const response = await fetch(url, {
Expand Down
18 changes: 9 additions & 9 deletions src/utils/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,16 @@ function alternativePathsFor(url) {
if (url[url.length - 1] === '/') {
const end = url.length - 1
if (url !== '/') {
paths.push(url.slice(0, end) + '.html')
paths.push(url.slice(0, end) + '.htm')
paths.push(`${url.slice(0, end)}.html`)
paths.push(`${url.slice(0, end)}.htm`)
}
paths.push(url + 'index.html')
paths.push(url + 'index.htm')
paths.push(`${url}index.html`)
paths.push(`${url}index.htm`)
} else if (!url.match(assetExtensionRegExp)) {
paths.push(url + '.html')
paths.push(url + '.htm')
paths.push(url + '/index.html')
paths.push(url + '/index.htm')
paths.push(`${url}.html`)
paths.push(`${url}.htm`)
paths.push(`${url}/index.html`)
paths.push(`${url}/index.htm`)
}

return paths
Expand Down Expand Up @@ -148,7 +148,7 @@ async function serveRedirect({ req, res, proxy, match, options }) {

const reqUrl = new url.URL(
req.url,
`${req.protocol || (req.headers.scheme && req.headers.scheme + ':') || 'http:'}//${
`${req.protocol || (req.headers.scheme && `${req.headers.scheme}:`) || 'http:'}//${
req.headers.host || req.hostname
}`
)
Expand Down
2 changes: 1 addition & 1 deletion src/utils/rules-proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const createRewriter = async function ({ distDir, projectDir, jwtSecret, jwtRole
getMatcher().then((matcher) => {
const reqUrl = new url.URL(
req.url,
`${req.protocol || (req.headers.scheme && req.headers.scheme + ':') || 'http:'}//${
`${req.protocol || (req.headers.scheme && `${req.headers.scheme}:`) || 'http:'}//${
req.hostname || req.headers.host
}`
)
Expand Down
4 changes: 2 additions & 2 deletions src/utils/serve-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const { detectFunctionsBuilder } = require('./detect-functions-builder')

function handleErr(err, response) {
response.statusCode = 500
response.write(`${NETLIFYDEVERR} Function invocation failed: ` + err.toString())
response.write(`${NETLIFYDEVERR} Function invocation failed: ${err.toString()}`)
response.end()
console.log(`${NETLIFYDEVERR} Error during invocation:`, err)
}
Expand Down Expand Up @@ -189,7 +189,7 @@ function createFormSubmissionHandler(siteInfo) {
fakeRequest.headers = req.headers

const originalUrl = new URL(req.url, 'http://localhost')
req.url = '/.netlify/functions/submission-created' + originalUrl.search
req.url = `/.netlify/functions/submission-created${originalUrl.search}`

const ct = contentType.parse(req)
let fields = {}
Expand Down
2 changes: 1 addition & 1 deletion tests/command.functions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ test('should return function response when invoked', async (t) => {
await builder.buildAsync()

await withDevServer({ cwd: builder.directory }, async (server) => {
const { stdout } = await execa(cliPath, ['functions:invoke', 'ping', '--identity', '--port=' + server.port], {
const { stdout } = await execa(cliPath, ['functions:invoke', 'ping', '--identity', `--port=${server.port}`], {
cwd: builder.directory,
})

Expand Down