Skip to content

Commit

Permalink
Add id-length ESLint rule (#1422)
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky authored Oct 22, 2020
1 parent a2128e9 commit 03e96e7
Show file tree
Hide file tree
Showing 45 changed files with 198 additions and 179 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ module.exports = {
'default-case-last': 2,
'func-name-matching': [2, { considerPropertyDescriptor: true }],
'func-names': [2, 'as-needed'],
'id-length': [2, { exceptions: ['t', '_'] }],
'line-comment-position': 2,
'max-classes-per-file': 2,
'max-params': [2, { max: 4 }],
Expand Down
4 changes: 2 additions & 2 deletions site/scripts/generate-command-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ module.exports = function generateCommandData() {
return groupedCommandsWithData
}

function commandFromPath(p) {
let normalized = path.normalize(p)
function commandFromPath(filePath) {
let normalized = path.normalize(filePath)

// console.log('commandFromPath', normalized)
// console.log('process.cwd()', process.cwd())
Expand Down
8 changes: 4 additions & 4 deletions site/src/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const scope = {
...Rebass,
code: LiveEditor,
pre: ({ children }) => children,
// eslint-disable-next-line react/display-name
// eslint-disable-next-line react/display-name, id-length
a: ({ children, href }) => {
// handle external links
if (!href.match(/^\//)) {
Expand Down Expand Up @@ -64,9 +64,9 @@ const pageNames = {

const sortRoutes = (routes) =>
[
...sortBy([...routes], (a) => {
const i = navOrder.indexOf(a.name)
return i < 0 ? Infinity : i
...sortBy([...routes], ({ name }) => {
const index = navOrder.indexOf(name)
return index < 0 ? Infinity : index
}),
].map((route) => {
if (!pageNames[route.name]) {
Expand Down
8 changes: 4 additions & 4 deletions site/src/_layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ const depthPad = ({ to = '' }) =>
(1 +
to
.split('/')
.filter((s) => s.length)
.filter((string) => string.length)
.slice(1).length) *
DEPTH_PAD_INCREMENT

Expand Down Expand Up @@ -254,10 +254,10 @@ const MyHits = createConnector({
},
})(({ query, hits }) => {
if (hits && query) {
return hits.map((hit, i) => {
return hits.map((hit, index) => {
const slug = hit.name.replace(/:/g, '')
return (
<HitsOverlay key={i}>
<HitsOverlay key={index}>
<a href={`/commands/${slug}`}>
<span style={{ minWidth: MIN_WIDTH, display: 'inline-block', fontWeight: 'bold' }}>
<Highlight attribute="name" hit={hit} />
Expand Down Expand Up @@ -371,7 +371,7 @@ export default class Layout extends React.Component {

const Wrapper = opts.fullWidth ? React.Fragment : MaxWidth

const index = routes.findIndex((r) => r.path === route.path)
const index = routes.findIndex((thisRoute) => thisRoute.path === route.path)
const pagination = {
previous: routes[index - 1],
next: routes[index + 1],
Expand Down
4 changes: 2 additions & 2 deletions site/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ const config = require('./config')
const { copyDirRecursiveAsync } = require('./fs')

async function readDir(dir, allFiles = []) {
const files = (await fs.readdir(dir)).map((f) => path.join(dir, f))
const files = (await fs.readdir(dir)).map((file) => path.join(dir, file))
allFiles.push(...files)
await Promise.all(files.map(async (f) => (await fs.stat(f)).isDirectory() && readDir(f, allFiles)))
await Promise.all(files.map(async (file) => (await fs.stat(file)).isDirectory() && readDir(file, allFiles)))
return allFiles
}

Expand Down
4 changes: 2 additions & 2 deletions src/commands/addons/delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ class AddonsDeleteCommand extends Command {
validation: ADDON_VALIDATION.EXISTS,
})

const { force, f } = parseRawFlags(raw)
if (!force && !f) {
const rawFlags = parseRawFlags(raw)
if (!rawFlags.force && !rawFlags.f) {
const { wantsToDelete } = await inquirer.prompt({
type: 'confirm',
name: 'wantsToDelete',
Expand Down
4 changes: 2 additions & 2 deletions src/commands/addons/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ class AddonsListCommand extends Command {

table.setHeading('NameSpace', 'Name', 'Instance Id')

addonData.forEach((s) => {
table.addRow(s.namespace, s.name, s.id)
addonData.forEach(({ namespace, name, id }) => {
table.addRow(namespace, name, id)
})
// Log da addons
this.log(table.toString())
Expand Down
4 changes: 3 additions & 1 deletion src/commands/dev/exec.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ class ExecCommand extends Command {
const envSettings = await getEnvSettings({ projectDir: site.root, warn: this.warn })
if (envSettings.vars.length !== 0) {
this.log(
`${NETLIFYDEVLOG} Adding the following env variables from ${envSettings.files.map((f) => chalk.blue(f))}:`,
`${NETLIFYDEVLOG} Adding the following env variables from ${envSettings.files.map((file) =>
chalk.blue(file),
)}:`,
chalk.yellow(envSettings.vars.map(([key]) => key)),
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/commands/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const addDotFileEnvs = async ({ site, log, warn }) => {
const envSettings = await getEnvSettings({ projectDir: site.root, warn })
if (envSettings.vars.length !== 0) {
log(
`${NETLIFYDEVLOG} Adding the following env variables from ${envSettings.files.map((f) => chalk.blue(f))}:`,
`${NETLIFYDEVLOG} Adding the following env variables from ${envSettings.files.map((file) => chalk.blue(file))}:`,
chalk.yellow(envSettings.vars.map(([key]) => key)),
)
envSettings.vars.forEach(([key, val]) => {
Expand Down
25 changes: 16 additions & 9 deletions src/commands/functions/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,25 +140,29 @@ async function pickTemplate() {
]
}
// only show filtered results sorted by score
const ans = [
const answers = [
...filterRegistry(jsreg, input),
// ...filterRegistry(tsreg, input),
// ...filterRegistry(goreg, input)
...specialCommands,
].sort((a, b) => b.score - a.score)
return ans
].sort((answerA, answerB) => answerB.score - answerA.score)
return answers
},
})
return chosentemplate
function filterRegistry(registry, input) {
const temp = registry.map((x) => x.name + x.description)
const temp = registry.map((value) => value.name + value.description)
const filteredTemplates = fuzzy.filter(input, temp)
const filteredTemplateNames = new Set(filteredTemplates.map((x) => (input ? x.string : x)))
const filteredTemplateNames = new Set(
filteredTemplates.map((filteredTemplate) => (input ? filteredTemplate.string : filteredTemplate)),
)
return registry
.filter((t) => filteredTemplateNames.has(t.name + t.description))
.map((t) => {
// add the score
const { score } = filteredTemplates.find((f) => f.string === t.name + t.description)
const { score } = filteredTemplates.find(
(filteredTemplate) => filteredTemplate.string === t.name + t.description,
)
t.score = score
return t
})
Expand All @@ -167,9 +171,12 @@ async function pickTemplate() {
const folderNames = fs.readdirSync(path.join(templatesDir, lang))
const registry = folderNames
// filter out markdown files
.filter((x) => !x.endsWith('.md'))
.map((name) => require(path.join(templatesDir, lang, name, '.netlify-function-template.js')))
.sort((a, b) => (a.priority || DEFAULT_PRIORITY) - (b.priority || DEFAULT_PRIORITY))
.filter((folderName) => !folderName.endsWith('.md'))
.map((folderName) => require(path.join(templatesDir, lang, folderName, '.netlify-function-template.js')))
.sort(
(folderNameA, folderNameB) =>
(folderNameA.priority || DEFAULT_PRIORITY) - (folderNameB.priority || DEFAULT_PRIORITY),
)
.map((t) => {
t.lang = lang
return {
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 @@ -263,14 +263,14 @@ module.exports = FunctionsInvokeCommand
// https://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try
function tryParseJSON(jsonString) {
try {
const o = JSON.parse(jsonString)
const parsedValue = JSON.parse(jsonString)

// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === 'object') {
return o
if (parsedValue && typeof parsedValue === 'object') {
return parsedValue
}
// eslint-disable-next-line no-empty
} catch (error) {}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/functions/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class FunctionsListCommand extends Command {

if (flags.json) {
const jsonData = functionData.map(([functionName, { moduleDir }]) => {
const isDeployed = deployedFunctions.map(({ n }) => n).includes(functionName)
const isDeployed = deployedFunctions.map((deployedFunction) => deployedFunction.n).includes(functionName)
return {
name: functionName,
url: `/.netlify/functions/${functionName}`,
Expand All @@ -81,7 +81,7 @@ class FunctionsListCommand extends Command {
const table = new AsciiTable(`Netlify Functions (in local functions folder)`)
table.setHeading('Name', 'Url', 'moduleDir', 'deployed')
functionData.forEach(([functionName, { moduleDir }]) => {
const isDeployed = deployedFunctions.map(({ n }) => n).includes(functionName)
const isDeployed = deployedFunctions.map((deployedFunction) => deployedFunction.n).includes(functionName)
table.addRow(functionName, `/.netlify/functions/${functionName}`, moduleDir, isDeployed ? 'yes' : 'no')
})
this.log(table.toString())
Expand Down
4 changes: 2 additions & 2 deletions src/commands/sites/delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ class SitesDeleteCommand extends Command {
},
})

const { force, f } = parseRawFlags(raw)
const noForce = !force && !f
const rawFlags = parseRawFlags(raw)
const noForce = !rawFlags.force && !rawFlags.f

/* Verify the user wants to delete the site */
if (noForce) {
Expand Down
14 changes: 7 additions & 7 deletions src/commands/sites/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ class SitesListCommand extends Command {
Count: ${logSites.length}
`)

logSites.forEach((s) => {
this.log(`${chalk.greenBright(s.name)} - ${s.id}`)
this.log(` ${chalk.whiteBright.bold('url:')} ${chalk.yellowBright(s.ssl_url)}`)
if (s.repo_url) {
this.log(` ${chalk.whiteBright.bold('repo:')} ${chalk.white(s.repo_url)}`)
logSites.forEach((logSite) => {
this.log(`${chalk.greenBright(logSite.name)} - ${logSite.id}`)
this.log(` ${chalk.whiteBright.bold('url:')} ${chalk.yellowBright(logSite.ssl_url)}`)
if (logSite.repo_url) {
this.log(` ${chalk.whiteBright.bold('repo:')} ${chalk.white(logSite.repo_url)}`)
}
if (s.account_name) {
this.log(` ${chalk.whiteBright.bold('account:')} ${chalk.white(s.account_name)}`)
if (logSite.account_name) {
this.log(` ${chalk.whiteBright.bold('account:')} ${chalk.white(logSite.account_name)}`)
}
this.log(`─────────────────────────────────────────────────`)
})
Expand Down
4 changes: 3 additions & 1 deletion src/commands/switch.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ class SwitchCommand extends Command {
if (accountSwitchChoice === LOGIN_NEW) {
await LoginCommand.run(['--new'])
} else {
const selectedAccount = Object.entries(availableUsersChoices).find(([, v]) => v === accountSwitchChoice)
const selectedAccount = Object.entries(availableUsersChoices).find(
([, availableUsersChoice]) => availableUsersChoice === accountSwitchChoice,
)
this.netlify.globalConfig.set('userId', selectedAccount[0])
this.log('')
this.log(`You're now using ${chalk.bold(selectedAccount[1])}.`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const resolvers = {
author: () => {},
authorByName: (root, args) => {
console.log('hihhihi', args.name)
return authors.find((x) => x.name === args.name) || 'NOTFOUND'
return authors.find((author) => author.name === args.name) || 'NOTFOUND'
},
},
}
Expand Down
12 changes: 5 additions & 7 deletions src/functions-templates/js/fauna-crud/create-schema.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,26 @@
#!/usr/bin/env node

/* bootstrap database in your FaunaDB account - use with `netlify dev:exec <path-to-this-file>` */
const faunadb = require('faunadb')

const q = faunadb.query
const { query, Client } = require('faunadb')

function createFaunaDB() {
if (!process.env.FAUNADB_SERVER_SECRET) {
console.log('No FAUNADB_SERVER_SECRET in environment, skipping DB setup')
}
console.log('Create the database!')
const client = new faunadb.Client({
const client = new Client({
secret: process.env.FAUNADB_SERVER_SECRET,
})

/* Based on your requirements, change the schema here */
return client
.query(q.Create(q.Ref('classes'), { name: 'items' }))
.query(query.Create(query.Ref('classes'), { name: 'items' }))
.then(() => {
console.log('Created items class')
return client.query(
q.Create(q.Ref('indexes'), {
query.Create(query.Ref('indexes'), {
name: 'all_items',
source: q.Ref('classes/items'),
source: query.Ref('classes/items'),
active: true,
}),
)
Expand Down
7 changes: 3 additions & 4 deletions src/functions-templates/js/fauna-crud/create.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const faunadb = require('faunadb')
const { query, Client } = require('faunadb')

/* configure faunaDB Client with our secret */
const q = faunadb.query
const client = new faunadb.Client({
const client = new Client({
secret: process.env.FAUNADB_SERVER_SECRET,
})

Expand All @@ -16,7 +15,7 @@ const handler = async (event) => {
}
/* construct the fauna query */
return client
.query(q.Create(q.Ref('classes/items'), item))
.query(query.Create(query.Ref('classes/items'), item))
.then((response) => {
console.log('success', response)
/* Success! return the response with statusCode 200 */
Expand Down
7 changes: 3 additions & 4 deletions src/functions-templates/js/fauna-crud/delete.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
/* Import faunaDB sdk */
const faunadb = require('faunadb')
const { query, Client } = require('faunadb')

const q = faunadb.query
const client = new faunadb.Client({
const client = new Client({
secret: process.env.FAUNADB_SERVER_SECRET,
})

const handler = async (event) => {
const { id } = event
console.log(`Function 'delete' invoked. delete id: ${id}`)
return client
.query(q.Delete(q.Ref(`classes/items/${id}`)))
.query(query.Delete(query.Ref(`classes/items/${id}`)))
.then((response) => {
console.log('success', response)
return {
Expand Down
2 changes: 1 addition & 1 deletion src/functions-templates/js/fauna-crud/fauna-crud.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const handler = async (event, context) => {
const path = event.path.replace(/\.netlify\/functions\/[^/]+/, '')
const segments = path.split('/').filter((e) => e)
const segments = path.split('/').filter(Boolean)

switch (event.httpMethod) {
case 'GET':
Expand Down
9 changes: 4 additions & 5 deletions src/functions-templates/js/fauna-crud/read-all.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
/* Import faunaDB sdk */
const faunadb = require('faunadb')
const { query, Client } = require('faunadb')

const q = faunadb.query
const client = new faunadb.Client({
const client = new Client({
secret: process.env.FAUNADB_SERVER_SECRET,
})

const handler = async () => {
console.log('Function `read-all` invoked')
return client
.query(q.Paginate(q.Match(q.Ref('indexes/all_items'))))
.query(query.Paginate(query.Match(query.Ref('indexes/all_items'))))
.then((response) => {
const itemRefs = response.data
// create new query out of item refs. http://bit.ly/2LG3MLg
const getAllItemsDataQuery = itemRefs.map((ref) => {
return q.Get(ref)
return query.Get(ref)
})
// then query the refs
return client.query(getAllItemsDataQuery).then((ret) => {
Expand Down
7 changes: 3 additions & 4 deletions src/functions-templates/js/fauna-crud/read.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
/* Import faunaDB sdk */
const faunadb = require('faunadb')
const { query, Client } = require('faunadb')

const q = faunadb.query
const client = new faunadb.Client({
const client = new Client({
secret: process.env.FAUNADB_SERVER_SECRET,
})

const handler = async (event) => {
const { id } = event
console.log(`Function 'read' invoked. Read id: ${id}`)
return client
.query(q.Get(q.Ref(`classes/items/${id}`)))
.query(query.Get(query.Ref(`classes/items/${id}`)))
.then((response) => {
console.log('success', response)
return {
Expand Down
Loading

0 comments on commit 03e96e7

Please sign in to comment.