Repository: 8398a7/action-slack
Pull request #164 (2021-10-21 23:07:31)

Add field 'pullRequest' as pull request title, number with link
Add field `pullRequest` as pull request title, number with link.

Motivation:
When triggered with pull request event, the commit is the SHA of the merge commit, and the message is "HEAD into BASE".
I can trace the pull request page from `job` or `workflow`, but it would be nice to be able to refer to the pull request directly.

Note:
When it is triggered by push event, this field shows "n/a".

~~Discussions:
Which is the best format for the pullRequest field?
Current: `<url | title #numer>`
Alternative: `title <html_url | #numer>`~~


Patch:
diff --git a/README.md b/README.md
index c91200d..f3b5619 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@ steps:
   - uses: 8398a7/action-slack@v3
     with:
       status: ${{ job.status }}
-      fields: repo,message,commit,author,action,eventName,ref,workflow,job,took # selectable (default: repo,message)
+      fields: repo,message,commit,author,action,eventName,ref,workflow,job,took,pullRequest # selectable (default: repo,message)
     env:
       SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} # required
     if: always() # Pick up events even if the job fails or is canceled.
@@ -57,7 +57,7 @@ steps:
     with:
       github_base_url: https://your.ghe.com # Specify your GHE
       status: ${{ job.status }}
-      fields: repo,message,commit,author,action,eventName,ref,workflow,job,took
+      fields: repo,message,commit,author,action,eventName,ref,workflow,job,took,pullRequest
     env:
       SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
     if: always()
diff --git a/docs/content/fields.md b/docs/content/fields.md
index 1bf64aa..9e266be 100644
--- a/docs/content/fields.md
+++ b/docs/content/fields.md
@@ -6,7 +6,7 @@ metaDescription: This explains the values that can be specified in Fields.
 
 caution: Additional configuration is required to work with matrix.
 
-Don't forget to add `MATRIX_CONTEXT`.  
+Don't forget to add `MATRIX_CONTEXT`.
 Not required if the fields do not contain jobs or tooks.
 
 ```yaml
@@ -19,22 +19,23 @@ steps:
       MATRIX_CONTEXT: ${{ toJson(matrix) }} # required
 ```
 
-If you have more than one, please enter it in csv format.  
+If you have more than one, please enter it in csv format.
 Corresponding types are as follows.
 
 <img width="495" alt="success" src="https://user-images.githubusercontent.com/8043276/84587112-64844800-ae57-11ea-8007-7ce83a91dae3.png" />
 
-| Field     | Environment Variable    | Description                                                  |
-| --------- | ----------------------- | ------------------------------------------------------------ |
-| repo      | `AS_REPO`               | A working repository name                                    |
-| commit    | `AS_COMMIT`             | commit hash                                                  |
-| eventName | `AS_EVENT_NAME`         | trigger event name                                           |
-| ref       | `AS_REF`                | git refrence                                                 |
-| workflow  | `AS_WORKFLOW`           | Generate a workflow link from git sha                        |
-| message   | `AS_MESSAGE`            | commit message                                               |
-| author    | `AS_AUTHOR`             | The author who pushed                                        |
-| job       | `AS_JOB`                | Generate a job run link of the job that was executed         |
-| took      | `AS_TOOK`               | Execution time for the job                                   |
+| Field       | Environment Variable    | Description                                                 |
+| ----------- | ----------------------- | ----------------------------------------------------------- |
+| repo        | `AS_REPO`               | A working repository name                                   |
+| commit      | `AS_COMMIT`             | commit hash                                                 |
+| eventName   | `AS_EVENT_NAME`         | trigger event name                                          |
+| ref         | `AS_REF`                | git reference                                               |
+| workflow    | `AS_WORKFLOW`           | Generate a workflow link from git sha                       |
+| message     | `AS_MESSAGE`            | commit message                                              |
+| author      | `AS_AUTHOR`             | The author who pushed                                       |
+| job         | `AS_JOB`                | Generate a job run link of the job that was executed        |
+| took        | `AS_TOOK`               | Execution time for the job                                  |
+| pullRequest | `AS_PULL_REQUEST`       | Pull Request title, number with link                        |
 
 ```yaml
 steps:
diff --git a/docs/content/usecase/01-general.md b/docs/content/usecase/01-general.md
index 7bf4e6f..c87e905 100644
--- a/docs/content/usecase/01-general.md
+++ b/docs/content/usecase/01-general.md
@@ -11,13 +11,13 @@ steps:
   - uses: 8398a7/action-slack@v3
     with:
       status: ${{ job.status }}
-      fields: repo,message,commit,author,action,eventName,ref,workflow,job,took # selectable (default: repo,message)
+      fields: repo,message,commit,author,action,eventName,ref,workflow,job,took,pullRequest # selectable (default: repo,message)
     env:
       SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} # required
     if: always() # Pick up events even if the job fails or is canceled.
 ```
 
-`status: ${{ job.status }}` allows a job to succeed, fail or cancel etc. to action-slack.  
+`status: ${{ job.status }}` allows a job to succeed, fail or cancel etc. to action-slack.
 `if: always()` to trigger action-slack even if the job fails Let them.
 
 For the fields, look at [Fields](/fields) to determine what you want.
diff --git a/src/fields.ts b/src/fields.ts
index 90059f0..04cd299 100644
--- a/src/fields.ts
+++ b/src/fields.ts
@@ -73,6 +73,9 @@ export class FieldFactory {
         this.includes('workflow')
           ? createAttachment('workflow', await this.workflow())
           : undefined,
+        this.includes('pullRequest')
+          ? createAttachment('pullRequest', await this.pullRequest())
+          : undefined,
       ],
       undefined,
     );
@@ -193,6 +196,17 @@ export class FieldFactory {
     return value;
   }
 
+  private async pullRequest(): Promise<string> {
+    let value;
+    if (context.eventName.startsWith('pull_request')) {
+      value = `<${context.payload.pull_request?.html_url}|${context.payload.pull_request?.title} #${context.payload.pull_request?.number}>`;
+    } else {
+      value = 'n/a';
+    }
+    process.env.AS_PULL_REQUEST = value;
+    return value;
+  }
+
   private async action(): Promise<string> {
     const sha = context.payload.pull_request?.head.sha ?? context.sha;
     const { owner, repo } = context.repo;


Test patch:
diff --git a/__tests__/client.test.ts b/__tests__/client.test.ts
index 90bc8b3..6eb270e 100644
--- a/__tests__/client.test.ts
+++ b/__tests__/client.test.ts
@@ -80,7 +80,7 @@ describe('8398a7/action-slack', () => {
         ...newWith(),
         status: Success,
         fields:
-          'repo,message,commit,author,job,action,eventName,ref,workflow,took',
+          'repo,message,commit,author,job,action,eventName,ref,workflow,took,pullRequest',
       };
       const client = new Client(
         withParams,
@@ -585,7 +585,7 @@ describe('8398a7/action-slack', () => {
         ...newWith(),
         status: Success,
         fields:
-          'repo,message,commit,author,job,action,eventName,ref,workflow,took',
+          'repo,message,commit,author,job,action,eventName,ref,workflow,took,pullRequest',
       };
       const client = new Client(
         withParams,
diff --git a/__tests__/helper.ts b/__tests__/helper.ts
index 5e843c8..8a4aada 100644
--- a/__tests__/helper.ts
+++ b/__tests__/helper.ts
@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';
 import { resolve } from 'path';
 import { Field, With } from '../src/client';
 import { FieldFactory } from '../src/fields';
-import { getOctokit } from '@actions/github';
+import github, { context, getOctokit } from '@actions/github';
 
 export const gitHubToken = 'github-token';
 export const gitHubBaseUrl = '';
@@ -92,6 +92,7 @@ export const fixedFields = (fields: string, sha?: string) => {
       ff.includes('eventName') ? eventName() : undefined,
       ff.includes('ref') ? ref() : undefined,
       ff.includes('workflow') ? workflow(sha) : undefined,
+      ff.includes('pullRequest') ? pullRequest() : undefined,
     ],
     undefined,
   );
@@ -175,3 +176,18 @@ export const took = (): Field => {
     value: '1 hour 1 min 1 sec',
   };
 };
+
+export const pullRequest = (): Field => {
+  let value;
+  if (context.eventName.startsWith('pull_request')) {
+    value =
+      '<https://github.com/8398a7/action-slack/pull/123|Add pullRequest field #123>';
+  } else {
+    value = 'n/a';
+  }
+  return {
+    short: true,
+    title: 'pullRequest',
+    value: value,
+  };
+};
diff --git a/__tests__/pull_request.test.ts b/__tests__/pull_request.test.ts
index adb4458..de6285a 100644
--- a/__tests__/pull_request.test.ts
+++ b/__tests__/pull_request.test.ts
@@ -11,6 +11,7 @@ import {
   webhookUrl,
 } from './helper';
 import { Client, Success } from '../src/client';
+import github from '@actions/github';
 
 beforeAll(() => {
   nock.disableNetConnect();
@@ -52,3 +53,44 @@ describe('pull request event', () => {
     expect(await client.prepare(msg)).toStrictEqual(payload);
   });
 });
+
+describe.each`
+  eventName
+  ${`pull_request`}
+  ${`pull_request_review`}
+  ${`pull_request_review_comment`}
+  ${`pull_request_target`}
+`('pullRequest field on pull_request events', ({ eventName }) => {
+  test(`${eventName}`, async () => {
+    const github = require('@actions/github');
+    const sha = 'expected-sha-for-pull_request_event';
+    github.context.payload = {
+      pull_request: {
+        html_url: 'https://github.com/8398a7/action-slack/pull/123',
+        title: 'Add pullRequest field',
+        number: 123,
+        head: { sha },
+      },
+    };
+    github.context.eventName = eventName;
+
+    const withParams = {
+      ...newWith(),
+      status: Success,
+      fields: 'pullRequest',
+    };
+    const client = new Client(
+      withParams,
+      gitHubToken,
+      gitHubBaseUrl,
+      webhookUrl,
+    );
+    const msg = 'pullRequest test';
+    const payload = getTemplate(withParams.fields, msg, sha);
+    payload.attachments[0].color = 'good';
+    expect(await client.prepare(msg)).toStrictEqual(payload);
+    expect(process.env.AS_PULL_REQUEST).toStrictEqual(
+      '<https://github.com/8398a7/action-slack/pull/123|Add pullRequest field #123>',
+    );
+  });
+});