Skip to content

Commit

Permalink
Merge pull request #2 from tiloio/feature/mention
Browse files Browse the repository at this point in the history
Feature/mention
  • Loading branch information
tiloio authored Oct 5, 2020
2 parents 4ee6311 + 2a0def3 commit dbaa013
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 5 deletions.
3 changes: 3 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ inputs:
slack_web_hook_url:
description: "Webhook URL from Slack for the notification (see https://vw-dilab-projects.slack.com/apps/A0F7XDUAZ-incoming-webhooks)."
required: true
slack_mention_mapping_file:
description: "An optional mapping file to map GitHub Usernames and @Mentions to real Slack Mentions."
required: false
runs:
using: 'node12'
main: 'index.js'
50 changes: 45 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,53 @@ const fs = require('fs');

const inputSlackJson = core.getInput('slack_json');
const webHookUrl = core.getInput('slack_web_hook_url');
const slackMentionMappingFilePath = core.getInput('slack_mention_mapping_file');
const commitSHA = process.env.GITHUB_SHA;
const repositoryName = process.env.GITHUB_REPOSITORY;
const authorName = process.env.GITHUB_ACTOR;
const eventPath = process.env.GITHUB_EVENT_PATH;
const runId = process.env.GITHUB_RUN_ID;


const escapeRegex = (string) => string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

let slackMentionMappingData = null;

const slackMentionMapping = () => {
if (!slackMentionMappingFilePath) return null;

if (slackMentionMappingData == null) {
this.slackMentionMapping = JSON.parse(fs.readFileSync(slackMentionMappingFilePath, 'utf8'));
}

return this.slackMentionMapping;
}
const slackMention = (slackUserId) => `<@${slackUserId}>`;
const mentionRegex = (mention) => new RegExp(`@${escapeRegex(mention)}`, 'gi');
const gitHubNameToSlackMention = (gitHubName) => {
if (!slackMentionMapping()) return gitHubName;

const slackMappingObject = slackMentionMapping()[gitHubName];
if (!slackMappingObject) return gitHubName;

return slackMention(slackMappingObject.slackId);
}
const replaceAllMentions = (json) => {
if (!slackMentionMapping()) return json;

let replacedText = json;
Object.entries(slackMentionMapping()).forEach(([key, user]) => {
if (user.mentions) {
user.mentions.forEach(mention => {
replacedText = replacedText.replace(mentionRegex(mention), slackMention(user.slackId));
});
}
});
return replacedText;
}

const readEventFile = () => fs.readFileSync(eventPath, 'utf8');
const escapeUnicode = (str) => str.replace(/[^\0-~]/g, (ch) =>
const escapeUnicode = (str) => str.replace(/[^\0-~]/g, (ch) =>
"\\u" + ("000" + ch.charCodeAt().toString(16)).slice(-4)
);
const commitMessage = () => JSON.parse(readEventFile()).commits[0].message;
Expand Down Expand Up @@ -44,10 +83,11 @@ const listOfVariables = [
envVariable('GITHUB_GRAPHQL_URL'),
customVariable('CUSTOM_COMMIT_URL', () => `https://github.com/${repositoryName}/commit/${commitSHA}`),
customVariable('CUSTOM_AUTHOR_LINK', () => `http://github.com/${authorName}`),
customVariable('CUSTOM_AUTHOR_PICTURE', () => `http://github.com/${authorName}.png?size=32`),
customVariable('CUSTOM_AUTHOR_PICTURE', () => `http://github.com/${authorName}.png?size=32`),
customVariable('CUSTOM_SHORT_GITHUB_SHA', () => process.env.GITHUB_SHA.substring(0, 7)),
customVariable('CUSTOM_COMMIT_MSG', () => commitMessage()),
customVariable('CUSTOM_ACTION_LINK', () => `https://github.com/${repositoryName}/actions/runs/${runId}`),
customVariable('CUSTOM_GITHUB_ACTOR_AS_SLACK', () => gitHubNameToSlackMention(authorName)),
];

const replacer = (json) => {
Expand Down Expand Up @@ -80,11 +120,11 @@ function sendMessage(data) {

(async () => {
try {
const data = escapeUnicode(replacer(inputSlackJson));
const data = escapeUnicode(replaceAllMentions(replacer(inputSlackJson)));
const result = await sendMessage(data);

if (result !== 'ok') {
if (result === 'invalid_payload') {
if (result !== 'ok') {
if (result === 'invalid_payload') {
core.setFailed('Could not send notification with invalid payload: ' + data);
} else {
core.setFailed('Could not send notification: ' + result);
Expand Down
20 changes: 20 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ You can use all this `{{placeholders}}`:
| CUSTOM_SHORT_GITHUB_SHA | process.env.GITHUB_SHA.substring(0, 7) |
| CUSTOM_COMMIT_MSG | commitMessage |
| CUSTOM_ACTION_LINK | https://github.com/${repositoryName}/actions/runs/${runId} |
| CUSTOM_GITHUB_ACTOR_AS_SLACK | creates an `@UserName` in the Slack message. Needs the `slack_mention_mapping_file` input, otherwise it will return the GitHub username. |
| GITHUB_WORKFLOW | The name of the workflow. |
| GITHUB_RUN_ID | A unique number for each run within a repository. This number does not change if you re-run the workflow run. |
| GITHUB_RUN_NUMBER | A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run. |
Expand All @@ -46,6 +47,25 @@ You can use all this `{{placeholders}}`:

More information about the [GitHub placeholders (which are environment variables)](https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables).

### `slack_mention_mapping_file`

**Optional** Only needed when you want to map the GitHub usernames to Slack `@mentions`.

The file should look like:
```json
{
"john-smith": {
"slackId": "1234465",
"mentions": ["john" "johnSmith", "john-smith"]
}
}
```

Where
- **john-smith** is the GitHub Username,
- **slackId** is the ID of the Slack-Account of this GitHub User (more here: https://api.slack.com/reference/surfaces/formatting#mentioning-users),
- **mentions** an Array of Strings which are used to replace e.g. `@johnSmith` with a real Slack `@Mention`, it's case insensitive.

## Outputs

There are no outputs at the moment.
Expand Down

0 comments on commit dbaa013

Please sign in to comment.