πŸ›β™»οΈ paging support & use graphql (#471)

* πŸ›β™»οΈ paging support & use graphql

* πŸš€ build

* 🚨 ignore eslint
This commit is contained in:
marocchino 2021-10-20 22:19:58 +09:00 committed by GitHub
parent 1bffac7054
commit 1a8e0448ba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 490 additions and 114 deletions

View file

@ -1 +1 @@
nodejs 14.15.4 nodejs 14.17.0

View file

@ -25,41 +25,63 @@ it("findPreviousComment", async () => {
login: "some-user" login: "some-user"
} }
const comment = { const comment = {
user: authenticatedUser, id: "1",
author: authenticatedUser,
isMinimized: false,
body: "previous message\n<!-- Sticky Pull Request Comment -->" body: "previous message\n<!-- Sticky Pull Request Comment -->"
} }
const commentWithCustomHeader = { const commentWithCustomHeader = {
user: authenticatedUser, id: "2",
author: authenticatedUser,
isMinimized: false,
body: "previous message\n<!-- Sticky Pull Request CommentTypeA -->" body: "previous message\n<!-- Sticky Pull Request CommentTypeA -->"
} }
const headerFirstComment = { const headerFirstComment = {
user: authenticatedUser, id: "3",
author: authenticatedUser,
isMinimized: false,
body: "<!-- Sticky Pull Request CommentLegacyComment -->\nheader first message" body: "<!-- Sticky Pull Request CommentLegacyComment -->\nheader first message"
} }
const otherUserComment = { const otherUserComment = {
user: otherUser, id: "4",
author: otherUser,
isMinimized: false,
body: "Fake previous message\n<!-- Sticky Pull Request Comment -->" body: "Fake previous message\n<!-- Sticky Pull Request Comment -->"
} }
const otherComments = [ const otherComments = [
{ {
user: otherUser, id: "5",
author: otherUser,
isMinimized: false,
body: "lgtm" body: "lgtm"
}, },
{ {
user: authenticatedUser, id: "6",
author: authenticatedUser,
isMinimized: false,
body: "previous message\n<!-- Sticky Pull Request CommentTypeB -->" body: "previous message\n<!-- Sticky Pull Request CommentTypeB -->"
} }
] ]
const octokit = getOctokit("github-token") const octokit = getOctokit("github-token")
jest.spyOn(octokit, "graphql").mockResolvedValue({viewer: authenticatedUser}) jest.spyOn(octokit, "graphql").mockResolvedValue({
jest.spyOn(octokit.rest.issues, "listComments").mockResolvedValue({ viewer: authenticatedUser,
data: [ repository: {
commentWithCustomHeader, pullRequest: {
otherUserComment, comments: {
comment, nodes: [
headerFirstComment, commentWithCustomHeader,
...otherComments otherUserComment,
] comment,
headerFirstComment,
...otherComments
],
pageInfo: {
hasNextPage: false,
endCursor: "6"
}
}
}
}
} as any) } as any)
expect(await findPreviousComment(octokit, repo, 123, "")).toBe(comment) expect(await findPreviousComment(octokit, repo, 123, "")).toBe(comment)
@ -69,10 +91,11 @@ it("findPreviousComment", async () => {
expect(await findPreviousComment(octokit, repo, 123, "LegacyComment")).toBe( expect(await findPreviousComment(octokit, repo, 123, "LegacyComment")).toBe(
headerFirstComment headerFirstComment
) )
expect(octokit.rest.issues.listComments).toBeCalledWith({ expect(octokit.graphql).toBeCalledWith(expect.any(String), {
after: null,
number: 123,
owner: "marocchino", owner: "marocchino",
repo: "sticky-pull-request-comment", repo: "sticky-pull-request-comment"
issue_number: 123
}) })
}) })
@ -80,51 +103,48 @@ describe("updateComment", () => {
const octokit = getOctokit("github-token") const octokit = getOctokit("github-token")
beforeEach(() => { beforeEach(() => {
jest jest.spyOn<any, string>(octokit, "graphql").mockResolvedValue("")
.spyOn<any, string>(octokit.rest.issues, "updateComment")
.mockResolvedValue("")
}) })
it("with comment body", async () => { it("with comment body", async () => {
expect( expect(
await updateComment(octokit, repo, 456, "hello there", "") await updateComment(octokit, "456", "hello there", "")
).toBeUndefined() ).toBeUndefined()
expect(octokit.rest.issues.updateComment).toBeCalledWith({ expect(octokit.graphql).toBeCalledWith(expect.any(String), {
comment_id: 456, input: {
owner: "marocchino", id: "456",
repo: "sticky-pull-request-comment", body: "hello there\n<!-- Sticky Pull Request Comment -->"
body: "hello there\n<!-- Sticky Pull Request Comment -->" }
}) })
expect( expect(
await updateComment(octokit, repo, 456, "hello there", "TypeA") await updateComment(octokit, "456", "hello there", "TypeA")
).toBeUndefined() ).toBeUndefined()
expect(octokit.rest.issues.updateComment).toBeCalledWith({ expect(octokit.graphql).toBeCalledWith(expect.any(String), {
comment_id: 456, input: {
owner: "marocchino", id: "456",
repo: "sticky-pull-request-comment", body: "hello there\n<!-- Sticky Pull Request CommentTypeA -->"
body: "hello there\n<!-- Sticky Pull Request CommentTypeA -->" }
}) })
expect( expect(
await updateComment( await updateComment(
octokit, octokit,
repo, "456",
456,
"hello there", "hello there",
"TypeA", "TypeA",
"hello there\n<!-- Sticky Pull Request CommentTypeA -->" "hello there\n<!-- Sticky Pull Request CommentTypeA -->"
) )
).toBeUndefined() ).toBeUndefined()
expect(octokit.rest.issues.updateComment).toBeCalledWith({ expect(octokit.graphql).toBeCalledWith(expect.any(String), {
comment_id: 456, input: {
owner: "marocchino", id: "456",
repo: "sticky-pull-request-comment", body: "hello there\n<!-- Sticky Pull Request CommentTypeA -->\nhello there"
body: "hello there\n<!-- Sticky Pull Request CommentTypeA -->\nhello there" }
}) })
}) })
it("without comment body and previous body", async () => { it("without comment body and previous body", async () => {
expect(await updateComment(octokit, repo, 456, "", "")).toBeUndefined() expect(await updateComment(octokit, "456", "", "")).toBeUndefined()
expect(octokit.rest.issues.updateComment).not.toBeCalled() expect(octokit.graphql).not.toBeCalled()
expect(core.warning).toBeCalledWith("Comment body cannot be blank") expect(core.warning).toBeCalledWith("Comment body cannot be blank")
}) })
}) })
@ -168,14 +188,10 @@ describe("createComment", () => {
it("deleteComment", async () => { it("deleteComment", async () => {
const octokit = getOctokit("github-token") const octokit = getOctokit("github-token")
jest jest.spyOn(octokit, "graphql").mockReturnValue(undefined as any)
.spyOn(octokit.rest.issues, "deleteComment") expect(await deleteComment(octokit, "456")).toBeUndefined()
.mockReturnValue(undefined as any) expect(octokit.graphql).toBeCalledWith(expect.any(String), {
expect(await deleteComment(octokit, repo, 456)).toBeUndefined() id: "456"
expect(octokit.rest.issues.deleteComment).toBeCalledWith({
comment_id: 456,
owner: "marocchino",
repo: "sticky-pull-request-comment"
}) })
}) })

248
dist/index.js generated vendored
View file

@ -40,22 +40,78 @@ const core = __importStar(__nccwpck_require__(186));
function headerComment(header) { function headerComment(header) {
return `<!-- Sticky Pull Request Comment${header} -->`; return `<!-- Sticky Pull Request Comment${header} -->`;
} }
function findPreviousComment(octokit, repo, issue_number, header) { function findPreviousComment(octokit, repo, number, header) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const { viewer } = yield octokit.graphql("query { viewer { login } }"); let after = null;
const { data: comments } = yield octokit.rest.issues.listComments(Object.assign(Object.assign({}, repo), { issue_number })); let hasNextPage = true;
const h = headerComment(header); const h = headerComment(header);
return comments.find(comment => { var _a, _b; return ((_a = comment.user) === null || _a === void 0 ? void 0 : _a.login) === viewer.login && ((_b = comment.body) === null || _b === void 0 ? void 0 : _b.includes(h)); }); while (hasNextPage) {
const data = yield octokit.graphql(`
query($repo: String! $owner: String! $number: Int! $after: String) {
viewer { login }
repository(name: $repo owner: $owner) {
pullRequest(number: $number) {
comments(first: 100 after: $after) {
nodes {
id
author {
login
}
isMinimized
body
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
}
`, Object.assign(Object.assign({}, repo), { after, number }));
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const viewer = data.viewer;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const repository = data.repository;
const target = (_c = (_b = (_a = repository.pullRequest) === null || _a === void 0 ? void 0 : _a.comments) === null || _b === void 0 ? void 0 : _b.nodes) === null || _c === void 0 ? void 0 : _c.find((node) => {
var _a, _b;
return ((_a = node === null || node === void 0 ? void 0 : node.author) === null || _a === void 0 ? void 0 : _a.login) === viewer.login &&
!(node === null || node === void 0 ? void 0 : node.isMinimized) &&
((_b = node === null || node === void 0 ? void 0 : node.body) === null || _b === void 0 ? void 0 : _b.includes(h));
});
if (target) {
return target;
}
after = (_f = (_e = (_d = repository.pullRequest) === null || _d === void 0 ? void 0 : _d.comments) === null || _e === void 0 ? void 0 : _e.pageInfo) === null || _f === void 0 ? void 0 : _f.endCursor;
hasNextPage =
(_k = (_j = (_h = (_g = repository.pullRequest) === null || _g === void 0 ? void 0 : _g.comments) === null || _h === void 0 ? void 0 : _h.pageInfo) === null || _j === void 0 ? void 0 : _j.hasNextPage) !== null && _k !== void 0 ? _k : false;
}
return undefined;
}); });
} }
exports.findPreviousComment = findPreviousComment; exports.findPreviousComment = findPreviousComment;
function updateComment(octokit, repo, comment_id, body, header, previousBody) { function updateComment(octokit, id, body, header, previousBody) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (!body && !previousBody) if (!body && !previousBody)
return core.warning("Comment body cannot be blank"); return core.warning("Comment body cannot be blank");
yield octokit.rest.issues.updateComment(Object.assign(Object.assign({}, repo), { comment_id, body: previousBody yield octokit.graphql(`
? `${previousBody}\n${body}` mutation($input: UpdateIssueCommentInput!) {
: `${body}\n${headerComment(header)}` })); updateIssueComment(input: $input) {
issueComment {
id
body
}
}
}
`, {
input: {
id,
body: previousBody
? `${previousBody}\n${body}`
: `${body}\n${headerComment(header)}`
}
});
}); });
} }
exports.updateComment = updateComment; exports.updateComment = updateComment;
@ -69,9 +125,15 @@ function createComment(octokit, repo, issue_number, body, header, previousBody)
}); });
} }
exports.createComment = createComment; exports.createComment = createComment;
function deleteComment(octokit, repo, comment_id) { function deleteComment(octokit, id) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
yield octokit.rest.issues.deleteComment(Object.assign(Object.assign({}, repo), { comment_id })); yield octokit.graphql(`
mutation($id: ID!) {
deleteIssueComment(input: { id: $id }) {
clientMutationId
}
}
`, { id });
}); });
} }
exports.deleteComment = deleteComment; exports.deleteComment = deleteComment;
@ -217,16 +279,16 @@ function run() {
return; return;
} }
if (config_1.deleteOldComment) { if (config_1.deleteOldComment) {
yield (0, comment_1.deleteComment)(octokit, config_1.repo, previous.id); yield (0, comment_1.deleteComment)(octokit, previous.id);
return; return;
} }
const previousBody = (0, comment_1.getBodyOf)(previous, config_1.append, config_1.hideDetails); const previousBody = (0, comment_1.getBodyOf)(previous, config_1.append, config_1.hideDetails);
if (config_1.recreate) { if (config_1.recreate) {
yield (0, comment_1.deleteComment)(octokit, config_1.repo, previous.id); yield (0, comment_1.deleteComment)(octokit, previous.id);
yield (0, comment_1.createComment)(octokit, config_1.repo, config_1.pullRequestNumber, config_1.body, config_1.header, previousBody); yield (0, comment_1.createComment)(octokit, config_1.repo, config_1.pullRequestNumber, config_1.body, config_1.header, previousBody);
return; return;
} }
yield (0, comment_1.updateComment)(octokit, config_1.repo, previous.id, config_1.body, config_1.header, previousBody); yield (0, comment_1.updateComment)(octokit, previous.id, config_1.body, config_1.header, previousBody);
} }
catch (error) { catch (error) {
if (error instanceof Error) { if (error instanceof Error) {
@ -373,12 +435,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}); });
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
const command_1 = __nccwpck_require__(351); const command_1 = __nccwpck_require__(351);
const file_command_1 = __nccwpck_require__(717); const file_command_1 = __nccwpck_require__(717);
const utils_1 = __nccwpck_require__(278); const utils_1 = __nccwpck_require__(278);
const os = __importStar(__nccwpck_require__(87)); const os = __importStar(__nccwpck_require__(87));
const path = __importStar(__nccwpck_require__(622)); const path = __importStar(__nccwpck_require__(622));
const oidc_utils_1 = __nccwpck_require__(41);
/** /**
* The code to exit an action * The code to exit an action
*/ */
@ -647,6 +710,12 @@ function getState(name) {
return process.env[`STATE_${name}`] || ''; return process.env[`STATE_${name}`] || '';
} }
exports.getState = getState; exports.getState = getState;
function getIDToken(aud) {
return __awaiter(this, void 0, void 0, function* () {
return yield oidc_utils_1.OidcClient.getIDToken(aud);
});
}
exports.getIDToken = getIDToken;
//# sourceMappingURL=core.js.map //# sourceMappingURL=core.js.map
/***/ }), /***/ }),
@ -700,6 +769,90 @@ exports.issueCommand = issueCommand;
/***/ }), /***/ }),
/***/ 41:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.OidcClient = void 0;
const http_client_1 = __nccwpck_require__(925);
const auth_1 = __nccwpck_require__(702);
const core_1 = __nccwpck_require__(186);
class OidcClient {
static createHttpClient(allowRetry = true, maxRetry = 10) {
const requestOptions = {
allowRetries: allowRetry,
maxRetries: maxRetry
};
return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);
}
static getRequestToken() {
const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
if (!token) {
throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
}
return token;
}
static getIDTokenUrl() {
const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
if (!runtimeUrl) {
throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
}
return runtimeUrl;
}
static getCall(id_token_url) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const httpclient = OidcClient.createHttpClient();
const res = yield httpclient
.getJson(id_token_url)
.catch(error => {
throw new Error(`Failed to get ID Token. \n
Error Code : ${error.statusCode}\n
Error Message: ${error.result.message}`);
});
const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
if (!id_token) {
throw new Error('Response json body do not have ID Token field');
}
return id_token;
});
}
static getIDToken(audience) {
return __awaiter(this, void 0, void 0, function* () {
try {
// New ID Token is requested from action service
let id_token_url = OidcClient.getIDTokenUrl();
if (audience) {
const encodedAudience = encodeURIComponent(audience);
id_token_url = `${id_token_url}&audience=${encodedAudience}`;
}
core_1.debug(`ID token url is ${id_token_url}`);
const id_token = yield OidcClient.getCall(id_token_url);
core_1.setSecret(id_token);
return id_token;
}
catch (error) {
throw new Error(`Error message: ${error.message}`);
}
});
}
}
exports.OidcClient = OidcClient;
//# sourceMappingURL=oidc-utils.js.map
/***/ }),
/***/ 278: /***/ 278:
/***/ ((__unused_webpack_module, exports) => { /***/ ((__unused_webpack_module, exports) => {
@ -735,6 +888,7 @@ function toCommandProperties(annotationProperties) {
} }
return { return {
title: annotationProperties.title, title: annotationProperties.title,
file: annotationProperties.file,
line: annotationProperties.startLine, line: annotationProperties.startLine,
endLine: annotationProperties.endLine, endLine: annotationProperties.endLine,
col: annotationProperties.startColumn, col: annotationProperties.startColumn,
@ -959,6 +1113,72 @@ function getOctokitOptions(token, options) {
exports.getOctokitOptions = getOctokitOptions; exports.getOctokitOptions = getOctokitOptions;
//# sourceMappingURL=utils.js.map //# sourceMappingURL=utils.js.map
/***/ }),
/***/ 702:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
class BasicCredentialHandler {
constructor(username, password) {
this.username = username;
this.password = password;
}
prepareRequest(options) {
options.headers['Authorization'] =
'Basic ' +
Buffer.from(this.username + ':' + this.password).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.BasicCredentialHandler = BasicCredentialHandler;
class BearerCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
options.headers['Authorization'] = 'Bearer ' + this.token;
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.BearerCredentialHandler = BearerCredentialHandler;
class PersonalAccessTokenCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
options.headers['Authorization'] =
'Basic ' + Buffer.from('PAT:' + this.token).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
/***/ }), /***/ }),
/***/ 925: /***/ 925:

2
dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

82
lib/comment.js generated
View file

@ -33,22 +33,78 @@ const core = __importStar(require("@actions/core"));
function headerComment(header) { function headerComment(header) {
return `<!-- Sticky Pull Request Comment${header} -->`; return `<!-- Sticky Pull Request Comment${header} -->`;
} }
function findPreviousComment(octokit, repo, issue_number, header) { function findPreviousComment(octokit, repo, number, header) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const { viewer } = yield octokit.graphql("query { viewer { login } }"); let after = null;
const { data: comments } = yield octokit.rest.issues.listComments(Object.assign(Object.assign({}, repo), { issue_number })); let hasNextPage = true;
const h = headerComment(header); const h = headerComment(header);
return comments.find(comment => { var _a, _b; return ((_a = comment.user) === null || _a === void 0 ? void 0 : _a.login) === viewer.login && ((_b = comment.body) === null || _b === void 0 ? void 0 : _b.includes(h)); }); while (hasNextPage) {
const data = yield octokit.graphql(`
query($repo: String! $owner: String! $number: Int! $after: String) {
viewer { login }
repository(name: $repo owner: $owner) {
pullRequest(number: $number) {
comments(first: 100 after: $after) {
nodes {
id
author {
login
}
isMinimized
body
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
}
`, Object.assign(Object.assign({}, repo), { after, number }));
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const viewer = data.viewer;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const repository = data.repository;
const target = (_c = (_b = (_a = repository.pullRequest) === null || _a === void 0 ? void 0 : _a.comments) === null || _b === void 0 ? void 0 : _b.nodes) === null || _c === void 0 ? void 0 : _c.find((node) => {
var _a, _b;
return ((_a = node === null || node === void 0 ? void 0 : node.author) === null || _a === void 0 ? void 0 : _a.login) === viewer.login &&
!(node === null || node === void 0 ? void 0 : node.isMinimized) &&
((_b = node === null || node === void 0 ? void 0 : node.body) === null || _b === void 0 ? void 0 : _b.includes(h));
});
if (target) {
return target;
}
after = (_f = (_e = (_d = repository.pullRequest) === null || _d === void 0 ? void 0 : _d.comments) === null || _e === void 0 ? void 0 : _e.pageInfo) === null || _f === void 0 ? void 0 : _f.endCursor;
hasNextPage =
(_k = (_j = (_h = (_g = repository.pullRequest) === null || _g === void 0 ? void 0 : _g.comments) === null || _h === void 0 ? void 0 : _h.pageInfo) === null || _j === void 0 ? void 0 : _j.hasNextPage) !== null && _k !== void 0 ? _k : false;
}
return undefined;
}); });
} }
exports.findPreviousComment = findPreviousComment; exports.findPreviousComment = findPreviousComment;
function updateComment(octokit, repo, comment_id, body, header, previousBody) { function updateComment(octokit, id, body, header, previousBody) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (!body && !previousBody) if (!body && !previousBody)
return core.warning("Comment body cannot be blank"); return core.warning("Comment body cannot be blank");
yield octokit.rest.issues.updateComment(Object.assign(Object.assign({}, repo), { comment_id, body: previousBody yield octokit.graphql(`
? `${previousBody}\n${body}` mutation($input: UpdateIssueCommentInput!) {
: `${body}\n${headerComment(header)}` })); updateIssueComment(input: $input) {
issueComment {
id
body
}
}
}
`, {
input: {
id,
body: previousBody
? `${previousBody}\n${body}`
: `${body}\n${headerComment(header)}`
}
});
}); });
} }
exports.updateComment = updateComment; exports.updateComment = updateComment;
@ -62,9 +118,15 @@ function createComment(octokit, repo, issue_number, body, header, previousBody)
}); });
} }
exports.createComment = createComment; exports.createComment = createComment;
function deleteComment(octokit, repo, comment_id) { function deleteComment(octokit, id) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
yield octokit.rest.issues.deleteComment(Object.assign(Object.assign({}, repo), { comment_id })); yield octokit.graphql(`
mutation($id: ID!) {
deleteIssueComment(input: { id: $id }) {
clientMutationId
}
}
`, { id });
}); });
} }
exports.deleteComment = deleteComment; exports.deleteComment = deleteComment;

6
lib/main.js generated
View file

@ -52,16 +52,16 @@ function run() {
return; return;
} }
if (config_1.deleteOldComment) { if (config_1.deleteOldComment) {
yield (0, comment_1.deleteComment)(octokit, config_1.repo, previous.id); yield (0, comment_1.deleteComment)(octokit, previous.id);
return; return;
} }
const previousBody = (0, comment_1.getBodyOf)(previous, config_1.append, config_1.hideDetails); const previousBody = (0, comment_1.getBodyOf)(previous, config_1.append, config_1.hideDetails);
if (config_1.recreate) { if (config_1.recreate) {
yield (0, comment_1.deleteComment)(octokit, config_1.repo, previous.id); yield (0, comment_1.deleteComment)(octokit, previous.id);
yield (0, comment_1.createComment)(octokit, config_1.repo, config_1.pullRequestNumber, config_1.body, config_1.header, previousBody); yield (0, comment_1.createComment)(octokit, config_1.repo, config_1.pullRequestNumber, config_1.body, config_1.header, previousBody);
return; return;
} }
yield (0, comment_1.updateComment)(octokit, config_1.repo, previous.id, config_1.body, config_1.header, previousBody); yield (0, comment_1.updateComment)(octokit, previous.id, config_1.body, config_1.header, previousBody);
} }
catch (error) { catch (error) {
if (error instanceof Error) { if (error instanceof Error) {

View file

@ -27,7 +27,8 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/core": "^1.6.0", "@actions/core": "^1.6.0",
"@actions/github": "^5.0.0" "@actions/github": "^5.0.0",
"@octokit/graphql-schema": "^10.73.0"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^27.0.2", "@types/jest": "^27.0.2",

View file

@ -1,4 +1,5 @@
import * as core from "@actions/core" import * as core from "@actions/core"
import {IssueComment, Repository, User} from "@octokit/graphql-schema"
import {GitHub} from "@actions/github/lib/utils" import {GitHub} from "@actions/github/lib/utils"
function headerComment(header: String): string { function headerComment(header: String): string {
@ -11,26 +12,62 @@ export async function findPreviousComment(
owner: string owner: string
repo: string repo: string
}, },
issue_number: number, number: number,
header: string header: string
): Promise<{body?: string; id: number} | undefined> { ): Promise<{body: string; id: string} | undefined> {
const {viewer} = await octokit.graphql("query { viewer { login } }") let after = null
const {data: comments} = await octokit.rest.issues.listComments({ let hasNextPage = true
...repo,
issue_number
})
const h = headerComment(header) const h = headerComment(header)
return comments.find( while (hasNextPage) {
comment => comment.user?.login === viewer.login && comment.body?.includes(h) const data = await octokit.graphql<{repository: Repository; viewer: User}>(
) `
query($repo: String! $owner: String! $number: Int! $after: String) {
viewer { login }
repository(name: $repo owner: $owner) {
pullRequest(number: $number) {
comments(first: 100 after: $after) {
nodes {
id
author {
login
}
isMinimized
body
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
}
`,
{...repo, after, number}
)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const viewer = data.viewer as User
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const repository = data.repository as Repository
const target = repository.pullRequest?.comments?.nodes?.find(
(node: IssueComment | null | undefined) =>
node?.author?.login === viewer.login &&
!node?.isMinimized &&
node?.body?.includes(h)
)
if (target) {
return target
}
after = repository.pullRequest?.comments?.pageInfo?.endCursor
hasNextPage =
repository.pullRequest?.comments?.pageInfo?.hasNextPage ?? false
}
return undefined
} }
export async function updateComment( export async function updateComment(
octokit: InstanceType<typeof GitHub>, octokit: InstanceType<typeof GitHub>,
repo: { id: string,
owner: string
repo: string
},
comment_id: number,
body: string, body: string,
header: string, header: string,
previousBody?: string previousBody?: string
@ -38,13 +75,26 @@ export async function updateComment(
if (!body && !previousBody) if (!body && !previousBody)
return core.warning("Comment body cannot be blank") return core.warning("Comment body cannot be blank")
await octokit.rest.issues.updateComment({ await octokit.graphql(
...repo, `
comment_id, mutation($input: UpdateIssueCommentInput!) {
body: previousBody updateIssueComment(input: $input) {
? `${previousBody}\n${body}` issueComment {
: `${body}\n${headerComment(header)}` id
}) body
}
}
}
`,
{
input: {
id,
body: previousBody
? `${previousBody}\n${body}`
: `${body}\n${headerComment(header)}`
}
}
)
} }
export async function createComment( export async function createComment(
octokit: InstanceType<typeof GitHub>, octokit: InstanceType<typeof GitHub>,
@ -70,16 +120,18 @@ export async function createComment(
} }
export async function deleteComment( export async function deleteComment(
octokit: InstanceType<typeof GitHub>, octokit: InstanceType<typeof GitHub>,
repo: { id: string
owner: string
repo: string
},
comment_id: number
): Promise<void> { ): Promise<void> {
await octokit.rest.issues.deleteComment({ await octokit.graphql(
...repo, `
comment_id mutation($id: ID!) {
}) deleteIssueComment(input: { id: $id }) {
clientMutationId
}
}
`,
{id}
)
} }
export function getBodyOf( export function getBodyOf(

View file

@ -48,13 +48,13 @@ async function run(): Promise<undefined> {
} }
if (deleteOldComment) { if (deleteOldComment) {
await deleteComment(octokit, repo, previous.id) await deleteComment(octokit, previous.id)
return return
} }
const previousBody = getBodyOf(previous, append, hideDetails) const previousBody = getBodyOf(previous, append, hideDetails)
if (recreate) { if (recreate) {
await deleteComment(octokit, repo, previous.id) await deleteComment(octokit, previous.id)
await createComment( await createComment(
octokit, octokit,
repo, repo,
@ -66,7 +66,7 @@ async function run(): Promise<undefined> {
return return
} }
await updateComment(octokit, repo, previous.id, body, header, previousBody) await updateComment(octokit, previous.id, body, header, previousBody)
} catch (error) { } catch (error) {
if (error instanceof Error) { if (error instanceof Error) {
core.setFailed(error.message) core.setFailed(error.message)

View file

@ -597,6 +597,14 @@
is-plain-object "^5.0.0" is-plain-object "^5.0.0"
universal-user-agent "^6.0.0" universal-user-agent "^6.0.0"
"@octokit/graphql-schema@^10.73.0":
version "10.73.0"
resolved "https://registry.yarnpkg.com/@octokit/graphql-schema/-/graphql-schema-10.73.0.tgz#d1dadc7ea854f01b16ee9a5bdc4715b9ab5a8f9c"
integrity sha512-0pHfbnl3n+b5mtTwP6nmMYlMwLgUvGZjndKVqPS2uyR1Vh8WGMldVW4sFXxDxOPY8RyznLGg44m8sDQT+vAbnw==
dependencies:
graphql "^15.0.0"
graphql-tag "^2.10.3"
"@octokit/graphql@^4.5.8": "@octokit/graphql@^4.5.8":
version "4.8.0" version "4.8.0"
resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3"
@ -1992,6 +2000,18 @@ graceful-fs@^4.2.4:
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.8.tgz#e412b8d33f5e006593cbd3cee6df9f2cebbe802a" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.8.tgz#e412b8d33f5e006593cbd3cee6df9f2cebbe802a"
integrity sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg== integrity sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==
graphql-tag@^2.10.3:
version "2.12.5"
resolved "https://registry.yarnpkg.com/graphql-tag/-/graphql-tag-2.12.5.tgz#5cff974a67b417747d05c8d9f5f3cb4495d0db8f"
integrity sha512-5xNhP4063d16Pz3HBtKprutsPrmHZi5IdUGOWRxA2B6VF7BIRGOHZ5WQvDmJXZuPcBg7rYwaFxvQYjqkSdR3TQ==
dependencies:
tslib "^2.1.0"
graphql@^15.0.0:
version "15.6.1"
resolved "https://registry.yarnpkg.com/graphql/-/graphql-15.6.1.tgz#9125bdf057553525da251e19e96dab3d3855ddfc"
integrity sha512-3i5lu0z6dRvJ48QP9kFxBkJ7h4Kso7PS8eahyTFz5Jm6CvQfLtNIE8LX9N6JLnXTuwR+sIYnXzaWp6anOg0QQw==
has-bigints@^1.0.1: has-bigints@^1.0.1:
version "1.0.1" version "1.0.1"
resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.0.1.tgz#64fe6acb020673e3b78db035a5af69aa9d07b113" resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.0.1.tgz#64fe6acb020673e3b78db035a5af69aa9d07b113"
@ -3639,6 +3659,11 @@ tslib@^1.8.1:
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
tslib@^2.1.0:
version "2.3.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01"
integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==
tsutils@^3.21.0: tsutils@^3.21.0:
version "3.21.0" version "3.21.0"
resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.21.0.tgz#b48717d394cea6c1e096983eed58e9d61715b623" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.21.0.tgz#b48717d394cea6c1e096983eed58e9d61715b623"