Skip to content

Commit

Permalink
feat(2492): Update to eslint-config-screwdriver v5 (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
tkyi authored Jul 9, 2021
1 parent c150906 commit d2e3d4a
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 139 deletions.
153 changes: 77 additions & 76 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
'use strict';

const Joi = require('joi');
const slacker = require('./slack');
const NotificationBase = require('screwdriver-notifications-base');
const schema = require('screwdriver-data-schema');
const hoek = require('@hapi/hoek');
const slacker = require('./slack');

// This should match what is in https://github.com/screwdriver-cd/data-schema/blob/master/models/build.js#L14
// https://github.com/screwdriver-cd/ui/blob/master/app/styles/screwdriver-colors.scss
Expand Down Expand Up @@ -42,43 +42,46 @@ const SCHEMA_SLACK_CHANNEL = Joi.string().required();
const SCHEMA_SLACK_CHANNELS = Joi.array()
.items(SCHEMA_SLACK_CHANNEL)
.min(1);
const SCHEMA_SLACK_SETTINGS = Joi.object().keys({
slack: Joi.alternatives().try(
Joi.object().keys({
channels: SCHEMA_SLACK_CHANNELS,
statuses: SCHEMA_STATUSES,
minimized: Joi.boolean()
}),
SCHEMA_SLACK_CHANNELS, SCHEMA_SLACK_CHANNEL
).required()
}).unknown(true);
const SCHEMA_BUILD_DATA = Joi.object()
const SCHEMA_SLACK_SETTINGS = Joi.object()
.keys({
...schema.plugins.notifications.schemaBuildData,
settings: SCHEMA_SLACK_SETTINGS.required()
});
const SCHEMA_SLACK_CONFIG = Joi.object()
.keys({
token: Joi.string().required()
});
slack: Joi.alternatives()
.try(
Joi.object().keys({
channels: SCHEMA_SLACK_CHANNELS,
statuses: SCHEMA_STATUSES,
minimized: Joi.boolean()
}),
SCHEMA_SLACK_CHANNELS,
SCHEMA_SLACK_CHANNEL
)
.required()
})
.unknown(true);
const SCHEMA_BUILD_DATA = Joi.object().keys({
...schema.plugins.notifications.schemaBuildData,
settings: SCHEMA_SLACK_SETTINGS.required()
});
const SCHEMA_SLACK_CONFIG = Joi.object().keys({
token: Joi.string().required()
});

class SlackNotifier extends NotificationBase {
/**
* Constructs an SlackNotifier
* @constructor
* @param {object} config - Screwdriver config object initialized in API
*/
* Constructs an SlackNotifier
* @constructor
* @param {object} config - Screwdriver config object initialized in API
*/
constructor(config) {
super(...arguments);
this.config = Joi.attempt(config, SCHEMA_SLACK_CONFIG,
'Invalid config for slack notifications');
this.config = Joi.attempt(config, SCHEMA_SLACK_CONFIG, 'Invalid config for slack notifications');
}

/**
* Sets listener on server event of name 'eventName' in Screwdriver
* Currently, event is triggered with a build status is updated
* @method _notify
* @param {Object} buildData - Build data emitted with some event from Screwdriver
*/
* Sets listener on server event of name 'eventName' in Screwdriver
* Currently, event is triggered with a build status is updated
* @method _notify
* @param {Object} buildData - Build data emitted with some event from Screwdriver
*/
_notify(buildData) {
// Check buildData format against SCHEMA_BUILD_DATA
try {
Expand All @@ -100,15 +103,12 @@ class SlackNotifier extends NotificationBase {
if (metaDataSlackChannel) {
channelReplacement = metaDataSlackChannel.split(',');
// Remove empty/blank items.
channelReplacement = channelReplacement.filter(
x => (x.trim() !== ('')));
channelReplacement = channelReplacement.filter(x => x.trim() !== '');
}
// Slack channels from configuration
if (typeof buildData.settings.slack === 'string' ||
Array.isArray(buildData.settings.slack)) {
buildData.settings.slack = (typeof buildData.settings.slack === 'string')
? [buildData.settings.slack]
: buildData.settings.slack;
if (typeof buildData.settings.slack === 'string' || Array.isArray(buildData.settings.slack)) {
buildData.settings.slack =
typeof buildData.settings.slack === 'string' ? [buildData.settings.slack] : buildData.settings.slack;
buildData.settings.slack = {
channels: buildData.settings.slack,
statuses: DEFAULT_STATUSES,
Expand Down Expand Up @@ -144,30 +144,30 @@ class SlackNotifier extends NotificationBase {
const pipelineLink = buildData.buildLink.split('/builds')[0];
const truncatedSha = buildData.event.sha.slice(0, 6);
const cutOff = 150;
const commitMessage = buildData.event.commit.message.length > cutOff ?
`${buildData.event.commit.message.substring(0, cutOff)}...` :
buildData.event.commit.message;
const commitMessage =
buildData.event.commit.message.length > cutOff
? `${buildData.event.commit.message.substring(0, cutOff)}...`
: buildData.event.commit.message;

// Slack channel overwrite from meta data. Job specific only.
const metaMinimizedReplaceVar =
`build.meta.notification.slack.${buildData.jobName}.minimized`;
const isMinimized = hoek.reach(buildData, metaMinimizedReplaceVar,
{ default: buildData.settings.slack.minimized });
const metaMinimizedReplaceVar = `build.meta.notification.slack.${buildData.jobName}.minimized`;
const isMinimized = hoek.reach(buildData, metaMinimizedReplaceVar, {
default: buildData.settings.slack.minimized
});

let message = isMinimized ?
// eslint-disable-next-line max-len
`<${pipelineLink}|${buildData.pipeline.scmRepo.name}#${buildData.jobName}> *${notificationStatus}*` :
// eslint-disable-next-line max-len
`*${notificationStatus}* ${STATUSES_MAP[notificationStatus]} <${pipelineLink}|${buildData.pipeline.scmRepo.name} ${buildData.jobName}>`;
let message = isMinimized
? // eslint-disable-next-line max-len
`<${pipelineLink}|${buildData.pipeline.scmRepo.name}#${buildData.jobName}> *${notificationStatus}*`
: // eslint-disable-next-line max-len
`*${notificationStatus}* ${STATUSES_MAP[notificationStatus]} <${pipelineLink}|${buildData.pipeline.scmRepo.name} ${buildData.jobName}>`;

const rootDir = hoek.reach(buildData, 'pipeline.scmRepo.rootDir', { default: false });

if (rootDir) {
message = `${message}\n*Source Directory:* ${rootDir}`;
}

const metaMessage = hoek.reach(buildData,
'build.meta.notification.slack.message', { default: false });
const metaMessage = hoek.reach(buildData, 'build.meta.notification.slack.message', { default: false });

const metaVar = `build.meta.notification.slack.${buildData.jobName}.message`;

Expand All @@ -179,31 +179,32 @@ class SlackNotifier extends NotificationBase {
} else if (metaMessage) {
message = `${message}\n${metaMessage}`;
}
const attachments = isMinimized ?
[
{
fallback: '',
color: COLOR_MAP[notificationStatus],
fields: [
{
title: 'Build',
value: `<${buildData.buildLink}|#${buildData.build.id}>`,
short: true
}
]
}
] :
[
{
fallback: '',
color: COLOR_MAP[notificationStatus],
title: `#${buildData.build.id}`,
title_link: `${buildData.buildLink}`,
// eslint-disable-next-line max-len
text: `${commitMessage} (<${buildData.event.commit.url}|${truncatedSha}>)` +
`\n${buildData.event.causeMessage}`
}
];
const attachments = isMinimized
? [
{
fallback: '',
color: COLOR_MAP[notificationStatus],
fields: [
{
title: 'Build',
value: `<${buildData.buildLink}|#${buildData.build.id}>`,
short: true
}
]
}
]
: [
{
fallback: '',
color: COLOR_MAP[notificationStatus],
title: `#${buildData.build.id}`,
title_link: `${buildData.buildLink}`,
// eslint-disable-next-line max-len
text:
`${commitMessage} (<${buildData.event.commit.url}|${truncatedSha}>)` +
`\n${buildData.event.causeMessage}`
}
];
const slackMessage = {
message,
attachments
Expand Down
23 changes: 12 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,26 @@
"Tiffany Kyi <[email protected]>"
],
"devDependencies": {
"chai": "^3.5.0",
"eslint": "^4.19.1",
"eslint-config-screwdriver": "^3.0.0",
"mocha": "^8.2.1",
"chai": "^4.2.0",
"eslint": "^7.5.0",
"eslint-config-screwdriver": "^5.0.1",
"mocha": "^8.4.0",
"mocha-multi-reporters": "^1.5.1",
"mocha-sonarqube-reporter": "^1.0.2",
"mockery": "^2.1.0",
"nyc": "^15.0.0",
"sinon": "^4.5.0"
"sinon": "^9.0.0"
},
"dependencies": {
"@hapi/hapi": "^20.0.0",
"@hapi/hoek": "^9.0.4",
"@slack/web-api": "^5.14.0",
"joi": "^17.2.1",
"mockery": "^2.1.0",
"@hapi/hapi": "^20.1.5",
"@hapi/hoek": "^9.2.0",
"@slack/web-api": "^5.15.0",
"joi": "^17.4.0",
"request": "^2.87.0",
"samsam": "^1.3.0",
"screwdriver-data-schema": "^21.0.0",
"screwdriver-notifications-base": "^3.0.0"
"screwdriver-logger": "^1.0.2",
"screwdriver-notifications-base": "^3.0.3"
},
"release": {
"debug": false,
Expand Down
23 changes: 12 additions & 11 deletions slack.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const { WebClient } = require('@slack/web-api');
const logger = require('screwdriver-logger');

let web;

Expand All @@ -13,21 +14,21 @@ let web;
*/
function postMessage(channelName, payload) {
// Can post to channel name directly https://api.slack.com/methods/chat.postMessage#channels
return web.chat.postMessage({
channel: channelName,
text: payload.message,
as_user: true,
attachments: payload.attachments
})
// eslint-disable-next-line no-console
.catch(err => console.error(err.message));
return web.chat
.postMessage({
channel: channelName,
text: payload.message,
as_user: true,
attachments: payload.attachments
})
.catch(err => logger.error(`postMessage: failed to notify Slack channel ${channelName}: ${err.message}`));
}

/**
* Sends slack message to slack channels
* @param {String} token access token for slack
* @param {String[]} channels slack channel names
* @param {Object} payload
* @param {String} token access token for slack
* @param {String[]} channels slack channel names
* @param {Object} payload slack message payload
* @return {Promise}
*/
function slacker(token, channels, payload) {
Expand Down
Loading

0 comments on commit d2e3d4a

Please sign in to comment.