From 7a9e93ef45b835784425cc365ffba143bc3e4dd3 Mon Sep 17 00:00:00 2001 From: Christian Maniewski Date: Fri, 27 Sep 2019 21:52:47 +0200 Subject: [PATCH] Apply prettier fixes --- scripts/colony-stats.js | 97 ++++++++++-------- scripts/countdown.js | 140 +++++++++++++------------- scripts/daily-standup.js | 16 +-- scripts/deployments.js | 189 ++++++++++++++++++++--------------- scripts/figma-preview.js | 34 ++++--- scripts/github-issue-link.js | 14 +-- scripts/utils/brain.js | 54 +++++----- scripts/utils/channels.js | 6 +- scripts/utils/dates.js | 80 ++++++++------- 9 files changed, 335 insertions(+), 295 deletions(-) diff --git a/scripts/colony-stats.js b/scripts/colony-stats.js index 7a9b725..92053cf 100644 --- a/scripts/colony-stats.js +++ b/scripts/colony-stats.js @@ -9,12 +9,16 @@ const { providers, Wallet } = require('ethers') const { default: EthersAdapter } = require('@colony/colony-js-adapter-ethers') -const { default: NetworkLoader } = require('@colony/colony-contract-loader-network') +const { + default: NetworkLoader +} = require('@colony/colony-contract-loader-network') const { default: ColonyNetworkClient } = require('@colony/colony-js-client') -module.exports = async (robot) => { +module.exports = async robot => { const network = 'rinkeby' - const privateKey = process.env.HUBOT_ETHEREUM_PRIVATE_KEY || '0x0123456789012345678901234567890123456789012345678901234567890123' + const privateKey = + process.env.HUBOT_ETHEREUM_PRIVATE_KEY || + '0x0123456789012345678901234567890123456789012345678901234567890123' const loader = new NetworkLoader({ network }) const provider = new providers.EtherscanProvider(network) @@ -23,7 +27,7 @@ module.exports = async (robot) => { const adapter = new EthersAdapter({ loader, provider, - wallet, + wallet }) const networkClient = new ColonyNetworkClient({ adapter }) @@ -32,72 +36,79 @@ module.exports = async (robot) => { const metaColonyClient = await networkClient.getMetaColonyClient() robot.hear(/!colony ([0-9]*)$/i, async msg => { - msg.send('Gathering data...'); - const { address } = await networkClient.getColony.call({ id: parseInt(msg.match[1], 10) }) + msg.send('Gathering data...') + const { address } = await networkClient.getColony.call({ + id: parseInt(msg.match[1], 10) + }) if (!address) { - return msg.send("No such colony"); + return msg.send('No such colony') } const colonyClient = await networkClient.getColonyClientByAddress(address) - const { count } = await colonyClient.getTaskCount.call(); - let res = await colonyClient.getToken.call(); - const tokenAddress = res.address; - let tokenName; - let tokenSymbol; + const { count } = await colonyClient.getTaskCount.call() + let res = await colonyClient.getToken.call() + const tokenAddress = res.address + let tokenName + let tokenSymbol try { - res = await colonyClient.token.getTokenInfo.call(); - tokenName = res.name; - tokenSymbol = res.symbol; - } catch (err){ + res = await colonyClient.token.getTokenInfo.call() + tokenName = res.name + tokenSymbol = res.symbol + } catch (err) { // No such properties on the token - possible if not ERC20 compliant, as BYOT allows } - msg.send(`Address: ${address} \nTask count: ${count}\nToken Address: ${tokenAddress}\nToken Name: ${tokenName} (${tokenSymbol})`) + msg.send( + `Address: ${address} \nTask count: ${count}\nToken Address: ${tokenAddress}\nToken Name: ${tokenName} (${tokenSymbol})` + ) }) - robot.hear(/!colony ([0-9]*) task ([0-9]*)$/i, async msg => { msg.send('Gathering data...') - const { address } = await networkClient.getColony.call({ id: parseInt(msg.match[1], 10) }) - const taskId = parseInt(msg.match[2], 10); + const { address } = await networkClient.getColony.call({ + id: parseInt(msg.match[1], 10) + }) + const taskId = parseInt(msg.match[2], 10) if (!address) { - return msg.send("No such colony"); + return msg.send('No such colony') } - const colonyClient = await networkClient.getColonyClientByAddress(address); - const task = await colonyClient.getTask.call({taskId}); - let output = ""; - if (task.specificationHash){ - output += "Specification: https://gateway.ipfs.io/ipfs/QmTDMoVqvyBkNMRhzvukTDznntByUNDwyNdSfV8dZ3VKRC/\n" + const colonyClient = await networkClient.getColonyClientByAddress(address) + const task = await colonyClient.getTask.call({ taskId }) + let output = '' + if (task.specificationHash) { + output += + 'Specification: https://gateway.ipfs.io/ipfs/QmTDMoVqvyBkNMRhzvukTDznntByUNDwyNdSfV8dZ3VKRC/\n' } else { - output += "Specification: None\n" + output += 'Specification: None\n' } - if (task.deliverableHash){ - output += "Deliverable: https://gateway.ipfs.io/ipfs/QmTDMoVqvyBkNMRhzvukTDznntByUNDwyNdSfV8dZ3VKRC/\n" + if (task.deliverableHash) { + output += + 'Deliverable: https://gateway.ipfs.io/ipfs/QmTDMoVqvyBkNMRhzvukTDznntByUNDwyNdSfV8dZ3VKRC/\n' } else { - output += "Deliverable: None\n" + output += 'Deliverable: None\n' } - output += `Finalized: ${task.finalized ? "Yes" : "No"}\n` - output += `Cancelled: ${task.cancelled ? "Yes" : "No"}` + output += `Finalized: ${task.finalized ? 'Yes' : 'No'}\n` + output += `Cancelled: ${task.cancelled ? 'Yes' : 'No'}` output += `\nDue date: ` - if (task.dueDate){ + if (task.dueDate) { output += ` ${new Date(task.dueDate * 1000).toISOString()}` } else { output += ` none` } - output += `\nDeliverable date: `; - if (task.deliverableDate){ + output += `\nDeliverable date: ` + if (task.deliverableDate) { output += `${new Date(task.deliverableDate * 1000).toISOString()}` } else { - output += ` none`; + output += ` none` } - let res = await colonyClient.getTaskRole.call({taskId, role: 'MANAGER'} ) - output += `\nManager: ${ res.address }` - res = await colonyClient.getTaskRole.call({taskId, role: 'EVALUATOR'} ) - output += `\nEvaluator: ${ res.address }` - res = await colonyClient.getTaskRole.call({taskId, role: 'WORKER'} ) - output += `\nWorker: ${ res.address }` + let res = await colonyClient.getTaskRole.call({ taskId, role: 'MANAGER' }) + output += `\nManager: ${res.address}` + res = await colonyClient.getTaskRole.call({ taskId, role: 'EVALUATOR' }) + output += `\nEvaluator: ${res.address}` + res = await colonyClient.getTaskRole.call({ taskId, role: 'WORKER' }) + output += `\nWorker: ${res.address}` - msg.send(output); + msg.send(output) }) } diff --git a/scripts/countdown.js b/scripts/countdown.js index 3a89f4e..462d5a3 100644 --- a/scripts/countdown.js +++ b/scripts/countdown.js @@ -17,137 +17,131 @@ // Author: // JamesLefrere -const CronJob = require('cron').CronJob; +const CronJob = require('cron').CronJob -const getBrain = require('./utils/brain'); +const getBrain = require('./utils/brain') -const { - getOffsetDate, - parseNaturalDate, -} = require('./utils/dates'); +const { getOffsetDate, parseNaturalDate } = require('./utils/dates') -const { isPrivateSlackMessage } = require('./utils/channels'); +const { isPrivateSlackMessage } = require('./utils/channels') -const BRAIN_PREFIX = 'countdown'; -const COUNTDOWNS = 'countdowns'; +const BRAIN_PREFIX = 'countdown' +const COUNTDOWNS = 'countdowns' -const { - addToMap, - getFromMap, - getMap, - removeFromMap, -} = getBrain(BRAIN_PREFIX); +const { addToMap, getFromMap, getMap, removeFromMap } = getBrain(BRAIN_PREFIX) const getSass = hours => { - if (hours > 24 * 7 * 4) return 'An ocean of time.'; - if (hours > 24 * 7 * 3.5) return 'Ages, mate.'; - if (hours > 24 * 7 * 3) return `It's getting closer, but it'll be fine.`; - if (hours > 24 * 7 * 2.5) return 'Watch out for this one.'; - if (hours > 24 * 7 * 2) return 'Did you try working faster?'; - if (hours > 24 * 7 * 1.5) return `That's concerning.`; - if (hours > 24 * 7) return `That's quite soon if you think about it.`; - if (hours > 24 * 6) return `Well that doesn't sound right...`; - if (hours > 24 * 5) return 'A week?! A mere working week?!'; - if (hours > 24 * 4) return 'Shit, we can do it!'; - if (hours > 24 * 3) return 'A'.repeat(20); - if (hours > 24 * 2) return `I'll give you 1 ETH if you finish it today.`; - if (hours > 24) return `*${'A'.repeat(200)}*`; - return '*PANIC MODE ENGAGE!!!* gogogogogogogogogogogogogo54321111111glhf'; -}; - -const getKey = title => title.replace(/\s/g, ''); + if (hours > 24 * 7 * 4) return 'An ocean of time.' + if (hours > 24 * 7 * 3.5) return 'Ages, mate.' + if (hours > 24 * 7 * 3) return `It's getting closer, but it'll be fine.` + if (hours > 24 * 7 * 2.5) return 'Watch out for this one.' + if (hours > 24 * 7 * 2) return 'Did you try working faster?' + if (hours > 24 * 7 * 1.5) return `That's concerning.` + if (hours > 24 * 7) return `That's quite soon if you think about it.` + if (hours > 24 * 6) return `Well that doesn't sound right...` + if (hours > 24 * 5) return 'A week?! A mere working week?!' + if (hours > 24 * 4) return 'Shit, we can do it!' + if (hours > 24 * 3) return 'A'.repeat(20) + if (hours > 24 * 2) return `I'll give you 1 ETH if you finish it today.` + if (hours > 24) return `*${'A'.repeat(200)}*` + return '*PANIC MODE ENGAGE!!!* gogogogogogogogogogogogogo54321111111glhf' +} + +const getKey = title => title.replace(/\s/g, '') const processCountdowns = robot => { - const { brain } = robot; - const currentDate = getOffsetDate(-11); + const { brain } = robot + const currentDate = getOffsetDate(-11) Object.entries(getMap(COUNTDOWNS, brain)).forEach( ([key, { title, dueDate, room }]) => { - const diff = new Date(dueDate).getTime() - new Date(currentDate).getTime(); + const diff = new Date(dueDate).getTime() - new Date(currentDate).getTime() if (diff < 0) { - robot.messageRoom(room, `${title}: due date elapsed!`); - return removeFromMap(COUNTDOWNS, key, brain); + robot.messageRoom(room, `${title}: due date elapsed!`) + return removeFromMap(COUNTDOWNS, key, brain) } - const hours = (diff / (1000 * 60 * 60)).toFixed(2); + const hours = (diff / (1000 * 60 * 60)).toFixed(2) robot.messageRoom( room, `${title}: ${hours} hours remaining. ${getSass(hours)}` - ); - }); -}; + ) + } + ) +} const setupCronJob = robot => { const job = new CronJob({ // Every weekday 23:45h cronTime: '00 45 23 * * *', onTick: () => { - processCountdowns(robot); + processCountdowns(robot) }, start: false, // Last time zone of the day (UTC-11) timeZone: 'Pacific/Niue' - }); - job.start(); -}; + }) + job.start() +} module.exports = robot => { - const { brain } = robot; - setupCronJob(robot); + const { brain } = robot + setupCronJob(robot) robot.hear(/^countdown add '(.+)' (.+)$/, res => { - const { message: { user, room }, match } = res; + const { + message: { user, room }, + match + } = res if (isPrivateSlackMessage(res)) { - return res.send('Countdowns can only be added in a channel.'); + return res.send('Countdowns can only be added in a channel.') } if (user.slack.tz_offset == null) { return res.send('Please set your time zone in slack first') } - const title = match[1]; - const dueDate = parseNaturalDate(match[2], user); + const title = match[1] + const dueDate = parseNaturalDate(match[2], user) - const key = getKey(title); - const existing = getFromMap(COUNTDOWNS, key, brain); + const key = getKey(title) + const existing = getFromMap(COUNTDOWNS, key, brain) if (existing) { - return res.send('Oops, a countdown with that title already exists'); + return res.send('Oops, a countdown with that title already exists') } - addToMap( - COUNTDOWNS, - key, - { title, dueDate, room, userId: user.id }, - brain - ); + addToMap(COUNTDOWNS, key, { title, dueDate, room, userId: user.id }, brain) - return res.send('The countdown begins!'); - }); + return res.send('The countdown begins!') + }) robot.hear(/^countdown status$/, () => { - processCountdowns(robot); - }); + processCountdowns(robot) + }) robot.hear(/^countdown remove '(.*)'$/, res => { - const { message: { user }, match } = res; + const { + message: { user }, + match + } = res - const key = getKey(match[1]); - const existing = getFromMap(COUNTDOWNS, key, brain); + const key = getKey(match[1]) + const existing = getFromMap(COUNTDOWNS, key, brain) if (!existing) { - return res.send(`That countdown doesn't exist`); + return res.send(`That countdown doesn't exist`) } if (user.id !== existing.userId) { - return res.send(`Only user ID ${userId} can remove that countdown`); + return res.send(`Only user ID ${userId} can remove that countdown`) } - removeFromMap(COUNTDOWNS, key, brain); + removeFromMap(COUNTDOWNS, key, brain) - return res.send('Countdown removed'); - }); -}; + return res.send('Countdown removed') + }) +} diff --git a/scripts/daily-standup.js b/scripts/daily-standup.js index fd4873b..9782e04 100644 --- a/scripts/daily-standup.js +++ b/scripts/daily-standup.js @@ -24,16 +24,16 @@ const { getCurrentTimeForUser, dateIsInRange, dateIsOlderThan, - parseNaturalDate, -} = require('./utils/dates'); + parseNaturalDate +} = require('./utils/dates') -const { isChannel, isPrivateSlackMessage } = require('./utils/channels'); +const { isChannel, isPrivateSlackMessage } = require('./utils/channels') -const getBrain = require('./utils/brain'); +const getBrain = require('./utils/brain') -const BRAIN_PREFIX = 'standup'; +const BRAIN_PREFIX = 'standup' // This is the daily-standup channel. This should be an env variable at some point -const HUBOT_STANDUP_CHANNEL = 'C0NFZA7T5'; +const HUBOT_STANDUP_CHANNEL = 'C0NFZA7T5' // #standup-testing channel // const HUBOT_STANDUP_CHANNEL = 'CBX6J6MAA' @@ -44,8 +44,8 @@ const { removeFromMap, removeMap, setMap, - updateMap, -} = getBrain(BRAIN_PREFIX); + updateMap +} = getBrain(BRAIN_PREFIX) /* User permission helpers */ const getUser = (userId, brain) => { diff --git a/scripts/deployments.js b/scripts/deployments.js index 4a0c955..52769dd 100644 --- a/scripts/deployments.js +++ b/scripts/deployments.js @@ -1,11 +1,11 @@ // Description: // Used to deploy specified builds to QA const exec = require('await-exec') -const { isChannel, isPrivateSlackMessage } = require('./utils/channels'); +const { isChannel, isPrivateSlackMessage } = require('./utils/channels') -const getBrain = require('./utils/brain'); +const getBrain = require('./utils/brain') -const BRAIN_PREFIX = 'deployment'; +const BRAIN_PREFIX = 'deployment' const { addToMap, @@ -14,43 +14,57 @@ const { removeFromMap, removeMap, setMap, - updateMap, -} = getBrain(BRAIN_PREFIX); + updateMap +} = getBrain(BRAIN_PREFIX) module.exports = async function(robot) { - // Activate credentials - await exec(`echo ${process.env.GCLOUD_SERVICE_KEY} | base64 --decode > /gcloud-service-key.json`); - await exec('gcloud auth activate-service-account --key-file /gcloud-service-key.json'); - await exec(`gcloud config set project ${process.env.GCLOUD_PROJECT_NAME}`); - await exec(`gcloud --quiet config set container/cluster ${process.env.GCLOUD_CLUSTER_NAME}`) - await exec(`gcloud config set compute/zone ${process.env.GCLOUD_CLOUDSDK_COMPUTE_ZONE}`); + await exec( + `echo ${ + process.env.GCLOUD_SERVICE_KEY + } | base64 --decode > /gcloud-service-key.json` + ) + await exec( + 'gcloud auth activate-service-account --key-file /gcloud-service-key.json' + ) + await exec(`gcloud config set project ${process.env.GCLOUD_PROJECT_NAME}`) + await exec( + `gcloud --quiet config set container/cluster ${ + process.env.GCLOUD_CLUSTER_NAME + }` + ) + await exec( + `gcloud config set compute/zone ${process.env.GCLOUD_CLOUDSDK_COMPUTE_ZONE}` + ) // It appears this is not needed to patch the containers as we want, so // let's not bother given that it errors // await exec(`gcloud --quiet container clusters get-credentials ${process.env.GCLOUD_CLUSTER_NAME}`); // Get the devops channel ID. The topic will be used to determine what colour is staging / production when asked to deploy to either. - let channels = await robot.adapter.client.web.conversations.list(); - let devopsChannel = channels.channels.filter(channel => channel.name === "devops")[0]; + let channels = await robot.adapter.client.web.conversations.list() + let devopsChannel = channels.channels.filter( + channel => channel.name === 'devops' + )[0] const devopsid = devopsChannel.id - async function transformUserToID(user) { - let users = await robot.adapter.client.web.users.list(); - users = users.members; - users = users.filter(u => (u.profile.display_name===user || u.name === user || u.id===user)); - if (users.length === 0){ - return [false, "Couldn't find such a user"]; - } else if (users.length > 1){ - return [false, "More than one user matched - be more specific"]; + let users = await robot.adapter.client.web.users.list() + users = users.members + users = users.filter( + u => u.profile.display_name === user || u.name === user || u.id === user + ) + if (users.length === 0) { + return [false, "Couldn't find such a user"] + } else if (users.length > 1) { + return [false, 'More than one user matched - be more specific'] } else { - return [true, users[0].id]; + return [true, users[0].id] } } const canDeploy = (userid, where, brain) => { - const users = getMap(`${where}Deployers`, brain); - return !!users[userid]; + const users = getMap(`${where}Deployers`, brain) + return !!users[userid] } const isAdmin = (user, brain) => { const admins = getMap('admins', brain) @@ -80,20 +94,19 @@ module.exports = async function(robot) { } const getUserList = (map, brain) => { - const userids = getMap(map, brain) - return Object.keys(userids) - .map(userid => `• <@${userid}>`) - .join('\n') + const userids = getMap(map, brain) + return Object.keys(userids) + .map(userid => `• <@${userid}>`) + .join('\n') } - robot.hear(/!deployment permissions/, async(res) => { + robot.hear(/!deployment permissions/, async res => { const { brain } = robot const { user } = res.message if (!isPrivateSlackMessage(res)) return if (!noAdmins(brain) && !isAdmin(user, brain)) return - const msg = `QA deployers:\n${getUserList( 'qaDeployers', brain @@ -104,71 +117,73 @@ module.exports = async function(robot) { 'productionDeployers', brain )}\nAdmins:\n${getUserList('admins', brain)}` - res.send(msg); - - }); + res.send(msg) + }) - robot.hear(/!deployment admin add (.+)/, async (res) => { + robot.hear(/!deployment admin add (.+)/, async res => { const { user } = res.message const { brain } = robot - const who = res.match[1].toLowerCase(); + const who = res.match[1].toLowerCase() if (!isPrivateSlackMessage(res)) return if (!noAdmins(brain) && !isAdmin(user, brain)) return const [userLookupSuccess, userIDToAdd] = await transformUserToID(who) - if (!userLookupSuccess){ - return msg.send(userIDToAdd); + if (!userLookupSuccess) { + return msg.send(userIDToAdd) } if (userIDToAdd && addUserWithRole(userIDToAdd, 'admin', brain)) { - return res.send( - `I added <@${userIDToAdd}> as a deployment admin.` - ) + return res.send(`I added <@${userIDToAdd}> as a deployment admin.`) } return res.send( 'Could not add user as a deployment admin. Maybe they do not exist or are already?' ) }) - robot.hear(/!deployment add (.+) (.+)/, async (res) => { + robot.hear(/!deployment add (.+) (.+)/, async res => { const { user } = res.message const { brain } = robot - const where = res.match[1].toLowerCase(); + const where = res.match[1].toLowerCase() const who = res.match[2] if (!isPrivateSlackMessage(res)) return if (!noAdmins(brain) && !isAdmin(user, brain)) return const [userLookupSuccess, userIDToAdd] = await transformUserToID(who) - if (!userLookupSuccess){ - return msg.send(userIDToAdd); + if (!userLookupSuccess) { + return msg.send(userIDToAdd) } - if (userIDToAdd && addUserWithRole(userIDToAdd, `${where}Deployer`, brain)) { - return res.send( - `I added <@${userIDToAdd}> as ${where} deployer.` - ) + if ( + userIDToAdd && + addUserWithRole(userIDToAdd, `${where}Deployer`, brain) + ) { + return res.send(`I added <@${userIDToAdd}> as ${where} deployer.`) } return res.send( `Could not add <@${userIDToAdd}> as a deployer. Maybe they do not exist or are already?` ) }) - - robot.hear(/!deployment remove (.+) (.+)/, async (res) => { + robot.hear(/!deployment remove (.+) (.+)/, async res => { const { user } = res.message const { brain } = robot - const where = res.match[1].toLowerCase(); - if (where !== "qa" && where !== "staging" && where !== "production") { return } - const who = res.match[2]; + const where = res.match[1].toLowerCase() + if (where !== 'qa' && where !== 'staging' && where !== 'production') { + return + } + const who = res.match[2] if (!isPrivateSlackMessage(res)) return if (!noAdmins(brain) && !isAdmin(user, brain)) return - const [userLookupSuccess, userToRemove] = await transformUserToID(res.match[2]) - if (!userLookupSuccess){ - return res.send(userToRemove); + const [userLookupSuccess, userToRemove] = await transformUserToID( + res.match[2] + ) + if (!userLookupSuccess) { + return res.send(userToRemove) } - if (userToRemove && removeUserWithRole(userToRemove, `${where}Deployer`, brain)) { - return res.send( - `I removed <@${userToRemove}> as ${where} deployer.` - ) + if ( + userToRemove && + removeUserWithRole(userToRemove, `${where}Deployer`, brain) + ) { + return res.send(`I removed <@${userToRemove}> as ${where} deployer.`) } return res.send( `Could not remove <@${userToRemove}> as ${where} deployer. Maybe they do not have the role?` @@ -177,41 +192,59 @@ module.exports = async function(robot) { const deployRegex = /!deploy (qa|staging|production) ([0-9a-fA-f]*)/ robot.hear(deployRegex, async msg => { - const { brain } = robot; + const { brain } = robot - const matches = deployRegex.exec(msg.message.text); - if (matches[1] === 'qa'){ + const matches = deployRegex.exec(msg.message.text) + if (matches[1] === 'qa') { // Check they have permission if (!canDeploy(msg.message.user.id, 'qa', brain)) { - return msg.send("You do not have that permission, as far as I can see? Take it up with the admins..."); + return msg.send( + 'You do not have that permission, as far as I can see? Take it up with the admins...' + ) } - await exec('kubectl patch deployment dapp-red -p \'{"spec":{"template":{"spec":{"containers":[{"name":"dapp","image":"eu.gcr.io/fluent-aileron-128715/dapp-goerli:' + matches[2] + '"}]}}}}\'') + await exec( + 'kubectl patch deployment dapp-red -p \'{"spec":{"template":{"spec":{"containers":[{"name":"dapp","image":"eu.gcr.io/fluent-aileron-128715/dapp-goerli:' + + matches[2] + + '"}]}}}}\'' + ) } else if (matches[1] === 'staging' || matches[1] === 'production') { // Get colours - const response = await robot.adapter.client.web.channels.info(devopsid); - devopsChannel = response.channel; - const devopsTopic = devopsChannel.topic.value; - let colour; + const response = await robot.adapter.client.web.channels.info(devopsid) + devopsChannel = response.channel + const devopsTopic = devopsChannel.topic.value + let colour - if (matches[1] === 'staging'){ + if (matches[1] === 'staging') { // check they have staging permission if (!canDeploy(msg.message.user.id, 'staging', brain)) { - return msg.send("You do not have that permission, as far as I can see? Take it up with the admins..."); + return msg.send( + 'You do not have that permission, as far as I can see? Take it up with the admins...' + ) } const stagingColourRegex = /Currently staging: ([a-zA-Z]*)/ - const stagingColourMatches = stagingColourRegex.exec(devopsTopic); - colour = stagingColourMatches[1].toLowerCase(); + const stagingColourMatches = stagingColourRegex.exec(devopsTopic) + colour = stagingColourMatches[1].toLowerCase() } else { // check they have production permission if (!canDeploy(msg.message.user.id, 'production', brain)) { - return msg.send("You do not have that permission, as far as I can see? Take it up with the admins..."); + return msg.send( + 'You do not have that permission, as far as I can see? Take it up with the admins...' + ) } const productionColourRegex = /Currently production\/live: ([a-zA-Z]*)/ - const productionColourMatches = productionColourRegex.exec(devopsTopic); - colour = productionColourMatches[1].toLowerCase(); + const productionColourMatches = productionColourRegex.exec(devopsTopic) + colour = productionColourMatches[1].toLowerCase() } - await exec('kubectl patch deployment dapp-' + colour +' -p \'{"spec":{"template":{"spec":{"containers":[{"name":"dapp","image":"eu.gcr.io/fluent-aileron-128715/dapp-mainnet:' + matches[2] + '"}]}}}}\'' ) + await exec( + 'kubectl patch deployment dapp-' + + colour + + ' -p \'{"spec":{"template":{"spec":{"containers":[{"name":"dapp","image":"eu.gcr.io/fluent-aileron-128715/dapp-mainnet:' + + matches[2] + + '"}]}}}}\'' + ) } - msg.send('Container patched. Could take up to two minutes to start responding.') + msg.send( + 'Container patched. Could take up to two minutes to start responding.' + ) }) } diff --git a/scripts/figma-preview.js b/scripts/figma-preview.js index 98d6a53..85a3260 100644 --- a/scripts/figma-preview.js +++ b/scripts/figma-preview.js @@ -11,13 +11,16 @@ // Author: // sprusr -module.exports = (robot) => { +module.exports = robot => { const Figma = require('figma-js') const { WebClient } = require('@slack/client') const figma = Figma.Client({ personalAccessToken: process.env.HUBOT_FIGMA_TOKEN }) - const slack = robot.adapterName === 'slack' ? new WebClient(robot.adapter.options.token) : undefined + const slack = + robot.adapterName === 'slack' + ? new WebClient(robot.adapter.options.token) + : undefined const fileRegex = /!(https?:\/\/)?(www.)?figma.com\/file\/([A-z0-9]*)\/?/g const simpleFigma = async (msg, files) => { @@ -32,23 +35,26 @@ module.exports = (robot) => { for (let file of files) { await slack.chat.postMessage({ channel: msg.message.rawMessage.channel, - attachments: [{ - fallback: `${file.name} on Figma ${file.thumbnailUrl}`, - color: '#36a64f', - title: file.name, - title_link: file.url, - image_url: file.thumbnailUrl, - footer: 'Figma', - footer_icon: 'https://static.figma.com/app/icon/1/favicon.png', - ts: Math.round(Date.parse(file.lastModified) / 1000) // unixtime - }] + attachments: [ + { + fallback: `${file.name} on Figma ${file.thumbnailUrl}`, + color: '#36a64f', + title: file.name, + title_link: file.url, + image_url: file.thumbnailUrl, + footer: 'Figma', + footer_icon: 'https://static.figma.com/app/icon/1/favicon.png', + ts: Math.round(Date.parse(file.lastModified) / 1000) // unixtime + } + ] }) } } robot.hear(fileRegex, async msg => { - let matches, files = [] - while (matches = fileRegex.exec(msg.message.text)) { + let matches, + files = [] + while ((matches = fileRegex.exec(msg.message.text))) { const fileId = matches[3] try { const file = await figma.file(fileId) diff --git a/scripts/github-issue-link.js b/scripts/github-issue-link.js index 6fe8c0f..2d7b6de 100644 --- a/scripts/github-issue-link.js +++ b/scripts/github-issue-link.js @@ -32,12 +32,12 @@ module.exports = function(robot) { } robot.hear(issueRegex, async msg => { - let matches, included = [], response = '' - while (matches = issueRegex.exec(msg.message.text)) { - if (included.indexOf(matches[0]) === -1) - included.push(matches[0]) - else - continue + let matches, + included = [], + response = '' + while ((matches = issueRegex.exec(msg.message.text))) { + if (included.indexOf(matches[0]) === -1) included.push(matches[0]) + else continue const issueNumber = matches[2] @@ -51,7 +51,7 @@ module.exports = function(robot) { const issue = await getIssue(repo, issueNumber) const title = issue.title const url = issue.html_url - const type = issue.pull_request ? "PR" : "Issue" + const type = issue.pull_request ? 'PR' : 'Issue' response += `${type} #${issueNumber}: ${title} ${url}\n` } diff --git a/scripts/utils/brain.js b/scripts/utils/brain.js index d02118b..04a912a 100644 --- a/scripts/utils/brain.js +++ b/scripts/utils/brain.js @@ -1,49 +1,48 @@ module.exports = brainPrefix => { const getMap = (key, brain) => - JSON.parse(brain.get(`${brainPrefix}-${key}`)) || {}; + JSON.parse(brain.get(`${brainPrefix}-${key}`)) || {} const setMap = (key, value, brain) => - brain.set(`${brainPrefix}-${key}`, JSON.stringify(value)); + brain.set(`${brainPrefix}-${key}`, JSON.stringify(value)) - const removeMap = (key, brain) => - brain.remove(`${brainPrefix}-${key}`); + const removeMap = (key, brain) => brain.remove(`${brainPrefix}-${key}`) const addToMap = (mapKey, key, value, brain) => { - const map = getMap(mapKey, brain); + const map = getMap(mapKey, brain) // Use incremental number if no key is given - key = key || Object.keys(map).length + 1; + key = key || Object.keys(map).length + 1 if (map[key]) { - return false; + return false } - map[key] = value; - setMap(mapKey, map, brain); + map[key] = value + setMap(mapKey, map, brain) return true - }; + } const updateMap = (mapKey, key, value, brain) => { - const map = getMap(mapKey, brain); + const map = getMap(mapKey, brain) if (!key || !map[key]) { - return false; + return false } - map[key] = value; - setMap(mapKey, map, brain); - return true; - }; + map[key] = value + setMap(mapKey, map, brain) + return true + } const getFromMap = (mapKey, key, brain) => { - const map = getMap(mapKey, brain); - return map[key]; - }; + const map = getMap(mapKey, brain) + return map[key] + } const removeFromMap = (mapKey, key, brain) => { - const map = getMap(mapKey, brain); + const map = getMap(mapKey, brain) if (!map[key]) { - return false; + return false } - delete map[key]; - setMap(mapKey, map, brain); - return true; - }; + delete map[key] + setMap(mapKey, map, brain) + return true + } return { addToMap, @@ -52,7 +51,6 @@ module.exports = brainPrefix => { removeFromMap, removeMap, setMap, - updateMap, - }; + updateMap + } } - diff --git a/scripts/utils/channels.js b/scripts/utils/channels.js index ec87564..63d5bd5 100644 --- a/scripts/utils/channels.js +++ b/scripts/utils/channels.js @@ -1,4 +1,4 @@ -const isPrivateSlackMessage = res => res.message.room.startsWith('D'); -const isChannel = (res, channelId) => res.message.room === channelId; +const isPrivateSlackMessage = res => res.message.room.startsWith('D') +const isChannel = (res, channelId) => res.message.room === channelId -module.exports = { isPrivateSlackMessage, isChannel }; +module.exports = { isPrivateSlackMessage, isChannel } diff --git a/scripts/utils/dates.js b/scripts/utils/dates.js index 6a6af1e..81669ec 100644 --- a/scripts/utils/dates.js +++ b/scripts/utils/dates.js @@ -1,67 +1,65 @@ -const chrono = require('chrono-node'); +const chrono = require('chrono-node') const getOffsetDate = (offset, timestamp = Date.now()) => { - const d = new Date(timestamp + offset * 60 * 60 * 1000); - return `${d.getUTCFullYear()}-${d.getUTCMonth() + 1}-${d.getUTCDate()}`; -}; + const d = new Date(timestamp + offset * 60 * 60 * 1000) + return `${d.getUTCFullYear()}-${d.getUTCMonth() + 1}-${d.getUTCDate()}` +} const getOffsetDay = offset => { - const d = new Date(Date.now() + offset * 60 * 60 * 1000); - return d.getUTCDay(); -}; + const d = new Date(Date.now() + offset * 60 * 60 * 1000) + return d.getUTCDay() +} const getOffsetHour = offset => { - const d = new Date(Date.now() + offset * 60 * 60 * 1000); - return d.getUTCHours(); -}; + const d = new Date(Date.now() + offset * 60 * 60 * 1000) + return d.getUTCHours() +} // Returns the current date for a specific user const getCurrentDateForUser = user => { - const offset = user.slack.tz_offset / (60 * 60); - return getOffsetDate(offset); -}; + const offset = user.slack.tz_offset / (60 * 60) + return getOffsetDate(offset) +} const getCurrentDayForUser = user => { - const offset = user.slack.tz_offset / (60 * 60); - return getOffsetDay(offset); -}; + const offset = user.slack.tz_offset / (60 * 60) + return getOffsetDay(offset) +} const getCurrentTimeForUser = user => { - const offset = user.slack.tz_offset / (60 * 60); - return getOffsetHour(offset); -}; + const offset = user.slack.tz_offset / (60 * 60) + return getOffsetHour(offset) +} const dateIsInRange = (dateStr, rangeStr) => { - const range = rangeStr.split('>'); - const date = new Date(dateStr); - const start = new Date(range[0]); - const end = new Date(range[1]); - return start <= date && date <= end; -}; + const range = rangeStr.split('>') + const date = new Date(dateStr) + const start = new Date(range[0]) + const end = new Date(range[1]) + return start <= date && date <= end +} const dateIsOlderThan = (dateOrRangeStr, refDate) => { const date = dateOrRangeStr.includes('>') ? dateOrRangeStr.split('>')[1] - : dateOrRangeStr; - return new Date(date) <= new Date(refDate); -}; + : dateOrRangeStr + return new Date(date) <= new Date(refDate) +} const parseNaturalDate = (expr, user) => { - const referenceDate = new Date(`${getCurrentDateForUser(user)} 11:00Z`); - const parsed = chrono.parse(expr, referenceDate, { forwardDate: true }); - const { start } = parsed[0]; - const end = parsed.length === 2 - ? parsed[1].start - : parsed[0].end; + const referenceDate = new Date(`${getCurrentDateForUser(user)} 11:00Z`) + const parsed = chrono.parse(expr, referenceDate, { forwardDate: true }) + const { start } = parsed[0] + const end = parsed.length === 2 ? parsed[1].start : parsed[0].end const dateStart = `${start.get('year')}-${start.get('month')}-${start.get( 'day' - )}`; + )}` if (end) { - const dateEnd = `${end.get('year')}-${end.get('month')}-${end.get('day')}`; - return `${dateStart}>${dateEnd}`; + const dateEnd = `${end.get('year')}-${end.get('month')}-${end.get('day')}` + return `${dateStart}>${dateEnd}` } - return dateStart; -}; + return dateStart +} module.exports = { getOffsetDate, @@ -72,5 +70,5 @@ module.exports = { getCurrentTimeForUser, dateIsInRange, dateIsOlderThan, - parseNaturalDate, -}; + parseNaturalDate +}