Skip to content
This repository has been archived by the owner on Sep 19, 2024. It is now read-only.

refactor: replace axios with native fetch for GitHub requests #936

Open
wants to merge 1 commit into
base: development
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
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
"@vercel/ncc": "^0.34.0",
"ajv": "^8.12.0",
"ajv-formats": "^2.1.1",
"axios": "^1.3.2",
"cspell": "^7.0.0",
"decimal.js": "^10.4.3",
"ethers": "^5.7.2",
Expand Down
36 changes: 19 additions & 17 deletions src/handlers/assign/check-pull-requests.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import axios from "axios";
import { HTMLElement, parse } from "node-html-parser";
import { getAllPullRequests, addAssignees } from "../../helpers/issue";
import { Context } from "../../types/context";

// Check for pull requests linked to their respective issues but not assigned to them
export async function checkPullRequests(context: Context) {
const { logger, payload } = context;
const pulls = await getAllPullRequests(context);
Expand All @@ -12,36 +10,30 @@ export async function checkPullRequests(context: Context) {
return logger.debug(`No pull requests found at this time`);
}

// Loop through the pull requests and assign them to their respective issues if needed
for (const pull of pulls) {
const linkedIssue = await getLinkedIssues({
owner: payload.repository.owner.login,
repository: payload.repository.name,
pull: pull.number,
});

// if pullRequestLinked is empty, continue
if (linkedIssue == null || !pull.user || !linkedIssue) {
continue;
}

const connectedPull = await getPullByNumber(context, pull.number);

// Newly created PULL (draft or direct) pull does have same `created_at` and `updated_at`.
if (connectedPull?.created_at !== connectedPull?.updated_at) {
logger.debug("It's an updated Pull Request, reverting");
continue;
}

const linkedIssueNumber = linkedIssue.substring(linkedIssue.lastIndexOf("/") + 1);

// Check if the pull request opener is assigned to the issue
const opener = pull.user.login;

const issue = await getIssueByNumber(context, +linkedIssueNumber);
if (!issue?.assignees) continue;

// if issue is already assigned, continue
if (issue.assignees.length > 0) {
logger.debug(`Issue already assigned, ignoring...`);
continue;
Expand All @@ -61,17 +53,26 @@ export async function checkPullRequests(context: Context) {
}

export async function getLinkedIssues({ owner, repository, pull }: GetLinkedParams) {
const { data } = await axios.get(`https://github.com/${owner}/${repository}/pull/${pull}`);
const dom = parse(data);
const devForm = dom.querySelector("[data-target='create-branch.developmentForm']") as HTMLElement;
const linkedIssues = devForm.querySelectorAll(".my-1");
try {
const response = await fetch(`https://github.com/${owner}/${repository}/pull/${pull}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.text();
const dom = parse(data);
const devForm = dom.querySelector("[data-target='create-branch.developmentForm']") as HTMLElement;
const linkedIssues = devForm.querySelectorAll(".my-1");

if (linkedIssues.length === 0) {
return null;
}

if (linkedIssues.length === 0) {
const issueUrl = linkedIssues[0].querySelector("a")?.attrs?.href || null;
return issueUrl;
} catch (error) {
console.error("Error fetching linked issues:", error);
return null;
}

const issueUrl = linkedIssues[0].querySelector("a")?.attrs?.href || null;
return issueUrl;
}

export async function getPullByNumber(context: Context, pull: number) {
Expand All @@ -89,7 +90,7 @@ export async function getPullByNumber(context: Context, pull: number) {
return;
}
}
// Get issues by issue number

export async function getIssueByNumber(context: Context, issueNumber: number) {
const payload = context.payload;
try {
Expand All @@ -104,6 +105,7 @@ export async function getIssueByNumber(context: Context, issueNumber: number) {
return;
}
}

export interface GetLinkedParams {
owner: string;
repository: string;
Expand Down
67 changes: 40 additions & 27 deletions src/helpers/get-linked-pull-requests.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,62 @@
import axios from "axios";
import { HTMLElement, parse } from "node-html-parser";
import { GetLinkedParams } from "../handlers/assign/check-pull-requests";
import { Context } from "../types/context";

interface GetLinkedResults {
organization: string;
repository: string;
number: number;
href: string;
}

export async function getLinkedPullRequests(
context: Context,
{ owner, repository, issue }: GetLinkedParams
): Promise<GetLinkedResults[]> {
const logger = context.logger;
const collection = [] as GetLinkedResults[];
const { data } = await axios.get(`https://github.com/${owner}/${repository}/issues/${issue}`);
const dom = parse(data);
const devForm = dom.querySelector("[data-target='create-branch.developmentForm']") as HTMLElement;
const linkedList = devForm.querySelectorAll(".my-1");
if (linkedList.length === 0) {
context.logger.info(`No linked pull requests found`);
return [];
}
const collection: GetLinkedResults[] = [];

for (const linked of linkedList) {
const relativeHref = linked.querySelector("a")?.attrs?.href;
if (!relativeHref) continue;
const parts = relativeHref.split("/");
try {
const response = await fetch(`https://github.com/${owner}/${repository}/issues/${issue}`);

// check if array size is at least 4
if (parts.length < 4) continue;
if (!response.ok) {
throw new Error(`GitHub responded with status ${response.status}`);
}

const html = await response.text();
const dom = parse(html);

// extract the organization name and repo name from the link:(e.g. "
const organization = parts[parts.length - 4];
const repository = parts[parts.length - 3];
const number = Number(parts[parts.length - 1]);
const href = `https://github.com${relativeHref}`;
const devForm = dom.querySelector("[data-target='create-branch.developmentForm']") as HTMLElement;
const linkedList = devForm?.querySelectorAll(".my-1") || [];

if (`${organization}/${repository}` !== `${owner}/${repository}`) {
logger.info("Skipping linked pull request from another repository", href);
continue;
if (linkedList.length === 0) {
logger.info(`No linked pull requests found`);
return [];
}

collection.push({ organization, repository, number, href });
}
for (const linked of linkedList) {
const relativeHref = linked.querySelector("a")?.attrs?.href;
if (!relativeHref) continue;
const parts = relativeHref.split("/");

return collection;
if (parts.length < 4) continue;

const organization = parts[parts.length - 4];
const repo = parts[parts.length - 3];
const number = Number(parts[parts.length - 1]);
const href = `https://github.com${relativeHref}`;

if (`${organization}/${repo}` !== `${owner}/${repository}`) {
logger.info("Skipping linked pull request from another repository", href);
continue;
}

collection.push({ organization, repository: repo, number, href });
}

return collection;
} catch (error) {
logger.error("Error fetching linked pull requests:", error);
throw error;
}
}
Loading