Skip to content

Commit

Permalink
refactor: format with prettier
Browse files Browse the repository at this point in the history
working towards conveyal#318
  • Loading branch information
miles-grant-ibigroup committed Jul 6, 2021
1 parent 5abb8a4 commit 03be4e8
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 80 deletions.
5 changes: 4 additions & 1 deletion lib/babel-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const reactRequire = require('babel-plugin-react-require').default
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')

const browsers = require('./constants').BROWSER_SUPPORT

module.exports = function (env, instrument) {
Expand All @@ -20,7 +21,9 @@ module.exports = function (env, instrument) {
reactRequire
]

if (instrument) { plugins.push(istanbul) }
if (instrument) {
plugins.push(istanbul)
}

return {
plugins,
Expand Down
10 changes: 4 additions & 6 deletions lib/fs-promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@ const fs = require('fs')
exports.readFile = function (file, options) {
options = options || { encoding: 'utf-8' }
return new Promise((resolve, reject) =>
fs.readFile(
file,
options,
(err, data) => (err ? reject(err) : resolve(data))
fs.readFile(file, options, (err, data) =>
err ? reject(err) : resolve(data)
)
)
}

exports.stat = function (file) {
return new Promise(resolve =>
return new Promise((resolve) =>
fs.stat(file, (err, stats) => resolve({ err, stats }))
)
}

exports.writeFile = function (file, data) {
return new Promise((resolve, reject) => {
fs.writeFile(file, data, err => (err ? reject(err) : resolve()))
fs.writeFile(file, data, (err) => (err ? reject(err) : resolve()))
})
}
2 changes: 1 addition & 1 deletion lib/jest-preprocessor.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {transform} = require('@babel/core')
const { transform } = require('@babel/core')

const babelCfg = require('./babel-config')
const transformCfg = babelCfg('test')
Expand Down
24 changes: 10 additions & 14 deletions lib/jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,7 @@ module.exports.generateTestConfig = (patterns, options) => {
collectCoverage: options.coverage,
collectCoverageFrom: ['lib/**/*.js'],
coverageDirectory: 'coverage',
moduleFileExtensions: [
'js',
'jsx',
'json',
'png',
'yml'
],
moduleFileExtensions: ['js', 'jsx', 'json', 'png', 'yml'],
notify: true,
testPathIgnorePatterns: [
'<rootDir>/node_modules/',
Expand All @@ -24,13 +18,14 @@ module.exports.generateTestConfig = (patterns, options) => {
transform: {
'\\.yml$': 'jest-yaml-transform',
'^.+\\.jsx?$': path.resolve(__dirname, 'jest-preprocessor.js'),
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub'
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub'
}
}

// add local package.json-level config options
if (pkg.jest != null) {
Object.keys(pkg.jest).forEach(key => {
Object.keys(pkg.jest).forEach((key) => {
jestConfig[key] = pkg.jest[key]
})
}
Expand All @@ -47,18 +42,19 @@ module.exports.generateTestConfig = (patterns, options) => {

const stringArrayOverrides = ['setupFiles', 'testPathIgnorePatterns']

stringArrayOverrides.forEach(option => {
stringArrayOverrides.forEach((option) => {
if (options[option]) {
jestConfig[option] = options[option].split(' ')
}
})

// override config with the values found in a specified file
if (options.customConfigFile) {
const customConfig = require(
path.resolve(process.cwd(), options.customConfigFile)
)
Object.keys(customConfig).forEach(key => {
const customConfig = require(path.resolve(
process.cwd(),
options.customConfigFile
))
Object.keys(customConfig).forEach((key) => {
jestConfig[key] = customConfig[key]
})
}
Expand Down
15 changes: 8 additions & 7 deletions lib/lint-messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@ const IS_IMPORT = /import.*from '[^ ]+\/messages'/
// You cannot have repeated capturing groups in a regex, http://stackoverflow.com/questions/3537878
// The default import name will be either group 1 or 3 depending on whether it comes before or after
// the named imports.
const IMPORT = /import ([a-zA-Z0-9_$]+)?,? ?(\{ ?(?:[a-zA-Z0-9_$]+(?: as [a-zA-Z0-9_$]+)?,? ?)* ?\})?,? ?([a-zA-Z0-9_$]+)? from '[^ ]+\/messages'/
const IMPORT =
/import ([a-zA-Z0-9_$]+)?,? ?(\{ ?(?:[a-zA-Z0-9_$]+(?: as [a-zA-Z0-9_$]+)?,? ?)* ?\})?,? ?([a-zA-Z0-9_$]+)? from '[^ ]+\/messages'/
// global regex, exec multiple times on same string to get all named imports. Has the source on the
// first group and the name (if applicable) on the second.
const NAMED_IMPORTS = /([a-zA-Z0-9_$]+)(?: as ([a-zA-Z0-9_$]+))?/g

/**
* parse a line to determine if it is an import of messages
*/
function parseImportLine (line) {
function parseImportLine(line) {
if (IS_IMPORT.test(line)) {
// could be either depending on whether default import was before or after named imports
const [, default0, named, default1] = IMPORT.exec(line)
Expand All @@ -41,7 +42,7 @@ function parseImportLine (line) {
}

/** Lint a file against messages. Exported for testing */
function lintFileContents (messages, js) {
function lintFileContents(messages, js) {
// what was messages imported as
let importedAtRootAs = false
let importedMembersAs
Expand All @@ -67,7 +68,7 @@ function lintFileContents (messages, js) {
)
namedMatcher = new RegExp(
`[^a-zA-Z0-9_$](${importedMembersAs
.map(a => a[1])
.map((a) => a[1])
.join('|')})\\.([^ ,\\(\\)\\[}]+)`,
'g'
)
Expand Down Expand Up @@ -114,10 +115,10 @@ module.exports = {
lint: function (files, messages) {
return util
.cliFileEntriesToArray(files)
.then(allFiles =>
.then((allFiles) =>
Promise.all(
allFiles.map(filename =>
readFile(filename).then(contents =>
allFiles.map((filename) =>
readFile(filename).then((contents) =>
Promise.resolve(
lintFileContents(messages, contents).map(([message, line]) => [
message,
Expand Down
8 changes: 4 additions & 4 deletions lib/load-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const path = require('path')

const YAML = require('yamljs')

module.exports = function load (cwd, config, environment) {
module.exports = function load(cwd, config, environment) {
const configDirectory = path.resolve(cwd, config || 'configurations/default')
const defaultDirectory = path.resolve(cwd, 'configurations/default')
const env = loadYaml('env')
Expand All @@ -27,7 +27,7 @@ module.exports = function load (cwd, config, environment) {
* Look first in the configDirectory and then fallback to the defaultDirectory.
* If the file is still not found, return null.
*/
function findFile (filename) {
function findFile(filename) {
const file = configDirectory + '/' + filename
if (fs.existsSync(file)) return file
const defaultFile = defaultDirectory + '/' + filename
Expand All @@ -38,7 +38,7 @@ module.exports = function load (cwd, config, environment) {
/**
* Return the JSON of a YAML file if it found, otherwise return an empty object.
*/
function loadYaml (filename) {
function loadYaml(filename) {
const file = findFile(`${filename}.yml`)
return file ? YAML.parse(fs.readFileSync(file, 'utf8')) : {}
}
Expand All @@ -47,7 +47,7 @@ module.exports = function load (cwd, config, environment) {
/**
* If an environments key exists within a config object, use that data instead.
*/
function overrideWithEnvironment (object, environment) {
function overrideWithEnvironment(object, environment) {
if (object.environments && object.environments[environment]) {
const newObject = Object.assign(
{},
Expand Down
44 changes: 21 additions & 23 deletions lib/logger.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
const fetch = require('isomorphic-fetch')
const nodeEmoji = require('node-emoji')

const logToConsole = text => Promise.resolve(console.log(emojify(text)))
const logToErrorConsole = text => Promise.resolve(console.error(emojify(text)))
const logToConsole = (text) => Promise.resolve(console.log(emojify(text)))
const logToErrorConsole = (text) =>
Promise.resolve(console.error(emojify(text)))

module.exports.log = logToConsole
module.exports.error = logToErrorConsole

module.exports.logToSlack = ({ channel, webhook }) => {
module.exports.log = text => {
module.exports.log = (text) => {
logToConsole(text)
return notifySlack({ channel, text, webhook })
}

module.exports.error = text => {
module.exports.error = (text) => {
logToErrorConsole(text)
return notifySlack({ channel, text, webhook })
}
Expand All @@ -22,15 +23,15 @@ module.exports.logToSlack = ({ channel, webhook }) => {
/**
* Emojify text outside of html
*/
function emojify (text) {
function emojify(text) {
const strippedLinks = text.replace(/<[^|>]+\|([^>]+)>/g, '$1')
return nodeEmoji.emojify(strippedLinks)
}

/**
* Send a message to slack by making a request to a webhook.
*/
function notifySlack ({ channel, text, webhook }) {
function notifySlack({ channel, text, webhook }) {
return fetch(webhook, {
body: JSON.stringify({
channel,
Expand All @@ -41,8 +42,8 @@ function notifySlack ({ channel, text, webhook }) {
},
method: 'POST'
})
.then(response => response.text())
.catch(err => {
.then((response) => response.text())
.catch((err) => {
logToErrorConsole('Error posting to Slack webhook')
logToErrorConsole(err)
return err
Expand All @@ -60,25 +61,22 @@ function notifySlack ({ channel, text, webhook }) {
* @param {String} title Title of the card
* @param {String} webhook Webhook url
*/
module.exports.notifyMsTeams = function notifyMSTeams ({
module.exports.notifyMsTeams = function notifyMSTeams({
potentialAction,
text,
themeColor = '0072C6',
title,
webhook
}) {
return fetch(
webhook,
{
method: 'POST',
body: JSON.stringify({
'@context': 'https://schema.org/extensions',
'@type': 'MessageCard',
themeColor,
title,
text,
potentialAction
})
}
)
return fetch(webhook, {
method: 'POST',
body: JSON.stringify({
'@context': 'https://schema.org/extensions',
'@type': 'MessageCard',
themeColor,
title,
text,
potentialAction
})
})
}
6 changes: 3 additions & 3 deletions lib/prepublish.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ module.exports = function ({ entries, env, outdir }) {
/**
* Transform all of the files in a directory recursively.
*/
function transformDir ({ config, entry, outdir }) {
return glob.sync(`${entry[0]}/**/*.js`).map(filename =>
function transformDir({ config, entry, outdir }) {
return glob.sync(`${entry[0]}/**/*.js`).map((filename) =>
transformFile({
config,
entry: [filename, filename.replace(entry[0], entry[1] || outdir)]
Expand All @@ -38,7 +38,7 @@ function transformDir ({ config, entry, outdir }) {
/**
* Transform a file with babel and also write the sourcemap for the file.
*/
function transformFile ({ config, entry, outdir }) {
function transformFile({ config, entry, outdir }) {
const filename = entry[0]
const filepath = entry[1] || `${outdir}/${filename}`
const results = babel.transform(
Expand Down
16 changes: 8 additions & 8 deletions lib/push-to-s3.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ const uuid = require('uuid')

const logger = require('./logger')

module.exports = ({ s3bucket, cloudfront }) => ({ body, outfile }) =>
upload({ body, cloudfront, outfile, s3bucket })
module.exports =
({ s3bucket, cloudfront }) =>
({ body, outfile }) =>
upload({ body, cloudfront, outfile, s3bucket })

/**
* Upload the contents of a file to s3.
* Also, invalidate the respective cloudfront path if instructed to do so.
*/
function upload ({ body, s3bucket, cloudfront, outfile }) {
function upload({ body, s3bucket, cloudfront, outfile }) {
const bucketUrl = `https://s3.amazonaws.com/${s3bucket}`
return new Promise((resolve, reject) => {
const s3object = new AWS.S3({
Expand All @@ -30,9 +32,7 @@ function upload ({ body, s3bucket, cloudfront, outfile }) {
if (err) {
return reject(
new Error(
`s3 upload to ${bucketLink} rejected with ${err.code} ${
err.message
}`
`s3 upload to ${bucketLink} rejected with ${err.code} ${err.message}`
)
)
}
Expand Down Expand Up @@ -70,7 +70,7 @@ function upload ({ body, s3bucket, cloudfront, outfile }) {
/**
* Helper function to log a successful upload to s3.
*/
function done () {
function done() {
logger
.log(`:checkered_flag: *uploaded:* ${bucketLink} (${bytes})`)
.then(resolve)
Expand All @@ -84,7 +84,7 @@ const DISPLAY_DECIMALS = 2
/**
* Pretty print the size of the number of bytes.
*/
function bytesToSize (bytes) {
function bytesToSize(bytes) {
const sizes = ['bytes', 'kb', 'mb', 'gb', 'tb']
if (bytes === 0) return '0 byte'
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(BYTES)))
Expand Down
Loading

0 comments on commit 03be4e8

Please sign in to comment.