Skip to content
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

fix: pull-request state adjustments #61

Merged
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion .github/knip.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { KnipConfig } from "knip";

const config: KnipConfig = {
entry: ["src/index.ts"],
entry: ["src/index.ts", "src/worker.ts"],
project: ["src/**/*.ts"],
ignore: ["**/__mocks__/**", "**/__fixtures__/**", "src/types/database.ts", "dist/**"],
ignoreExportsUsedInFile: true,
Expand Down
2 changes: 1 addition & 1 deletion .husky/commit-msg
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

yarn commitlint --edit "$1"
bun commitlint --edit "$1"
2 changes: 1 addition & 1 deletion .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

yarn lint-staged
bun lint-staged
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ tasks don't stall, and subtracts XP.
## Setup

```shell
yarn install
bun install
```

### Database
Expand All @@ -20,22 +20,21 @@ supabase start
Afterward, you can generate types for full auto-completion with

```shell
yarn supabase:generate:local
bun run supabase:generate:local
```

### Test

To start Jest testing, run

```shell
yarn test
bun run test
```

## Valid configuration

```yaml
- plugin: ubiquibot/user-activity-watcher
type: github
- plugin: ubiquity-os/daemon-disqualifier
with:
disqualification: "7 days"
warning: "3.5 days"
Expand All @@ -44,7 +43,7 @@ yarn test
optOut:
- "repoName"
- "repoName2"
eventWhitelist: # these are the tail of the webhook event i.e pull_request.review_requested
eventWhitelist: # these are the tail of the webhook event i.e. pull_request.review_requested
- "review_requested"
- "ready_for_review"
- "commented"
Expand Down
Binary file modified bun.lockb
Binary file not shown.
2 changes: 1 addition & 1 deletion dist/index.js

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"properties": {
"warning": {
"default": "3.5 days",
"description": "Delay to send reminders. 0 means disabled and any other value is counted in days, e.g. 1,5 days",
"examples": ["3.5 days", "1 day"],
"type": "string"
},
"watch": {
Expand All @@ -16,6 +18,8 @@
"properties": {
"optOut": {
"default": [],
"description": "List of repositories to opt-out from watching user activity within the organization",
"examples": ["repoName", "no-owner-required"],
"type": "array",
"items": {
"type": "string"
Expand All @@ -25,18 +29,24 @@
},
"prioritySpeed": {
"default": true,
"description": "Whether to rush the follow ups by the priority level",
"type": "boolean"
},
"disqualification": {
"default": "7 days",
"description": "Delay to unassign users. 0 means disabled and any other value is counted in days, e.g. 7 days",
"examples": ["7 days", "1 day"],
"type": "string"
},
"pullRequestRequired": {
"default": true,
"description": "Whether a pull request is required for the given issue on disqualify",
"type": "boolean"
},
"eventWhitelist": {
"default": ["pull_request.review_requested", "pull_request.ready_for_review", "pull_request_review_comment.created", "issue_comment.created", "push"],
"description": "List of webhook event names to consider as valid activity on a task",
"examples": ["pull_request.review_requested", "issue_comment.created", "push"],
"type": "array",
"items": {
"type": "string"
Expand Down
13 changes: 6 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"node": ">=20.10.0"
},
"scripts": {
"start": "tsx src/index.ts",
"prebuild": "dotenv -- cross-env yarn supabase:generate:remote",
"start": "bun --watch src/worker.ts",
"prebuild": "dotenv -- cross-env bun run supabase:generate:remote",
"format:lint": "eslint --fix .",
"format:prettier": "prettier --write .",
"format:cspell": "cspell **/*",
Expand All @@ -32,13 +32,12 @@
"dependencies": {
"@octokit/graphql-schema": "^15.25.0",
"@octokit/rest": "^21.0.2",
"@sinclair/typebox": "0.34.3",
"@ubiquity-os/plugin-sdk": "^1.1.0",
"@sinclair/typebox": "0.34.11",
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
"@ubiquity-os/plugin-sdk": "^1.1.1",
"@ubiquity-os/ubiquity-os-logger": "^1.3.2",
"dotenv": "16.4.5",
"luxon": "3.4.4",
"ms": "2.1.3",
"tsx": "4.11.2"
"ms": "2.1.3"
},
"devDependencies": {
"@commitlint/cli": "19.3.0",
Expand Down Expand Up @@ -78,7 +77,7 @@
},
"lint-staged": {
"*.ts": [
"yarn prettier --write",
"prettier --write",
"eslint --fix"
],
"src/**.{ts,json}": [
Expand Down
5 changes: 3 additions & 2 deletions src/helpers/collect-linked-pulls.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { PullRequest, User, validate } from "@octokit/graphql-schema";
import { PullRequest, validate } from "@octokit/graphql-schema";
import { ContextPlugin } from "../types/plugin-input";

type ClosedByPullRequestsReferences = {
node: Pick<PullRequest, "url" | "title" | "number" | "state" | "body"> & Pick<User, "login" | "id">;
node: Pick<PullRequest, "url" | "title" | "number" | "state" | "body" | "id"> & { author: { login: string; id: number } };
};

type IssueWithClosedByPrs = {
Expand All @@ -22,6 +22,7 @@ const query = /* GraphQL */ `
closedByPullRequestsReferences(first: 100, includeClosedPrs: false) {
edges {
node {
id
url
title
body
Expand Down
10 changes: 10 additions & 0 deletions src/helpers/pull-request-draft.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const MUTATION_PULL_REQUEST_TO_DRAFT = /* GraphQL */ `
mutation ConvertPullRequestToDraft($input: ConvertPullRequestToDraftInput!) {
convertPullRequestToDraft(input: $input) {
pullRequest {
id
isDraft
}
}
}
`;
28 changes: 28 additions & 0 deletions src/helpers/remind-and-remove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ListIssueForRepo } from "../types/github-types";
import { ContextPlugin } from "../types/plugin-input";
import { collectLinkedPullRequests } from "./collect-linked-pulls";
import { parseIssueUrl } from "./github-url";
import { MUTATION_PULL_REQUEST_TO_DRAFT } from "./pull-request-draft";
import { createStructuredMetadata } from "./structured-metadata";

export async function unassignUserFromIssue(context: ContextPlugin, issue: ListIssueForRepo) {
Expand Down Expand Up @@ -68,6 +69,11 @@ async function remindAssignees(context: ContextPlugin, issue: ListIssueForRepo)
issue_number: prNumber,
body: [logMessage.logMessage.raw, metadata].join("\n"),
});
await octokit.graphql(MUTATION_PULL_REQUEST_TO_DRAFT, {
input: {
pullRequestId: pullRequest.id,
},
});
} catch (e) {
logger.error(`Could not post to ${pullRequest.url} will post to the issue instead.`, { e });
shouldPostToMainIssue = true;
Expand Down Expand Up @@ -118,3 +124,25 @@ async function removeAllAssignees(context: ContextPlugin, issue: ListIssueForRep
});
return true;
}

export async function closeLinkedPullRequests(context: ContextPlugin, issue: ListIssueForRepo) {
const { octokit, logger } = context;
const { repo, owner, issue_number } = parseIssueUrl(issue.html_url);
const pullRequestsFromAssignees = (await collectLinkedPullRequests(context, { repo, owner, issue_number })).filter((o) =>
issue.assignees?.some((assignee) => assignee.id === o.author.id)
);

for (const pullRequest of pullRequestsFromAssignees) {
const { owner: prOwner, repo: prRepo, issue_number: prNumber } = parseIssueUrl(pullRequest.url);
try {
await octokit.rest.pulls.update({
owner: prOwner,
repo: prRepo,
pull_number: prNumber,
state: "closed",
});
} catch (e) {
logger.error(`Could not close pull-request ${pullRequest.url}.`, { e });
}
}
}
9 changes: 5 additions & 4 deletions src/helpers/task-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import { ContextPlugin, TimelineEvent } from "../types/plugin-input";
import { collectLinkedPullRequests } from "./collect-linked-pulls";
import { getAssigneesActivityForIssue } from "./get-assignee-activity";
import { parseIssueUrl } from "./github-url";
import { remindAssigneesForIssue, unassignUserFromIssue } from "./remind-and-remove";
import { closeLinkedPullRequests, remindAssigneesForIssue, unassignUserFromIssue } from "./remind-and-remove";
import { getCommentsFromMetadata } from "./structured-metadata";
import { getTaskAssignmentDetails, parsePriorityLabel } from "./task-metadata";

const getMostRecentActivityDate = (assignedEventDate: DateTime, activityEventDate?: DateTime): DateTime => {
function getMostRecentActivityDate(assignedEventDate: DateTime, activityEventDate?: DateTime): DateTime {
return activityEventDate && activityEventDate > assignedEventDate ? activityEventDate : assignedEventDate;
};
}

export async function updateTaskReminder(context: ContextPlugin, repo: ListForOrg["data"][0], issue: ListIssueForRepo) {
const {
Expand Down Expand Up @@ -79,8 +79,9 @@ export async function updateTaskReminder(context: ContextPlugin, repo: ListForOr
mostRecentActivityDate = lastReminderTime > mostRecentActivityDate ? lastReminderTime : mostRecentActivityDate;
if (mostRecentActivityDate.plus({ milliseconds: prioritySpeed ? disqualificationTimeDifference / priorityLevel : disqualificationTimeDifference }) <= now) {
await unassignUserFromIssue(context, issue);
await closeLinkedPullRequests(context, issue);
} else {
logger.info(`Reminder was sent for ${issue.html_url} already, not beyond disqualification disqualification threshold yet.`, {
logger.info(`Reminder was sent for ${issue.html_url} already, not beyond disqualification deadline threshold yet.`, {
now: now.toLocaleString(DateTime.DATETIME_MED),
assignedDate: DateTime.fromISO(assignedEvent.created_at).toLocaleString(DateTime.DATETIME_MED),
lastReminderComment: lastReminderComment ? DateTime.fromISO(lastReminderComment.created_at).toLocaleString(DateTime.DATETIME_MED) : "none",
Expand Down
26 changes: 26 additions & 0 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Manifest } from "@ubiquity-os/plugin-sdk/dist/manifest";
import { LOG_LEVEL } from "@ubiquity-os/ubiquity-os-logger";
import { createPlugin } from "@ubiquity-os/plugin-sdk";
import { run } from "./run";
import { Env, envSchema, PluginSettings, pluginSettingsSchema, SupportedEvents } from "./types/plugin-input";
import manifest from "../manifest.json";

const app = createPlugin<PluginSettings, Env, null, SupportedEvents>(
(context) => {
return run(context);
},
manifest as Manifest,
{
envSchema: envSchema,
settingsSchema: pluginSettingsSchema,
logLevel: process.env.LOG_LEVEL || LOG_LEVEL.INFO,
postCommentOnError: false,
...(process.env.KERNEL_PUBLIC_KEY && { kernelPublicKey: process.env.KERNEL_PUBLIC_KEY }),
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
bypassSignatureVerification: process.env.NODE_ENV === "local",
}
);

export default {
fetch: app.fetch,
port: 4000,
};
6 changes: 3 additions & 3 deletions tests/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ describe("User start/stop", () => {
caller: STRINGS.LOGS_ANON_CALLER,
});
expect(infoSpy).toHaveBeenCalledWith(
expect.stringContaining("Passed the deadline and no activity is detected, removing assignees: @user2."),
expect.stringContaining("Passed the disqualification threshold and no activity is detected, removing assignees: @user2."),
expect.anything()
);
expect(infoSpy).not.toHaveBeenCalledWith(expect.stringContaining(STRINGS.PRIVATE_REPO_NAME));
Expand All @@ -147,7 +147,7 @@ describe("User start/stop", () => {
taskAssignees: [2],
caller: STRINGS.LOGS_ANON_CALLER,
});
expect(infoSpy).toHaveBeenCalledWith("Passed the deadline and no activity is detected, removing assignees: @user2.", expect.anything());
expect(infoSpy).toHaveBeenCalledWith("Passed the disqualification threshold and no activity is detected, removing assignees: @user2.", expect.anything());
expect(infoSpy).toHaveBeenCalledWith(expect.stringContaining(STRINGS.PRIVATE_REPO_NAME));
});

Expand All @@ -166,7 +166,7 @@ describe("User start/stop", () => {
taskAssignees: [2],
caller: STRINGS.LOGS_ANON_CALLER,
});
expect(infoSpy).toHaveBeenCalledWith("Passed the deadline and no activity is detected, removing assignees: @user2.", expect.anything());
expect(infoSpy).toHaveBeenCalledWith("Passed the disqualification threshold and no activity is detected, removing assignees: @user2.", expect.anything());
const updatedIssue = db.issue.findFirst({ where: { id: { equals: 4 } } });
expect(updatedIssue?.assignees).toEqual([]);
});
Expand Down
Loading