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

Enforce use of template literals #2242

Merged
merged 6 commits into from
Nov 2, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ rules:
strict: "error"
arrow-body-style: ["error", "as-needed"]
no-extension-in-require/main: "error"
prefer-template: "error"

# Mocha-related.
mocha/no-exclusive-tests: "error"
Expand Down
2 changes: 1 addition & 1 deletion frontend/components/badge-examples.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ const Category = ({ category, examples, baseUrl, longCache, onClick }) => {
}
return (
<div>
<Link to={'/examples/' + category.id}>
<Link to={`/examples/${category.id}`}>
<h3 id={category.id}>{category.name}</h3>
</Link>
<table className="badge">
Expand Down
2 changes: 1 addition & 1 deletion frontend/components/search-results.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default class SearchResults extends React.Component {

renderCategoryHeadings() {
return this.preparedExamples.map((category, i) => (
<Link to={'/examples/' + category.category.id} key={category.category.id}>
<Link to={`/examples/${category.category.id}`} key={category.category.id}>
<h3 id={category.category.id}>{category.category.name}</h3>
</Link>
))
Expand Down
4 changes: 1 addition & 3 deletions lib/badge-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ if (process.argv.length < 4) {
'Or: badge subject status right-color [left-color] [.output] [@style]'
)
console.log()
console.log(
' colorscheme: one of ' + Object.keys(colorscheme).join(', ') + '.'
)
console.log(` colorscheme: one of ${Object.keys(colorscheme).join(', ')}.`)
console.log(' left-color, right-color:')
console.log(' #xxx (three hex digits)')
console.log(' #xxxxxx (six hex digits)')
Expand Down
15 changes: 7 additions & 8 deletions lib/badge-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function prependPrefix(s, prefix) {
return undefined
}

s = '' + s
s = `${s}`

if (s.startsWith(prefix)) {
return s
Expand All @@ -36,7 +36,7 @@ function isHexColor(s = '') {

function makeColor(color) {
if (isHexColor(color)) {
return '#' + color
return `#${color}`
} else if (colorschemes[color] !== undefined) {
return colorschemes[color].colorB
} else if (isCSSColor(color)) {
Expand All @@ -52,7 +52,7 @@ function makeColorB(defaultColor, overrides) {

function setBadgeColor(badgeData, color) {
if (isHexColor(color)) {
badgeData.colorB = '#' + color
badgeData.colorB = `#${color}`
delete badgeData.colorscheme
} else if (colorschemes[color] !== undefined) {
badgeData.colorscheme = color
Expand All @@ -68,12 +68,11 @@ function setBadgeColor(badgeData, color) {
}

function makeLabel(defaultLabel, overrides) {
return (
'' +
(overrides.label === undefined
return `${
overrides.label === undefined
? (defaultLabel || '').toLowerCase()
: overrides.label)
)
: overrides.label
}`
}

function getShieldsIcon(icon = '', color = '') {
Expand Down
2 changes: 1 addition & 1 deletion lib/color-formatters.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function version(version) {
if (typeof version !== 'string' && typeof version !== 'number') {
throw new Error(`Can't generate a version color for ${version}`)
}
version = '' + version
version = `${version}`
let first = version[0]
if (first === 'v') {
first = version[1]
Expand Down
10 changes: 5 additions & 5 deletions lib/github-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ function setRoutes(server) {
}
const query = queryString.stringify({
client_id: serverSecrets.gh_client_id,
redirect_uri: baseUrl + '/github-auth/done',
redirect_uri: `${baseUrl}/github-auth/done`,
})
ask.res.statusCode = 302 // Found.
ask.res.setHeader(
'Location',
'https://github.com/login/oauth/authorize?' + query
`https://github.com/login/oauth/authorize?${query}`
)
end('')
})
Expand Down Expand Up @@ -125,7 +125,7 @@ function sendTokenToAllServers(token) {
ip =>
new Promise((resolve, reject) => {
const options = {
url: 'https://' + ip + '/github-auth/add-token',
url: `https://${ip}/github-auth/add-token`,
method: 'POST',
form: {
shieldsSecret: serverSecrets.shieldsSecret,
Expand Down Expand Up @@ -298,7 +298,7 @@ function githubRequest(request, url, query, cb) {

if (githubToken != null) {
// Typically, GitHub user tokens grants us 12500 req/hour.
headers['Authorization'] = 'token ' + githubToken
headers['Authorization'] = `token ${githubToken}`
} else if (serverSecrets && serverSecrets.gh_client_id) {
// Using our OAuth App secret grants us 5000 req/hour
// instead of the standard 60 req/hour.
Expand All @@ -308,7 +308,7 @@ function githubRequest(request, url, query, cb) {

const qs = queryString.stringify(query)
if (qs) {
url += '?' + qs
url += `?${qs}`
}

request(url, { headers: headers }, (err, res, buffer) => {
Expand Down
2 changes: 1 addition & 1 deletion lib/load-logos.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ function loadLogos() {
return
}
// filename is eg, github.svg
const svg = fs.readFileSync(logoDir + '/' + filename).toString()
const svg = fs.readFileSync(`${logoDir}/${filename}`).toString()
const base64 = svg2base64(svg)

// eg, github
Expand Down
2 changes: 1 addition & 1 deletion lib/log.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const listeners = []
// eg. 4 becomes 04 but 17 stays 17.
function pad(string) {
string = String(string)
return string.length < 2 ? '0' + string : string
return string.length < 2 ? `0${string}` : string
}

// Compact date representation.
Expand Down
2 changes: 1 addition & 1 deletion lib/logo-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function svg2base64(svg) {
// Check if logo is already base64
return isDataUri(svg)
? svg
: 'data:image/svg+xml;base64,' + Buffer.from(svg).toString('base64')
: `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`
}

module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion lib/lru-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ Cache.prototype = {
return 0
}
} else {
console.error("Unknown heuristic '" + this.type + "' for LRU cache.")
console.error(`Unknown heuristic '${this.type}' for LRU cache.`)
return 1
}
},
Expand Down
10 changes: 5 additions & 5 deletions lib/make-badge.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ templateFiles.forEach(async filename => {
.readFileSync(path.join(__dirname, '..', 'templates', filename))
.toString()
const extension = path.extname(filename).slice(1)
const style = filename.slice(0, -('-template.' + extension).length)
const style = filename.slice(0, -`-template.${extension}`.length)
// Compile the template. Necessary to always have a working template.
templates[style + '-' + extension] = dot.template(templateData)
templates[`${style}-${extension}`] = dot.template(templateData)
if (extension === 'svg') {
// Substitute dot code.
const mapping = new Map()
let mappingIndex = 1
const untemplatedSvg = templateData.replace(/{{.*?}}/g, match => {
// Weird substitution that currently works for all templates.
const mapKey = '99999990' + mappingIndex + '.1'
const mapKey = `99999990${mappingIndex}.1`
mappingIndex++
mapping.set(mapKey, match)
return mapKey
Expand Down Expand Up @@ -74,7 +74,7 @@ templateFiles.forEach(async filename => {
return
}

templates[style + '-' + extension] = dot.template(svg)
templates[`${style}-${extension}`] = dot.template(svg)
}
})

Expand Down Expand Up @@ -125,7 +125,7 @@ function makeBadge(
}
) {
// String coercion.
text = text.map(value => '' + value)
text = text.map(value => `${value}`)

if (format !== 'json') {
format = 'svg'
Expand Down
6 changes: 3 additions & 3 deletions lib/php-version.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ function minorVersion(version) {
return ''
}

return result[1] + '.' + (result[2] ? result[2] : '0')
return `${result[1]}.${result[2] ? result[2] : '0'}`
}

function versionReduction(versions, phpReleases) {
Expand All @@ -208,10 +208,10 @@ function versionReduction(versions, phpReleases) {
// no missed versions
if (first + versions.length - 1 === last) {
if (last === phpReleases.length - 1) {
return '>= ' + (versions[0][2] === '0' ? versions[0][0] : versions[0]) // 7.0 -> 7
return `>= ${versions[0][2] === '0' ? versions[0][0] : versions[0]}` // 7.0 -> 7
}

return versions[0] + ' - ' + versions[versions.length - 1]
return `${versions[0]} - ${versions[versions.length - 1]}`
}

return versions.join(', ')
Expand Down
2 changes: 1 addition & 1 deletion lib/request-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function handleRequest(makeBadge, handlerOptions) {
ask.res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
ask.res.setHeader('Expires', reqTime.toGMTString())
} else {
ask.res.setHeader('Cache-Control', 'max-age=' + maxAge)
ask.res.setHeader('Cache-Control', `max-age=${maxAge}`)
ask.res.setHeader(
'Expires',
new Date(+reqTime + maxAge * 1000).toGMTString()
Expand Down
2 changes: 1 addition & 1 deletion lib/result-sender.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function sendSVG(res, askres, end) {
}

function sendOther(format, res, askres, end) {
askres.setHeader('Content-Type', 'image/' + format)
askres.setHeader('Content-Type', `image/${format}`)
svg2img(res, format)
.then(data => {
end(null, { template: streamFromString(data) })
Expand Down
2 changes: 1 addition & 1 deletion lib/service-test-runner/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class Runner {

// Throw at the end, to provide a better error message.
if (missingServices.length > 0) {
throw Error('Unknown services: ' + missingServices.join(', '))
throw Error(`Unknown services: ${missingServices.join(', ')}`)
}
}

Expand Down
34 changes: 14 additions & 20 deletions lib/suggest.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function suggest(allowedOrigin, githubApiProvider, data, end, ask) {
try {
url = nodeUrl.parse(data.url)
} catch (e) {
end({ err: '' + e })
end({ err: `${e}` })
return
}
findSuggestions(githubApiProvider, url, end)
Expand Down Expand Up @@ -76,43 +76,37 @@ function twitterPage(url) {
const path = url.path
return Promise.resolve({
name: 'Twitter',
link:
'https://twitter.com/intent/tweet?text=Wow:&url=' +
encodeURIComponent(url.href),
badge:
'https://img.shields.io/twitter/url/' +
schema +
'/' +
host +
path +
'.svg?style=social',
link: `https://twitter.com/intent/tweet?text=Wow:&url=${encodeURIComponent(
url.href
)}`,
badge: `https://img.shields.io/twitter/url/${schema}/${host}${path}.svg?style=social`,
})
}

function githubIssues(user, repo) {
const userRepo = user + '/' + repo
const userRepo = `${user}/${repo}`
return Promise.resolve({
name: 'GitHub issues',
link: 'https://github.com/' + userRepo + '/issues',
badge: 'https://img.shields.io/github/issues/' + userRepo + '.svg',
link: `https://github.com/${userRepo}/issues`,
badge: `https://img.shields.io/github/issues/${userRepo}.svg`,
})
}

function githubForks(user, repo) {
const userRepo = user + '/' + repo
const userRepo = `${user}/${repo}`
return Promise.resolve({
name: 'GitHub forks',
link: 'https://github.com/' + userRepo + '/network',
badge: 'https://img.shields.io/github/forks/' + userRepo + '.svg',
link: `https://github.com/${userRepo}/network`,
badge: `https://img.shields.io/github/forks/${userRepo}.svg`,
})
}

function githubStars(user, repo) {
const userRepo = user + '/' + repo
const userRepo = `${user}/${repo}`
return Promise.resolve({
name: 'GitHub stars',
link: 'https://github.com/' + userRepo + '/stargazers',
badge: 'https://img.shields.io/github/stars/' + userRepo + '.svg',
link: `https://github.com/${userRepo}/stargazers`,
badge: `https://img.shields.io/github/stars/${userRepo}.svg`,
})
}

Expand Down
8 changes: 4 additions & 4 deletions lib/text-formatters.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ function metric(n) {
if (n >= limit) {
n = Math.round(n / limit)
if (n < 1000) {
return '' + n + metricPrefix[i]
return `${n}${metricPrefix[i]}`
} else {
return '1' + metricPrefix[i + 1]
return `1${metricPrefix[i + 1]}`
}
}
}
return '' + n
return `${n}`
}

// Remove the starting v in a string.
Expand All @@ -79,7 +79,7 @@ function omitv(version) {
// - it is a date (yyyy-mm-dd)
const ignoredVersionPatterns = /^[^0-9]|[0-9]{4}-[0-9]{2}-[0-9]{2}/
function addv(version) {
version = '' + version
version = `${version}`
if (version.startsWith('v') || ignoredVersionPatterns.test(version)) {
return version
} else {
Expand Down
4 changes: 2 additions & 2 deletions lib/version.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ function latest(versions, { pre = false } = {}) {
// coerce to string then lowercase otherwise alpha > RC
version = versions.sort((a, b) =>
semver.rcompare(
('' + a).toLowerCase(),
('' + b).toLowerCase(),
`${a}`.toLowerCase(),
`${b}`.toLowerCase(),
/* loose */ true
)
)[0]
Expand Down
6 changes: 3 additions & 3 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ camp.route(

// Cache management - the badge is constant.
const cacheDuration = (3600 * 24 * 1) | 0 // 1 day.
ask.res.setHeader('Cache-Control', 'max-age=' + cacheDuration)
ask.res.setHeader('Cache-Control', `max-age=${cacheDuration}`)
if (+new Date(ask.req.headers['if-modified-since']) >= +serverStartTime) {
ask.res.statusCode = 304
ask.res.end() // not modified.
Expand Down Expand Up @@ -286,7 +286,7 @@ camp.route(
let bitFlip = false
camp.route(/^\/flip\.svg$/, (data, match, end, ask) => {
const cacheSecs = 60
ask.res.setHeader('Cache-Control', 'max-age=' + cacheSecs)
ask.res.setHeader('Cache-Control', `max-age=${cacheSecs}`)
const reqTime = new Date()
const date = new Date(+reqTime + cacheSecs * 1000).toGMTString()
ask.res.setHeader('Expires', date)
Expand All @@ -306,7 +306,7 @@ camp.route(/^\/([^/]+)\/(.+).png$/, (data, match, end, ask) => {

// Cache management - the badge is constant.
const cacheDuration = (3600 * 24 * 1) | 0 // 1 day.
ask.res.setHeader('Cache-Control', 'max-age=' + cacheDuration)
ask.res.setHeader('Cache-Control', `max-age=${cacheDuration}`)
if (+new Date(ask.req.headers['if-modified-since']) >= +serverStartTime) {
ask.res.statusCode = 304
ask.res.end() // not modified.
Expand Down
Loading