Skip to content

Commit

Permalink
Merge pull request #4 from Yleisradio/issue/3-prevent-adding-multiple…
Browse files Browse the repository at this point in the history
…-cardlinks

Prevent repeated link-to-card comment adding in pull requests
  • Loading branch information
rpsu authored Oct 1, 2021
2 parents f88da35 + e24554b commit e002bab
Show file tree
Hide file tree
Showing 6 changed files with 247 additions and 41 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ Required env variables include:
Optional env variables include:

- `TRELLO_ACTION_VERBOSE` to make action logs slightly more verbose.
- `TRELLO_API_DEBUG` expose all API call resposes in action log.
- `GITHUB_API_DEBUG` expose API call data in action log.
- `TRELLO_API_DEBUG` expose Trello API call resposes in action log.
- `GITHUB_API_DEBUG` expose Github API call data in action log.

### Pull requests and Cards referring to PR or issue

Expand Down Expand Up @@ -105,8 +105,8 @@ Optional env variables include:

- `TRELLO_SOURCE_LIST_ID` The id of your Trello list (column) where you wish to limit searching the Card.
- `TRELLO_ACTION_VERBOSE` to make action logs slightly more verbose.
- `TRELLO_API_DEBUG` expose all API call resposes in action log.
- `GITHUB_API_DEBUG` expose API call data in action log.
- `TRELLO_API_DEBUG` expose Trello API call resposes in action log.
- `GITHUB_API_DEBUG` expose Github API call data in action log.

## API key and token

Expand All @@ -132,5 +132,5 @@ yarn install
yarn pre-release
git add .
git commit -m'Compiled new code'
git tag -a 'Tagging new release v1.0.2' v1.0.2
git tag -a 'Tagging new release v1.2.0' v1.2.0
```
105 changes: 91 additions & 14 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.addIssueComment = void 0;
exports.getAllIssueComments = exports.addIssueComment = void 0;
const github = __importStar(__nccwpck_require__(2165));
const debug = process.env.GITHUB_API_DEBUG || true;
const githubToken = process.env.GITHUB_TOKEN;
Expand Down Expand Up @@ -75,6 +75,30 @@ const addIssueComment = ({ comment, issueNumber, repoOwner, repoName, }) => __aw
return true;
});
exports.addIssueComment = addIssueComment;
/**
* REST endpint to get all Issue (or PR) comments.
*
* @see https://docs.github.com/en/rest/reference/issues#list-issue-comments-for-a-repository
*/
const getAllIssueComments = ({ issueNumber, repoOwner, repoName }) => __awaiter(void 0, void 0, void 0, function* () {
if (!octokit) {
console.error('Octokit is not defined.');
!githubToken && console.error('GITHUB_TOKEN is falsy.');
return [];
}
const ghIssueData = {
owner: repoOwner,
repo: repoName,
issue_number: issueNumber,
};
const issueComments = yield octokit.rest.issues.listComments(ghIssueData);
if (debug) {
console.log(`getAllIssueComments with issue ${issueNumber}: `);
console.log(JSON.stringify(issueComments, null, 2));
}
return issueComments.data || [];
});
exports.getAllIssueComments = getAllIssueComments;
//# sourceMappingURL=api-github.js.map

/***/ }),
Expand Down Expand Up @@ -390,6 +414,17 @@ var __importStar = (this && this.__importStar) || function (mod) {
__setModuleDefault(result, mod);
return result;
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const core = __importStar(__nccwpck_require__(3020));
const github = __importStar(__nccwpck_require__(2165));
Expand Down Expand Up @@ -589,23 +624,32 @@ function pullRequestEventMoveCard() {
repoOwner: repository.owner,
repoName: repository.repo,
};
(0, api_github_1.addIssueComment)(commentData)
.then((success) => {
if (success) {
verbose &&
console.log(`Link to the Trello Card added to the PR: ${card.shortUrl}`);
}
else {
// Spread and desctruction of an object property.
const { comment } = commentData, issueLocator = __rest(commentData, ["comment"]);
if (!(0, utils_1.isIssueAlreadyLinkedTo)(card.shortUrl, issueLocator)) {
(0, api_github_1.addIssueComment)(commentData)
.then((success) => {
if (success) {
verbose &&
console.log(`Link to the Trello Card added to the PR: ${card.shortUrl}`);
}
else {
console.error(`Non-fatal error: Failed to add link to the Trello card.`);
}
})
.catch(() => {
console.error(`Non-fatal error: Failed to add link to the Trello card.`);
});
}
else {
if (verbose) {
console.log(`Link to the Trello Card was found in the comments, so adding it was skipped.`);
}
})
.catch(() => {
console.error(`Non-fatal error: Failed to add link to the Trello card.`);
});
}
})
.catch((error) => {
console.error(error);
core.setFailed('Something went wrong when querying Cards to be moved.');
core.setFailed('Something went wrong when updating Cards to be moved to some new column.');
return [];
});
});
Expand Down Expand Up @@ -640,9 +684,11 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.cardHasPrLinked = exports.boardId = exports.validateListExistsOnBoard = exports.validateIdPattern = void 0;
exports.isIssueAlreadyLinkedTo = exports.cardHasPrLinked = exports.boardId = exports.validateListExistsOnBoard = exports.validateIdPattern = void 0;
const core = __importStar(__nccwpck_require__(3020));
const api_github_1 = __nccwpck_require__(5518);
const api_trello_1 = __nccwpck_require__(6445);
const debug = process.env.GITHUB_API_DEBUG || true;
const verbose = process.env.TRELLO_ACTION_VERBOSE || false;
/**
* Validate Trello entity id.
Expand Down Expand Up @@ -707,6 +753,37 @@ const cardHasPrLinked = (card, repoHtmlUrl) => {
});
};
exports.cardHasPrLinked = cardHasPrLinked;
const isIssueAlreadyLinkedTo = (findme, { issueNumber, repoOwner, repoName }) => {
return (0, api_github_1.getAllIssueComments)({ issueNumber: issueNumber, repoOwner: repoOwner, repoName: repoName })
.then((comments) => {
// comments is array of individual comments here.
if (!comments) {
if (debug) {
console.log('getAllIssueComments() returned a falsy dataset: ', JSON.stringify(comments, null, 2));
}
return false;
}
else if (!comments.length) {
if (debug) {
console.log('getAllIssueComments() returned a empty array');
}
return false;
}
if (debug) {
console.log('getAllIssueComments() returned data: ', JSON.stringify(comments, null, 2));
}
const isLinked = comments.some((comment) => comment.body && comment.body.match(findme));
if (verbose) {
console.log(`String "${findme}" found in issue ${repoOwner}/${repoName}/${issueNumber} comments? ${isLinked ? 'yes' : 'no'}`);
}
return isLinked;
})
.catch((error) => {
console.error('Error locating the provided string in issue/pr comments: ' +
JSON.stringify(error, null, 2));
});
};
exports.isIssueAlreadyLinkedTo = isIssueAlreadyLinkedTo;
//# sourceMappingURL=utils.js.map

/***/ }),
Expand Down
31 changes: 29 additions & 2 deletions src/api-github.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as github from '@actions/github';
import { ghIssueCommentData, ghPullRequestCommentData } from './types';
import { ghIssueCommentData, ghIssueData } from './types';

const debug: string | boolean = process.env.GITHUB_API_DEBUG || true;
const githubToken: string | undefined = process.env.GITHUB_TOKEN;
Expand Down Expand Up @@ -50,4 +50,31 @@ const addIssueComment = async ({
return true;
};

export { addIssueComment };
/**
* REST endpint to get all Issue (or PR) comments.
*
* @see https://docs.github.com/en/rest/reference/issues#list-issue-comments-for-a-repository
*/
const getAllIssueComments = async ({ issueNumber, repoOwner, repoName }: ghIssueData) => {
if (!octokit) {
console.error('Octokit is not defined.');
!githubToken && console.error('GITHUB_TOKEN is falsy.');
return [];
}
const ghIssueData = {
owner: repoOwner,
repo: repoName,
issue_number: issueNumber,
};

const issueComments = await octokit.rest.issues.listComments(ghIssueData);

if (debug) {
console.log(`getAllIssueComments with issue ${issueNumber}: `);
console.log(JSON.stringify(issueComments, null, 2));
}

return issueComments.data || [];
};

export { addIssueComment, getAllIssueComments };
39 changes: 26 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
addAttachmentToCard,
} from './api-trello';
import { TrelloCard, TrelloCardRequestParams } from './types';
import { cardHasPrLinked, validateListExistsOnBoard } from './utils';
import { cardHasPrLinked, isIssueAlreadyLinkedTo, validateListExistsOnBoard } from './utils';

const verbose: string | boolean = process.env.TRELLO_ACTION_VERBOSE || false;
const action = core.getInput('action');
Expand Down Expand Up @@ -237,22 +237,35 @@ function pullRequestEventMoveCard() {
repoName: repository.repo,
};

addIssueComment(commentData)
.then((success) => {
if (success) {
verbose &&
console.log(`Link to the Trello Card added to the PR: ${card.shortUrl}`);
} else {
// Spread and desctruction of an object property.
const { comment, ...issueLocator } = commentData;

if (!isIssueAlreadyLinkedTo(card.shortUrl, issueLocator)) {
addIssueComment(commentData)
.then((success) => {
if (success) {
verbose &&
console.log(`Link to the Trello Card added to the PR: ${card.shortUrl}`);
} else {
console.error(`Non-fatal error: Failed to add link to the Trello card.`);
}
})
.catch(() => {
console.error(`Non-fatal error: Failed to add link to the Trello card.`);
}
})
.catch(() => {
console.error(`Non-fatal error: Failed to add link to the Trello card.`);
});
});
} else {
if (verbose) {
console.log(
`Link to the Trello Card was found in the comments, so adding it was skipped.`,
);
}
}
})
.catch((error) => {
console.error(error);
core.setFailed('Something went wrong when querying Cards to be moved.');
core.setFailed(
'Something went wrong when updating Cards to be moved to some new column.',
);
return [];
});
});
Expand Down
45 changes: 40 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,16 +119,50 @@ interface TrelloCardRequestParams {
destinationListId?: string;
}

interface ghCommentData {
comment: string;
interface ghBaseData {
repoOwner: string;
repoName: string;
}
interface ghCommentData extends ghBaseData {
comment: string;
}
interface ghIssueData extends ghBaseData {
issueNumber: number;
}
interface ghIssueCommentData extends ghCommentData {
issueNumber: number;
}
interface ghPullRequestCommentData extends ghCommentData {
pullNumber: number;

interface ghResponseIssueComment {
id: number;
node_id: string;
url: string;
html_url: string;
body: string;
user: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
};
created_at: string;
updated_at: string;
issue_url: string;
author_association: string;
}

export {
Expand All @@ -139,5 +173,6 @@ export {
TrelloAttachment,
TrelloCardRequestParams,
ghIssueCommentData,
ghPullRequestCommentData,
ghIssueData,
ghResponseIssueComment,
};
Loading

0 comments on commit e002bab

Please sign in to comment.