Skip to content

Commit

Permalink
chore: update logs and test
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Jul 29, 2024
1 parent aafc15e commit ed2e2dd
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 32 deletions.
38 changes: 24 additions & 14 deletions src/handlers/shared/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function start(context: Context, issue: Context["payload"]["issue"]
logger.info(`Opened Pull Requests with approved reviews or with no reviews but over 24 hours have passed: `, { openedPullRequests });

const assignedIssues = await getAssignedIssues(context, sender.login);
logger.info("Max issue allowed is", { maxConcurrentTasks });
logger.info("Max issue allowed is", { maxConcurrentTasks, assignedIssues: assignedIssues?.map((issue) => `${issue.url}`) });

// check for max and enforce max

Expand All @@ -65,8 +65,12 @@ export async function start(context: Context, issue: Context["payload"]["issue"]

if (assignees.length !== 0) {
const isCurrentUserAssigned = !!assignees.find((assignee) => assignee?.login === sender.login);
const log = logger.error(isCurrentUserAssigned ? "You are already assigned to this task." : "The issue is already assigned. Please choose another unassigned task.", { issueNumber: issue.number });
return await addCommentToIssue(context, log?.logMessage.diff as string);
const log = logger.error(
isCurrentUserAssigned ? "You are already assigned to this task." : "This issue is already assigned. Please choose another unassigned task.",
{ issueNumber: issue.number }
);
await addCommentToIssue(context, log?.logMessage.diff as string);
throw new Error(log?.logMessage.diff);
}

teammates.push(sender.login);
Expand Down Expand Up @@ -94,19 +98,25 @@ export async function start(context: Context, issue: Context["payload"]["issue"]
duration,
priceLabel,
revision: commitHash?.substring(0, 7),
teammate: teammates,
teammates: teammates,
assignee: login,
issue: issue.number,
});

const assignmentComment = await generateAssignmentComment(context, issue.created_at, issue.number, id, duration);
const metadata = structuredMetadata.create("Assignment", logMessage);

// add assignee
if (!assignees.map((i: Partial<Assignee>) => i?.login).includes(login)) {
await addAssignees(context, issue.number, [login]);
const toAssign = [];

for (const teammate of teammates) {
if (!assignees.find((assignee: Partial<Assignee>) => assignee?.login?.toLowerCase() === teammate.toLowerCase())) {
toAssign.push(teammate);
}
}

// assign the issue
await addAssignees(context, issue.number, toAssign);

const isTaskStale = checkTaskStale(taskStaleTimeoutDuration, issue.created_at);

await addCommentToIssue(
Expand All @@ -128,16 +138,16 @@ export async function start(context: Context, issue: Context["payload"]["issue"]

async function handleTaskLimitChecks(username: string, context: Context, maxConcurrentTasks: number, logger: Context["logger"], sender: string) {
const openedPullRequests = await getAvailableOpenedPullRequests(context, username);
logger.info(`Opened Pull Requests with approved reviews or with no reviews but over 24 hours have passed: `, { openedPullRequests });

const assignedIssues = await getAssignedIssues(context, username);
logger.info("Max issue allowed is", { maxConcurrentTasks, assignedIssues: assignedIssues.map((issue) => `${issue.url}`) });

// check for max and enforce max
if (assignedIssues.length - openedPullRequests.length >= maxConcurrentTasks) {
const isSender = username === sender;
const comment = (isSender ? "You have" : `${username} has`) + ` reached the max limit of ${maxConcurrentTasks} assigned issues.`;
await addCommentToIssue(context, `\`\`\`diff\n! ${comment}\n\`\`\``);
throw new Error(`Too many assigned issues, you have reached your max limit of ${maxConcurrentTasks} issues.`);
const log = logger.error(username === sender ? "You have reached your max task limit" : `${username} has reached their max task limit`, {
assignedIssues: assignedIssues.length,
openedPullRequests: openedPullRequests.length,
maxConcurrentTasks,
});
await addCommentToIssue(context, log?.logMessage.diff as string);
throw new Error(log?.logMessage.diff);
}
}
5 changes: 4 additions & 1 deletion src/handlers/user-start-stop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ export async function userStartStop(context: Context): Promise<{ output: string
const { payload } = context;
const { issue, comment, sender, repository } = payload;
const slashCommand = comment.body.split(" ")[0].replace("/", "");
const teamMates = comment.body.split("@").slice(1).map((teamMate) => teamMate.split(" ")[0]);
const teamMates = comment.body
.split("@")
.slice(1)
.map((teamMate) => teamMate.split(" ")[0]);

if (slashCommand === "stop") {
return await stop(context, issue, sender, repository);
Expand Down
3 changes: 1 addition & 2 deletions src/utils/get-linked-prs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,5 @@ export async function getLinkedPullRequests(context: Context, { owner, repositor
state: pr.state,
body: pr.body,
};
})
.filter((pr) => pr !== null && pr.state === "open") as GetLinkedResults[];
}).filter((pr) => pr !== null && pr.state === "open") as GetLinkedResults[];
}
7 changes: 6 additions & 1 deletion tests/__mocks__/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const handlers = [
db.issue.update({
where: { id: { equals: issue.id } },
data: {
assignees,
assignees: [...issue.assignees, ...assignees],
},
});
}
Expand All @@ -107,4 +107,9 @@ export const handlers = [
http.delete("https://api.github.com/repos/:owner/:repo/issues/:issue_number/assignees", ({ params: { owner, repo, issue_number: issueNumber } }) =>
HttpResponse.json({ owner, repo, issueNumber })
),
// search issues
http.get("https://api.github.com/search/issues", () => {
const issues = [db.issue.findFirst({ where: { number: { equals: 1 } } })];
return HttpResponse.json({ items: issues });
}),
];
25 changes: 11 additions & 14 deletions tests/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ describe("User start/stop", () => {
expect(output).toEqual("Task assigned successfully");

const issue2 = db.issue.findFirst({ where: { id: { equals: 1 } } }) as unknown as Issue;

expect(issue2.assignees).toHaveLength(2);

expect(issue2.assignees).toEqual(expect.arrayContaining(["ubiquity", "user2"]));
});

Expand All @@ -85,7 +83,7 @@ describe("User start/stop", () => {
});

test("Stopping an issue should close the author's linked PR", async () => {
const infoSpy = jest.spyOn(console, "info").mockImplementation(() => { });
const infoSpy = jest.spyOn(console, "info").mockImplementation(() => {});
const issue = db.issue.findFirst({ where: { id: { equals: 2 } } }) as unknown as Issue;
const sender = db.users.findFirst({ where: { id: { equals: 2 } } }) as unknown as Sender;
const context = createContext(issue, sender, "/stop");
Expand Down Expand Up @@ -138,7 +136,7 @@ describe("User start/stop", () => {

context.adapters = createAdapters(getSupabase(), context as unknown as Context);

const err = "The issue is already assigned. Please choose another unassigned task.";
const err = "```diff\n! This issue is already assigned. Please choose another unassigned task.\n```";

try {
await userStartStop(context as unknown as Context);
Expand Down Expand Up @@ -472,7 +470,6 @@ async function setupTests() {
state: "open",
body: `Resolves #2`,
html_url: "https://github.com/ubiquity/test-repo/pull/10",
state: "open",
repository: {
full_name: TEST_REPO,
},
Expand Down Expand Up @@ -585,17 +582,17 @@ function getSupabase(withData = true) {
single: jest.fn().mockResolvedValue({
data: withData
? {
id: 1,
wallets: {
address: "0x123",
},
}
id: 1,
wallets: {
address: "0x123",
},
}
: {
id: 1,
wallets: {
address: undefined,
id: 1,
wallets: {
address: undefined,
},
},
},
}),
}),
}),
Expand Down

0 comments on commit ed2e2dd

Please sign in to comment.