Skip to content

Add GitHubPRComment DevOps task #6190

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
parser: '@typescript-eslint/parser', // Specifies the ESLint parser
plugins: [ '@typescript-eslint' ],
extends: [
'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
]
};
3 changes: 3 additions & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
package-lock.json
!.eslintrc.js
1 change: 1 addition & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/.taskkey
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a8d096b7-2897-4a63-8f8d-922a3bff9562
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
75 changes: 75 additions & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/

import taskLibrary = require('azure-pipelines-task-lib/task');
import gitClient = require('@octokit/rest');
import path = require('path');
import fs = require('fs');

const clientWithAuth = new gitClient({
auth: "token "+ taskLibrary.getInput('userToken'),
userAgent: 'octokit/rest.js v1.2.3',
});

async function run() {
const files = getFilesFromDir(taskLibrary.getInput('bodyFilePath'), '.' + taskLibrary.getInput('extension'), taskLibrary.getBoolInput('getSubFolders'))
const message = combineMessageBody(files);
const repo = taskLibrary.getInput('repository').split('/');

const comment: gitClient.IssuesCreateCommentParams = {
owner: repo[0],
repo: repo[1],
number: parseInt(taskLibrary.getInput('prNumber')),
body: "\r\n" + message + "\r\n"
};

await clientWithAuth.issues.createComment(comment).then(res => {
console.log(res);
})
.catch(err => {
taskLibrary.setResult(taskLibrary.TaskResult.Failed, err);
});
}

const getFilesFromDir = (filePath: string, extName: string, recursive: boolean): string[] => {
if (!fs.existsSync(filePath)){
console.log("File path does not exist: ",filePath);
return [];
}
const result: string[] = [];
iterateFilesFromDir(filePath, extName, recursive, result);

return result;
}

const iterateFilesFromDir = (filePath: string, extName: string, recursive: boolean, result: string[]): string[] => {
const files = fs.readdirSync(filePath);
files.forEach(file => {
const fileName = path.join(filePath,file);
const isFolder = fs.lstatSync(fileName);
if (recursive && isFolder.isDirectory()){
result = iterateFilesFromDir(fileName, extName, recursive, result);
}

if (path.extname(fileName) == extName){
result.push(fileName);
}
});

return result;
}

const combineMessageBody = (files: string[]): string => {
let body = "";
files.forEach(file => {
const bodyFile = fs.readFileSync(file);
// var fileObject = JSON.parse(bodyFile.toString());
// body += fileObject["body"].toString() + "\r\n";
body += bodyFile + "\r\n";
});
return body;
}

run();
32 changes: 32 additions & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "pr-comment-task",
"version": "1.0.0",
"description": "A task to post comments on github from azure devops",
"main": "index.js",
"scripts": {
"test": "npm test",
"lint": "eslint ./*.ts"
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/botframework-sdk/tree/main/tools/devops-tasks/ApiCompat"
},
"keywords": [
"api",
"compat"
],
"author": "ParadoxArg",
"license": "ISC",
"dependencies": {
"@octokit/rest": "16.21.0",
"azure-pipelines-task-lib": "^2.8.0"
},
"devDependencies": {
"@types/node": "^11.12.0",
"@types/q": "^1.5.2",
"@typescript-eslint/eslint-plugin": "^4.14.2",
"@typescript-eslint/parser": "^4.14.2",
"eslint": "^7.19.0",
"typescript": "^4.1.3"
}
}
70 changes: 70 additions & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/task.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"id": "5609d229-6359-4b0d-a21a-1207d7e11dfe",
"name": "github-pr-comment",
"friendlyName": "GitHub PR Comment",
"description": "Publish a comment on a GitHub pull request.",
"helpMarkDown": "",
"category": "Utility",
"author": "Microsoft",
"version": {
"Major": 0,
"Minor": 1,
"Patch": 3
},
"instanceNameFormat": "GitHub Comment Publisher",
"inputs": [
{
"name": "userToken",
"type": "string",
"label": "User Token",
"defaultValue": "",
"required": true,
"helpMarkDown": "The user token to initiate the connection"
},
{
"name": "repository",
"type": "string",
"label": "Repository",
"defaultValue": "$(Build.Repository.Name)",
"required": true,
"helpMarkDown": "The full name of the repository where you want to make the comment(owner/repository)"
},
{
"name": "prNumber",
"type": "string",
"label": "Pull Request Number",
"defaultValue": "$(System.PullRequest.PullRequestNumber)",
"required": true,
"helpMarkDown": "The pull request to make a comment on"
},
{
"name": "bodyFilePath",
"type": "filePath",
"label": "Path to the body file/s",
"defaultValue": "",
"required": true,
"helpMarkDown": "Path to the .json files"
},
{
"name": "extension",
"type": "string",
"label": "Files extension",
"defaultValue": "txt",
"required": true,
"helpMarkDown": "Enter the files extension. Eg: txt"
},
{
"name": "getSubFolders",
"type": "boolean",
"label": "Use sub-folders",
"defaultValue": "",
"required": true,
"helpMarkDown": "Get all the .json files including the ones in sub-folders"
}
],
"execution": {
"Node": {
"target": "index.js"
}
}
}
60 changes: 60 additions & 0 deletions tools/devops-tasks/GitHubPRComment/githubComment/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 39 additions & 0 deletions tools/devops-tasks/GitHubPRComment/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# GitHub PR Comment Task

This task has the functionality to receive plain text files and use the content to create a GitHub comment on a Pull Request.

## Configuration

### User Token

[GitHub Personal Access Token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line) (it must have *Repo* permissions).

### Repository

RepositoryOwner/Repository name. Use `$(Build.Repository.Name)` if you want to run on the build's repository.

### Pull Request Number

Number of the pull request you want to comment. Use `$(System.PullRequest.PullRequestNumber)` if you want to run on the build's PR.

### Path to the file/s

Path to the file/s that you want to get the PR comments from. If you specify a folder, it will pick all the files that have the specified extension inside that folder.

### Use sub-folders

Checking this option will enable to search for all the files of the specified extensions in all the folders and sub-folders contained in the previously selected path.

### Basic Example

We prepared a simple example using the task by creating a pull request from a branch containing a message example. When the PR is created, the Azure Pipelines build is triggered, and the GitHub PR Comment task picks up the plain text file from the PR branch and creates a message on the PR with its contents.

## Azure Pipelines Setup

![PipelineSettings1](./media/guide-01.png)

![PipelineSettings2](./media/guide-02.png)

![PipelineSettings3](./media/guide-03.png)

![PipelineResults](./media/guide-04.png)
56 changes: 56 additions & 0 deletions tools/devops-tasks/GitHubPRComment/vss-extension.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"manifestVersion": 1,
"id": "github-pr-comment",
"name": "GitHub PR Comment",
"version": "0.1.3",
"publisher": "Microsoft",
"targets": [
{
"id": "Microsoft.VisualStudio.Services"
}
],
"description": "Automatically creates a comment on a Pull Request",
"categories": [
"Azure Pipelines"
],
"icons": {
"default": "media/extension-icon.png"
},
"content": {
"details": {
"path": "readme.md"
}
},
"links": {
"repository": {
"uri": "https://github.com/microsoft/botframework-sdk/tree/main/tools/devops-tasks/ApiCompat"
},
"issues": {
"uri": "https://github.com/microsoft/botframework-sdk/issues"
}
},
"repository": {
"type": "git",
"uri": "https://github.com/microsoft/botframework-sdk/tree/main/tools/devops-tasks/ApiCompat"
},
"files": [
{
"path": "githubComment"
}
],
"contributions": [
{
"id": "custom-publish-comment-task",
"type": "ms.vss-distributed-task.task",
"targets": [
"ms.vss-distributed-task.tasks"
],
"properties": {
"name": "githubComment"
}
}
],
"galleryFlags": [
"Public"
]
}