refactor(source-control): Forgejo lives in @t3tools/source-control-forgejo (#17581)
Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
28f11ed7a5
commit
f6e45028ef
31 files changed
+1632
-1303
No files matched your search
@@ -22,7 +22,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
|
||||
import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";
|
||||
import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
|
||||
import {
|
||||
buildReviewThreads,
|
||||
decodeCommentsJson,
|
||||
|
||||
@@ -1,614 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Result from "effect/Result";
|
||||
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
|
||||
import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";
|
||||
import {
|
||||
PullRequestProviderError,
|
||||
type ProviderChangeRequestDetail,
|
||||
type ProviderRepositoryRef,
|
||||
type PullRequestProviderApi,
|
||||
} from "@t3tools/source-control-core/server/PullRequestProvider";
|
||||
import {
|
||||
ForgejoPullRequest,
|
||||
ForgejoRepository,
|
||||
ForgejoUser,
|
||||
ForgejoComment,
|
||||
ForgejoReview,
|
||||
ForgejoReviewComment,
|
||||
ForgejoCommit,
|
||||
ForgejoStatus,
|
||||
ForgejoLabel,
|
||||
ForgejoReaction,
|
||||
FORGEJO_REACTIONS,
|
||||
forgejoChangeRequest,
|
||||
forgejoActor,
|
||||
forgejoComment,
|
||||
forgejoReview,
|
||||
forgejoReviewThread,
|
||||
forgejoCommit,
|
||||
forgejoChecks,
|
||||
forgejoReactions,
|
||||
} from "./forgejoPullRequestJson.ts";
|
||||
|
||||
const CAPABILITIES: PullRequestCapabilities = {
|
||||
diff: true,
|
||||
viewedFiles: "environment",
|
||||
comment: true,
|
||||
actions: ["merge", "close", "reopen", "update-branch"],
|
||||
mergeMethods: ["merge", "squash", "rebase"],
|
||||
updateMethods: ["merge", "rebase"],
|
||||
search: false,
|
||||
reactions: true,
|
||||
labels: true,
|
||||
// Forgejo's public API has no thread replies/resolution or draft conversion endpoint.
|
||||
review: {
|
||||
inlineComment: true,
|
||||
reply: false,
|
||||
resolve: false,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
},
|
||||
reviewers: { request: true, listCandidates: true },
|
||||
edit: { changeRequest: true, comment: true },
|
||||
};
|
||||
const repoPath = (input: ProviderRepositoryRef) =>
|
||||
`repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
|
||||
const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) =>
|
||||
`${repoPath(input)}/pulls/${input.number}`;
|
||||
const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) =>
|
||||
`${repoPath(input)}/issues/${input.number}`;
|
||||
// Review IDs differ from the issue-comment IDs used by Forgejo's reactions API.
|
||||
const reviewCommentId = (review: typeof ForgejoReview.Type) =>
|
||||
/#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1];
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const cli = yield* ForgejoCli.ForgejoCli;
|
||||
const failure = (operation: string, detail: string, cause?: unknown) =>
|
||||
new PullRequestProviderError({
|
||||
provider: "forgejo",
|
||||
operation,
|
||||
reason: "failed",
|
||||
detail,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
const request = (input: ForgejoCli.ForgejoApiInput) =>
|
||||
cli.api(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new PullRequestProviderError({
|
||||
provider: "forgejo",
|
||||
operation: input.path,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
reason:
|
||||
error.reason === "missing-cli"
|
||||
? "missing-tool"
|
||||
: error.reason === "authentication"
|
||||
? "unauthenticated"
|
||||
: error.reason === "rate-limit"
|
||||
? "rate-limited"
|
||||
: error.reason === "not-found"
|
||||
? "not-found"
|
||||
: "failed",
|
||||
}),
|
||||
),
|
||||
);
|
||||
const read = Effect.fn("ForgejoPullRequestProvider.read")(function* <A>(
|
||||
input: ForgejoCli.ForgejoApiInput,
|
||||
schema: Schema.Codec<A, unknown, never, never>,
|
||||
) {
|
||||
const result = yield* request(input);
|
||||
if (result.stdoutTruncated)
|
||||
return yield* failure(input.path, "Forgejo response exceeded the output limit.");
|
||||
const decoded = decodeJsonResult(schema)(result.stdout);
|
||||
return Result.isSuccess(decoded)
|
||||
? decoded.success
|
||||
: yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
|
||||
});
|
||||
const readArray = <A>(
|
||||
input: ForgejoCli.ForgejoApiInput,
|
||||
schema: Schema.Codec<A, unknown, never, never>,
|
||||
) => read(input, Schema.NullOr(Schema.Array(schema))).pipe(Effect.map((rows) => rows ?? []));
|
||||
const readPage = Effect.fn("ForgejoPullRequestProvider.readPage")(function* <A>(
|
||||
input: ForgejoCli.ForgejoApiInput,
|
||||
schema: Schema.Codec<A, unknown, never, never>,
|
||||
index: number,
|
||||
) {
|
||||
const result = yield* request({
|
||||
...input,
|
||||
path: `${input.path}${input.path.includes("?") ? "&" : "?"}limit=50&page=${index}`,
|
||||
});
|
||||
if (result.stdoutTruncated)
|
||||
return yield* failure(input.path, "Forgejo response exceeded the output limit.");
|
||||
const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);
|
||||
if (Result.isFailure(decoded))
|
||||
return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
|
||||
const rows = decoded.success ?? [];
|
||||
const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
|
||||
return {
|
||||
rows,
|
||||
more: rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links)),
|
||||
};
|
||||
});
|
||||
// Use a stable, small page size that also works with Forgejo's default maximum of 50.
|
||||
const page = Effect.fn("ForgejoPullRequestProvider.page")(function* <A>(
|
||||
input: ForgejoCli.ForgejoApiInput,
|
||||
schema: Schema.Codec<A, unknown, never, never>,
|
||||
limit = 500,
|
||||
) {
|
||||
const items: A[] = [];
|
||||
for (let index = 1; items.length < limit; index++) {
|
||||
const { rows, more } = yield* readPage(input, schema, index);
|
||||
items.push(...rows);
|
||||
if (!more) return { items, truncated: false };
|
||||
}
|
||||
return { items, truncated: true };
|
||||
});
|
||||
const write = (input: ForgejoCli.ForgejoApiInput) => request(input).pipe(Effect.asVoid);
|
||||
const getPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
|
||||
read(
|
||||
{
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
path: pullPath(input),
|
||||
},
|
||||
ForgejoPullRequest,
|
||||
);
|
||||
const getRepo = (input: ProviderRepositoryRef) =>
|
||||
read({ ...input, path: repoPath(input) }, ForgejoRepository);
|
||||
const getViewer = (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository?: string;
|
||||
readonly host?: string;
|
||||
}) => read({ ...input, path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));
|
||||
const permissions = (
|
||||
repo: typeof ForgejoRepository.Type,
|
||||
pr: typeof ForgejoPullRequest.Type,
|
||||
viewer: string,
|
||||
): PullRequestViewerPermissions => {
|
||||
const canWrite = repo.permissions?.push ?? false;
|
||||
const canEdit = canWrite || pr.user?.login === viewer;
|
||||
const active = !repo.archived;
|
||||
return {
|
||||
actions: active
|
||||
? CAPABILITIES.actions.filter((action) =>
|
||||
action === "merge" || action === "update-branch" ? canWrite : canEdit,
|
||||
)
|
||||
: [],
|
||||
comment: active && (!pr.is_locked || canWrite),
|
||||
resolve: false,
|
||||
verdicts: active
|
||||
? pr.user?.login === viewer
|
||||
? ["comment"]
|
||||
: CAPABILITIES.review.verdicts
|
||||
: [],
|
||||
requestReviewers: active && canEdit,
|
||||
labels: active && canWrite,
|
||||
updateMethods:
|
||||
active && canWrite ? (repo.allow_rebase_update ? ["merge", "rebase"] : ["merge"]) : [],
|
||||
};
|
||||
};
|
||||
const getPermissions = Effect.fn("ForgejoPullRequestProvider.getPermissions")(function* (
|
||||
input: ProviderRepositoryRef & { readonly number: number },
|
||||
) {
|
||||
const [repo, pr, viewer] = yield* Effect.all(
|
||||
[getRepo(input), getPull(input), getViewer(input)],
|
||||
{ concurrency: 3 },
|
||||
);
|
||||
return permissions(repo, pr, viewer);
|
||||
});
|
||||
const unsupported = (operation: string) =>
|
||||
Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`));
|
||||
const provider: PullRequestProviderApi = {
|
||||
kind: "forgejo",
|
||||
capabilities: CAPABILITIES,
|
||||
getViewer,
|
||||
listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")(
|
||||
function* (input) {
|
||||
const offset = input.cursor?.delivered ?? 0;
|
||||
const items: ReturnType<typeof forgejoChangeRequest>[] = [];
|
||||
const state = input.state === "merged" ? "closed" : input.state;
|
||||
const query = {
|
||||
...input,
|
||||
path: `${repoPath(input)}/pulls?state=${state}&sort=recentupdate`,
|
||||
};
|
||||
// Self-hosted servers may cap pages below 50. Establish their actual page size before
|
||||
// translating the service's row offset into an API page number.
|
||||
const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1);
|
||||
const pageSize = first.rows.length || 50;
|
||||
const firstIndex = Math.floor(offset / pageSize) + 1;
|
||||
let consumed = 0;
|
||||
let more = true;
|
||||
for (let index = firstIndex; more && consumed < input.limit; index++) {
|
||||
const result =
|
||||
index === 1 ? first : yield* readPage(query, Schema.NullOr(ForgejoPullRequest), index);
|
||||
const rows = result.rows;
|
||||
const start = index === firstIndex ? offset % pageSize : 0;
|
||||
const countBefore = consumed;
|
||||
for (const row of rows.slice(start)) {
|
||||
if (consumed >= input.limit) break;
|
||||
consumed++;
|
||||
if (row) items.push(forgejoChangeRequest(row));
|
||||
}
|
||||
more = result.more || rows.length - start > consumed - countBefore;
|
||||
}
|
||||
return { items, truncated: more, continues: true, cursorAdvance: consumed };
|
||||
},
|
||||
),
|
||||
getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),
|
||||
getChangeRequestChecks: Effect.fn("ForgejoPullRequestProvider.getChangeRequestChecks")(
|
||||
function* (input) {
|
||||
const pr = yield* getPull(input);
|
||||
const statuses = yield* page(
|
||||
{
|
||||
...input,
|
||||
path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
|
||||
},
|
||||
ForgejoStatus,
|
||||
);
|
||||
return { state: forgejoChangeRequest(pr).state, checks: forgejoChecks(statuses.items) };
|
||||
},
|
||||
),
|
||||
getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
|
||||
const [pr, repo, viewer] = yield* Effect.all(
|
||||
[getPull(input), getRepo(input), getViewer(input)],
|
||||
{ concurrency: 3 },
|
||||
);
|
||||
const statuses = yield* page(
|
||||
{
|
||||
...input,
|
||||
path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
|
||||
},
|
||||
ForgejoStatus,
|
||||
);
|
||||
return {
|
||||
...forgejoChangeRequest(pr),
|
||||
body: pr.body ?? "",
|
||||
changedFiles: pr.changed_files ?? 0,
|
||||
reviewers: (pr.requested_reviewers ?? []).flatMap((user) => {
|
||||
const actor = forgejoActor(user);
|
||||
return actor ? [actor] : [];
|
||||
}),
|
||||
checks: forgejoChecks(statuses.items),
|
||||
baseComparison: !pr.merge_base
|
||||
? "unknown"
|
||||
: pr.merge_base === pr.base.sha
|
||||
? "up-to-date"
|
||||
: "behind",
|
||||
viewerPermissions: permissions(repo, pr, viewer),
|
||||
mergeCapabilities: {
|
||||
merge: repo.allow_merge_commits ?? true,
|
||||
squash: repo.allow_squash_merge ?? true,
|
||||
rebase: repo.allow_rebase ?? true,
|
||||
},
|
||||
} satisfies ProviderChangeRequestDetail;
|
||||
}),
|
||||
getViewerPermissions: getPermissions,
|
||||
getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(
|
||||
function* (input) {
|
||||
const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(
|
||||
[
|
||||
// Issue comments ignore page/limit; fetch this unpaginated endpoint once.
|
||||
readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(
|
||||
Effect.map((items) => ({
|
||||
items: items.slice(0, 500),
|
||||
truncated: items.length > 500,
|
||||
})),
|
||||
),
|
||||
page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),
|
||||
page({ ...input, path: `${pullPath(input)}/commits` }, ForgejoCommit),
|
||||
page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),
|
||||
getViewer(input),
|
||||
],
|
||||
{ concurrency: 5 },
|
||||
);
|
||||
const reviewComments = yield* Effect.forEach(
|
||||
reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),
|
||||
(review) =>
|
||||
readArray(
|
||||
{ ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },
|
||||
ForgejoReviewComment,
|
||||
),
|
||||
{ concurrency: 4 },
|
||||
);
|
||||
const allInline = reviewComments.flat();
|
||||
const inline = allInline.slice(0, 500);
|
||||
const entries = [
|
||||
...comments.items.map((comment) => ({
|
||||
comment: forgejoComment(comment),
|
||||
reactionId: String(comment.id),
|
||||
})),
|
||||
...reviews.items
|
||||
.filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW")
|
||||
.map((review) => ({
|
||||
comment: forgejoReview(review),
|
||||
reactionId: reviewCommentId(review),
|
||||
})),
|
||||
...inline.map((comment) => ({
|
||||
comment: {
|
||||
...forgejoComment(comment),
|
||||
kind: "review-comment" as const,
|
||||
path: comment.path,
|
||||
},
|
||||
reactionId: String(comment.id),
|
||||
})),
|
||||
];
|
||||
const enriched = yield* Effect.forEach(
|
||||
entries,
|
||||
({ comment, reactionId }) =>
|
||||
(reactionId === undefined
|
||||
? Effect.succeed([])
|
||||
: readArray(
|
||||
{ ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` },
|
||||
ForgejoReaction,
|
||||
)
|
||||
).pipe(
|
||||
Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })),
|
||||
),
|
||||
{ concurrency: 4 },
|
||||
);
|
||||
const byId = new Map(enriched.map((comment) => [comment.id, comment]));
|
||||
const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
|
||||
return {
|
||||
comments: timeline,
|
||||
commentCount: timeline.length,
|
||||
commentsTruncated:
|
||||
comments.truncated || reviews.truncated || allInline.length > inline.length,
|
||||
reviewThreads: inline.map((comment) => ({
|
||||
...forgejoReviewThread(comment),
|
||||
comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)],
|
||||
})),
|
||||
commits: commits.items.map(forgejoCommit),
|
||||
reactions: forgejoReactions(reactions.items, viewer),
|
||||
};
|
||||
},
|
||||
),
|
||||
getFileRevisions: Effect.fn("ForgejoPullRequestProvider.getFileRevisions")(function* (input) {
|
||||
const result = yield* request({ ...input, path: `${pullPath(input)}.diff` });
|
||||
if (result.stdoutTruncated) {
|
||||
return yield* failure("getFileRevisions", "Forgejo diff exceeded the output limit.");
|
||||
}
|
||||
const revisions = new Map(parseDiffFileRevisions(result.stdout));
|
||||
for (const path of input.paths) {
|
||||
if (!revisions.has(path)) revisions.set(path, "");
|
||||
}
|
||||
return { revisions, complete: true };
|
||||
}),
|
||||
getDiff: (input) =>
|
||||
request({
|
||||
...input,
|
||||
path: input.commit
|
||||
? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff`
|
||||
: `${pullPath(input)}.diff`,
|
||||
}).pipe(
|
||||
Effect.map((result) => ({
|
||||
patch: result.stdout,
|
||||
truncated: result.stdoutTruncated,
|
||||
nextCursor: null,
|
||||
})),
|
||||
),
|
||||
getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")(
|
||||
function* (input) {
|
||||
const pr = yield* getPull(input);
|
||||
const commit = input.commit
|
||||
? yield* read(
|
||||
{
|
||||
...input,
|
||||
path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}`,
|
||||
},
|
||||
ForgejoCommit,
|
||||
)
|
||||
: null;
|
||||
const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha;
|
||||
const newRef = input.commit ?? pr.head.sha;
|
||||
const content = (repository: string, ref: string, path: string) =>
|
||||
read(
|
||||
{
|
||||
...input,
|
||||
repository,
|
||||
path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`,
|
||||
},
|
||||
Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }),
|
||||
).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8")));
|
||||
const [oldContents, newContents] = yield* Effect.all(
|
||||
[
|
||||
input.changeType === "new" || !oldRef
|
||||
? Effect.succeed("")
|
||||
: content(input.repository, oldRef, input.oldPath),
|
||||
input.changeType === "deleted"
|
||||
? Effect.succeed("")
|
||||
: content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
return { oldContents, newContents };
|
||||
},
|
||||
),
|
||||
runAction: (input) => {
|
||||
switch (input.action) {
|
||||
case "merge":
|
||||
return write({
|
||||
...input,
|
||||
path: `${pullPath(input)}/merge`,
|
||||
method: "POST",
|
||||
body: { Do: input.mergeMethod ?? "merge" },
|
||||
});
|
||||
case "close":
|
||||
case "reopen":
|
||||
return write({
|
||||
...input,
|
||||
path: pullPath(input),
|
||||
method: "PATCH",
|
||||
body: { state: input.action === "close" ? "closed" : "open" },
|
||||
});
|
||||
case "update-branch":
|
||||
return write({
|
||||
...input,
|
||||
path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`,
|
||||
method: "POST",
|
||||
});
|
||||
default:
|
||||
return unsupported(input.action);
|
||||
}
|
||||
},
|
||||
updateChangeRequest: (input) =>
|
||||
write({
|
||||
...input,
|
||||
path: pullPath(input),
|
||||
method: "PATCH",
|
||||
body: {
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
...(input.body === undefined ? {} : { body: input.body }),
|
||||
},
|
||||
}),
|
||||
comment: (input) =>
|
||||
write({
|
||||
...input,
|
||||
path: `${issuePath(input)}/comments`,
|
||||
method: "POST",
|
||||
body: { body: input.body },
|
||||
}),
|
||||
updateComment: (input) =>
|
||||
write({
|
||||
...input,
|
||||
path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`,
|
||||
method: "PATCH",
|
||||
body: { body: input.body },
|
||||
}),
|
||||
submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) {
|
||||
const pr = yield* getPull(input);
|
||||
yield* write({
|
||||
...input,
|
||||
path: `${pullPath(input)}/reviews`,
|
||||
method: "POST",
|
||||
body: {
|
||||
event:
|
||||
input.verdict === "approve"
|
||||
? "APPROVED"
|
||||
: input.verdict === "request-changes"
|
||||
? "REQUEST_CHANGES"
|
||||
: "COMMENT",
|
||||
body: input.body,
|
||||
commit_id: pr.head.sha,
|
||||
comments: input.comments.map((comment) => {
|
||||
const position = comment.position;
|
||||
const old =
|
||||
position.kind === "deleted" ||
|
||||
(position.kind === "context" && position.side === "left");
|
||||
return {
|
||||
path: old ? (comment.oldPath ?? comment.path) : comment.path,
|
||||
body: comment.body,
|
||||
old_position: old ? position.oldLine : 0,
|
||||
new_position: old ? 0 : position.newLine,
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
}),
|
||||
listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")(
|
||||
function* (input) {
|
||||
const [pr, users] = yield* Effect.all(
|
||||
[getPull(input), page({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser)],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
return {
|
||||
candidates: users.items
|
||||
.filter((user) => user.login !== pr.user?.login)
|
||||
.flatMap((user) => {
|
||||
const actor = forgejoActor(user);
|
||||
return actor
|
||||
? [
|
||||
{
|
||||
...actor,
|
||||
id: user.login,
|
||||
kind: "user" as const,
|
||||
isRequested:
|
||||
pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ??
|
||||
false,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
truncated: users.truncated,
|
||||
};
|
||||
},
|
||||
),
|
||||
setReviewerRequest: (input) =>
|
||||
write({
|
||||
...input,
|
||||
path: `${pullPath(input)}/requested_reviewers`,
|
||||
method: input.requested ? "POST" : "DELETE",
|
||||
body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) },
|
||||
}),
|
||||
listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")(
|
||||
function* (input) {
|
||||
const [pr, labels] = yield* Effect.all(
|
||||
[getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
return {
|
||||
candidates: labels.items.map((label) => ({
|
||||
name: label.name,
|
||||
color: label.color ?? null,
|
||||
description: label.description ?? null,
|
||||
isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false,
|
||||
})),
|
||||
truncated: labels.truncated,
|
||||
};
|
||||
},
|
||||
),
|
||||
setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {
|
||||
const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
|
||||
const selected = labels.items.filter((label) => input.labels.includes(label.name));
|
||||
if (selected.length !== input.labels.length)
|
||||
return yield* failure("setLabels", "One or more requested labels could not be found.");
|
||||
if (input.applied)
|
||||
yield* write({
|
||||
...input,
|
||||
path: `${issuePath(input)}/labels`,
|
||||
method: "POST",
|
||||
body: { labels: selected.map((label) => label.id) },
|
||||
});
|
||||
else
|
||||
yield* Effect.forEach(
|
||||
selected,
|
||||
(label) =>
|
||||
write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
}),
|
||||
setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) {
|
||||
let commentId = input.subjectId;
|
||||
if (commentId?.startsWith("review:")) {
|
||||
const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1];
|
||||
if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID.");
|
||||
const review = yield* read(
|
||||
{ ...input, path: `${pullPath(input)}/reviews/${reviewId}` },
|
||||
ForgejoReview,
|
||||
);
|
||||
commentId = reviewCommentId(review);
|
||||
if (!commentId)
|
||||
return yield* failure(
|
||||
"setReaction",
|
||||
"Forgejo did not return a comment ID for this review.",
|
||||
);
|
||||
}
|
||||
if (commentId && !/^[1-9]\d*$/.test(commentId))
|
||||
return yield* failure("setReaction", "Invalid Forgejo comment ID.");
|
||||
yield* write({
|
||||
...input,
|
||||
path: commentId
|
||||
? `${repoPath(input)}/issues/comments/${commentId}/reactions`
|
||||
: `${issuePath(input)}/reactions`,
|
||||
method: input.reacted ? "POST" : "DELETE",
|
||||
body: { content: FORGEJO_REACTIONS[input.content] },
|
||||
});
|
||||
}),
|
||||
replyToThread: () => unsupported("thread replies"),
|
||||
setThreadResolution: () => unsupported("thread resolution"),
|
||||
};
|
||||
return provider;
|
||||
});
|
||||
@@ -7,8 +7,6 @@ import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
|
||||
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
|
||||
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
|
||||
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
|
||||
import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
|
||||
import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
|
||||
import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
|
||||
import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
|
||||
import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
|
||||
@@ -17,6 +15,7 @@ import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
|
||||
import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
|
||||
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
|
||||
import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts";
|
||||
import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
|
||||
import type { PullRequestProviderApi } from "@t3tools/source-control-core/server/PullRequestProvider";
|
||||
|
||||
export class PullRequestProviderRegistry extends Context.Service<
|
||||
@@ -45,16 +44,21 @@ export function fromProviders(
|
||||
*
|
||||
* @public Service construction is part of the canonical Effect module API.
|
||||
*/
|
||||
export const make = Effect.map(
|
||||
Effect.all([
|
||||
export const make = Effect.gen(function* () {
|
||||
const providers = yield* Effect.all([
|
||||
GitHubPullRequestProvider.make,
|
||||
GitLabPullRequestProvider.make,
|
||||
ForgejoPullRequestProvider.make,
|
||||
BitbucketPullRequestProvider.make,
|
||||
AzureDevOpsPullRequestProvider.make,
|
||||
]),
|
||||
fromProviders,
|
||||
);
|
||||
]);
|
||||
const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
|
||||
driver.make.pipe(Effect.map((instance) => instance.pullRequests)),
|
||||
);
|
||||
return fromProviders([
|
||||
...providers,
|
||||
...drivers.filter((provider): provider is PullRequestProviderApi => provider !== null),
|
||||
]);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
|
||||
Layer.provide(
|
||||
@@ -66,7 +70,7 @@ export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
|
||||
),
|
||||
),
|
||||
Layer.provide(GitLabPullRequestCli.layer.pipe(Layer.provide(GitLabCli.layer))),
|
||||
Layer.provide(ForgejoCli.layer),
|
||||
Layer.provide(BuiltInDrivers.layer),
|
||||
Layer.provide(BitbucketPullRequestApi.layer.pipe(Layer.provide(BitbucketApi.layer))),
|
||||
Layer.provide(AzureDevOpsPullRequestCli.layer.pipe(Layer.provide(AzureDevOpsCli.layer))),
|
||||
);
|
||||
@@ -30,8 +30,8 @@ import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.t
|
||||
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
|
||||
import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
|
||||
import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
|
||||
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
|
||||
import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider";
|
||||
import {
|
||||
PullRequestProviderError,
|
||||
type ProviderChangeRequest,
|
||||
|
||||
@@ -1,280 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";
|
||||
|
||||
function patchOf(...lines: ReadonlyArray<string>): string {
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
|
||||
describe("parseDiffFileRevisions", () => {
|
||||
it("reads the head id of a changed file off its index line", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"index 7f2aa0ab6..b4a2a7c9a 100644",
|
||||
"--- a/src/a.ts",
|
||||
"+++ b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["src/a.ts", "b4a2a7c9a"]]);
|
||||
});
|
||||
|
||||
it("names a deletion by the path it had, which is the one still on screen", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/gone.ts b/gone.ts",
|
||||
"deleted file mode 100644",
|
||||
"index 1111111..0000000",
|
||||
"--- a/gone.ts",
|
||||
"+++ /dev/null",
|
||||
"@@ -1 +0,0 @@",
|
||||
"-x",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["gone.ts", "0000000"]]);
|
||||
});
|
||||
|
||||
it("names a rename by where it moved to", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/old.ts b/new.ts",
|
||||
"similarity index 90%",
|
||||
"rename from old.ts",
|
||||
"rename to new.ts",
|
||||
"index 2222222..3333333 100644",
|
||||
"--- a/old.ts",
|
||||
"+++ b/new.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["new.ts", "3333333"]]);
|
||||
});
|
||||
|
||||
it("names a rename that changed nothing, which states no paths of its own", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/old.ts b/new.ts",
|
||||
"similarity index 100%",
|
||||
"rename from old.ts",
|
||||
"rename to new.ts",
|
||||
"index 2222222..2222222 100644",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["new.ts", "2222222"]]);
|
||||
});
|
||||
|
||||
it("leaves out a file Bitbucket excluded, which it gives no index line for", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/package.json b/package.json",
|
||||
"index 7f2aa0ab6..b4a2a7c9a 100644",
|
||||
"--- a/package.json",
|
||||
"+++ b/package.json",
|
||||
"@@ -1 +1 @@",
|
||||
'- "x": "1"',
|
||||
'+ "x": "2"',
|
||||
"diff --git a/yarn.lock b/yarn.lock",
|
||||
'File excluded by pattern "yarn.lock"',
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["package.json", "b4a2a7c9a"]]);
|
||||
});
|
||||
|
||||
it("stops reading headers at the first hunk, so content cannot pose as one", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/notes.md b/notes.md",
|
||||
"index aaaaaaa..bbbbbbb 100644",
|
||||
"--- a/notes.md",
|
||||
"+++ b/notes.md",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"--- a/decoy.ts",
|
||||
"+++ b/decoy.ts",
|
||||
"+index ccccccc..ddddddd 100644",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["notes.md", "bbbbbbb"]]);
|
||||
});
|
||||
|
||||
it("splits a header whose paths contain the separator, by the sides agreeing", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/one b/two.ts b/one b/two.ts",
|
||||
"index eeeeeee..fffffff 100644",
|
||||
"@@ -1 +1 @@",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["one b/two.ts", "fffffff"]]);
|
||||
});
|
||||
|
||||
it("leaves out an added file that Bitbucket sent no index line for", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf("diff --git a/added.ts b/added.ts", "new file mode 100644", "--- /dev/null"),
|
||||
);
|
||||
|
||||
assert.strictEqual(revisions.size, 0);
|
||||
});
|
||||
|
||||
it("reads nothing out of an empty patch", () => {
|
||||
assert.strictEqual(parseDiffFileRevisions("").size, 0);
|
||||
});
|
||||
|
||||
it("reads a name git had to quote, here one holding a tab", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
'diff --git "a/we\\tird.ts" "b/we\\tird.ts"',
|
||||
"index 4444444..5555555 100644",
|
||||
'--- "a/we\\tird.ts"',
|
||||
'+++ "b/we\\tird.ts"',
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["we\tird.ts", "5555555"]]);
|
||||
});
|
||||
|
||||
it("rejoins the octal bytes git writes for a name outside ASCII", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
'diff --git "a/caf\\303\\251/r\\303\\251sum\\303\\251.ts" "b/caf\\303\\251/r\\303\\251sum\\303\\251.ts"',
|
||||
"index 6666666..7777777 100644",
|
||||
"@@ -1 +1 @@",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["café/résumé.ts", "7777777"]]);
|
||||
});
|
||||
|
||||
it("splits a rename header where git quoted only the side that needed it", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
'diff --git a/old.ts "b/new\\tname.ts"',
|
||||
"similarity index 90%",
|
||||
"rename from old.ts",
|
||||
'rename to "new\\tname.ts"',
|
||||
"index 8888888..9999999 100644",
|
||||
"--- a/old.ts",
|
||||
'+++ "b/new\\tname.ts"',
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["new\tname.ts", "9999999"]]);
|
||||
});
|
||||
|
||||
it("names a quoted rename that changed nothing, which states no paths of its own", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
'diff --git "a/old\\tname.ts" "b/new\\tname.ts"',
|
||||
"similarity index 100%",
|
||||
'rename from "old\\tname.ts"',
|
||||
'rename to "new\\tname.ts"',
|
||||
"index abcabca..abcabca 100644",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["new\tname.ts", "abcabca"]]);
|
||||
});
|
||||
|
||||
it("keeps a character from outside the basic plane that git left unescaped", () => {
|
||||
// `core.quotePath` off leaves the name's own bytes in place, and git still quotes the header
|
||||
// for the tab. Encoding what it left one unit at a time would split the pair into two halves.
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
'diff --git "a/we\\tird-\u{1f680}.ts" "b/we\\tird-\u{1f680}.ts"',
|
||||
"index aaaaaaa..bbbbbbb 100644",
|
||||
"@@ -1 +1 @@",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["we\tird-\u{1f680}.ts", "bbbbbbb"]]);
|
||||
});
|
||||
|
||||
it("drops the tab git ends a name holding a space with", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/with space.txt b/with space.txt",
|
||||
"index 1111111..6178079 100644",
|
||||
"--- a/with space.txt\t",
|
||||
"+++ b/with space.txt\t",
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["with space.txt", "6178079"]]);
|
||||
});
|
||||
|
||||
it("drops that tab from a quoted name too, where it lands past the closing quote", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
'diff --git "a/we ird\\tname.ts" "b/we ird\\tname.ts"',
|
||||
"index 2222222..7777777 100644",
|
||||
'--- "a/we ird\\tname.ts"\t',
|
||||
'+++ "b/we ird\\tname.ts"\t',
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["we ird\tname.ts", "7777777"]]);
|
||||
});
|
||||
|
||||
it("reads a deletion whose name holds a space, tab and all", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/with space.txt b/with space.txt",
|
||||
"deleted file mode 100644",
|
||||
"index 3333333..0000000",
|
||||
"--- a/with space.txt\t",
|
||||
"+++ /dev/null",
|
||||
"@@ -1 +0,0 @@",
|
||||
"-a",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["with space.txt", "0000000"]]);
|
||||
});
|
||||
|
||||
it("drops the timestamp other producers of the format write past that tab", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf(
|
||||
"diff --git a/stamped.ts b/stamped.ts",
|
||||
"index 4444444..5555555 100644",
|
||||
"--- a/stamped.ts\t2024-01-01 00:00:00.000000000 +0000",
|
||||
"+++ b/stamped.ts\t2024-01-02 00:00:00.000000000 +0000",
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["stamped.ts", "5555555"]]);
|
||||
});
|
||||
|
||||
it("splits an unquoted header whose names hold a space, by the sides agreeing", () => {
|
||||
const revisions = parseDiffFileRevisions(
|
||||
patchOf("diff --git a/one two b/one two", "index ddddddd..eeeeeee 100644", "@@ -1 +1 @@"),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual([...revisions], [["one two", "eeeeeee"]]);
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
import { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
|
||||
|
||||
const ENTRY = "diff --git ";
|
||||
const QUOTE = '"';
|
||||
|
||||
interface Entry {
|
||||
oldPath: string | null;
|
||||
newPath: string | null;
|
||||
deleted: boolean;
|
||||
revision: string | null;
|
||||
/** Past the first hunk header every line is content, and content can start like a header. */
|
||||
inBody: boolean;
|
||||
}
|
||||
|
||||
/** Where a quoted name closes, given git escapes every quote the name itself holds. */
|
||||
function quotedEnd(rest: string): number {
|
||||
for (let at = 1; at < rest.length; at += 1) {
|
||||
const char = rest.charAt(at);
|
||||
if (char === "\\") {
|
||||
at += 1;
|
||||
continue;
|
||||
}
|
||||
if (char === QUOTE) return at;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* `a/x`/`b/x` on a `---`/`+++` line; `/dev/null` marks the side that has no file. Git ends the
|
||||
* name with a tab when it holds a space, and a name with a tab of its own arrives quoted with
|
||||
* that tab escaped, so the first literal tab is never part of what the file is called.
|
||||
*/
|
||||
function sidePath(rest: string, prefix: string): string | null {
|
||||
const tab = rest.indexOf("\t");
|
||||
const token = tab === -1 ? rest : rest.slice(0, tab);
|
||||
if (token === "/dev/null") return null;
|
||||
const path = unquoteGitPatchPath(token);
|
||||
return path.startsWith(prefix) ? path.slice(prefix.length) : path;
|
||||
}
|
||||
|
||||
function headerSide(token: string, prefix: string): string | null {
|
||||
const path = unquoteGitPatchPath(token);
|
||||
return path.startsWith(prefix) ? path.slice(prefix.length) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The two names on a `diff --git` line, written with no delimiter between them. `a/one two b/one
|
||||
* two` can split in more than one place, so the split leaving both sides equal wins; a rename
|
||||
* (the only case where sides differ) states its names on separate lines instead. A quoted name
|
||||
* ends at its own closing quote and needs none of that guessing.
|
||||
*/
|
||||
function headerPaths(rest: string): readonly [string | null, string | null] {
|
||||
if (rest.startsWith(QUOTE)) {
|
||||
const end = quotedEnd(rest);
|
||||
if (end === -1 || rest.charAt(end + 1) !== " ") return [null, null];
|
||||
return [headerSide(rest.slice(0, end + 1), "a/"), headerSide(rest.slice(end + 2), "b/")];
|
||||
}
|
||||
if (rest.endsWith(QUOTE)) {
|
||||
const opens = rest.indexOf(QUOTE);
|
||||
if (opens < 1 || rest.charAt(opens - 1) !== " ") return [null, null];
|
||||
return [headerSide(rest.slice(0, opens - 1), "a/"), headerSide(rest.slice(opens), "b/")];
|
||||
}
|
||||
if (!rest.startsWith("a/")) return [null, null];
|
||||
const splits: Array<number> = [];
|
||||
for (let at = rest.indexOf(" b/"); at !== -1; at = rest.indexOf(" b/", at + 1)) splits.push(at);
|
||||
const chosen =
|
||||
splits.find((at) => rest.slice(2, at) === rest.slice(at + 3)) ??
|
||||
(splits.length === 1 ? splits[0] : undefined);
|
||||
return chosen === undefined ? [null, null] : [rest.slice(2, chosen), rest.slice(chosen + 3)];
|
||||
}
|
||||
|
||||
/** The right-hand id of `index <before>..<after> <mode>`. */
|
||||
function headRevision(rest: string): string | null {
|
||||
const gap = rest.indexOf("..");
|
||||
if (gap === -1) return null;
|
||||
const after = rest.slice(gap + 2);
|
||||
const end = after.indexOf(" ");
|
||||
const head = end === -1 ? after : after.slice(0, end);
|
||||
return head.length === 0 ? null : head;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the head has of each file, as the blob ids from a unified patch's `index <before>..<after>`
|
||||
* line: Bitbucket exposes no blob id for a file anywhere else. Keyed by the head's name, except
|
||||
* for a deletion where only the old name exists. An entry with no `index` line (most often one
|
||||
* Bitbucket excluded by pattern) is left out.
|
||||
*/
|
||||
export function parseDiffFileRevisions(patch: string): ReadonlyMap<string, string> {
|
||||
const revisions = new Map<string, string>();
|
||||
let entry: Entry | null = null;
|
||||
|
||||
const close = () => {
|
||||
if (entry === null) return;
|
||||
const path = entry.deleted ? entry.oldPath : (entry.newPath ?? entry.oldPath);
|
||||
if (path !== null && path.length > 0 && entry.revision !== null) {
|
||||
revisions.set(path, entry.revision);
|
||||
}
|
||||
entry = null;
|
||||
};
|
||||
|
||||
for (const line of patch.split("\n")) {
|
||||
if (line.startsWith(ENTRY)) {
|
||||
close();
|
||||
const [oldPath, newPath] = headerPaths(line.slice(ENTRY.length));
|
||||
entry = { oldPath, newPath, deleted: false, revision: null, inBody: false };
|
||||
continue;
|
||||
}
|
||||
if (entry === null || entry.inBody) continue;
|
||||
if (line.startsWith("@@")) {
|
||||
entry.inBody = true;
|
||||
} else if (line.startsWith("index ")) {
|
||||
entry.revision = headRevision(line.slice("index ".length));
|
||||
} else if (line.startsWith("deleted file mode")) {
|
||||
entry.deleted = true;
|
||||
} else if (line.startsWith("rename from ")) {
|
||||
entry.oldPath = unquoteGitPatchPath(line.slice("rename from ".length));
|
||||
} else if (line.startsWith("rename to ")) {
|
||||
entry.newPath = unquoteGitPatchPath(line.slice("rename to ".length));
|
||||
} else if (line.startsWith("--- ")) {
|
||||
entry.oldPath = sidePath(line.slice(4), "a/");
|
||||
} else if (line.startsWith("+++ ")) {
|
||||
const side = sidePath(line.slice(4), "b/");
|
||||
entry.newPath = side;
|
||||
if (side === null) entry.deleted = true;
|
||||
}
|
||||
}
|
||||
close();
|
||||
return revisions;
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
import type {
|
||||
PullRequestActor,
|
||||
PullRequestCheck,
|
||||
PullRequestComment,
|
||||
PullRequestCommit,
|
||||
PullRequestReaction,
|
||||
PullRequestReactionContent,
|
||||
PullRequestReviewThread,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ProviderChangeRequest } from "@t3tools/source-control-core/server/PullRequestProvider";
|
||||
import { dedupeChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
|
||||
|
||||
export const ForgejoUser = Schema.Struct({
|
||||
login: Schema.String,
|
||||
full_name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
export const ForgejoLabel = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
name: Schema.String,
|
||||
color: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
description: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
export const ForgejoRepository = Schema.Struct({
|
||||
full_name: Schema.String,
|
||||
permissions: Schema.optional(Schema.Struct({ push: Schema.Boolean, admin: Schema.Boolean })),
|
||||
archived: Schema.optional(Schema.Boolean),
|
||||
allow_merge_commits: Schema.optional(Schema.Boolean),
|
||||
allow_squash_merge: Schema.optional(Schema.Boolean),
|
||||
allow_rebase: Schema.optional(Schema.Boolean),
|
||||
allow_rebase_update: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
const Branch = Schema.Struct({
|
||||
ref: Schema.String,
|
||||
sha: Schema.String,
|
||||
repo: Schema.NullOr(ForgejoRepository),
|
||||
});
|
||||
export const ForgejoPullRequest = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
title: Schema.String,
|
||||
body: Schema.NullOr(Schema.String),
|
||||
html_url: Schema.String,
|
||||
user: Schema.NullOr(ForgejoUser),
|
||||
state: Schema.String,
|
||||
draft: Schema.optional(Schema.Boolean),
|
||||
merged: Schema.Boolean,
|
||||
mergeable: Schema.optional(Schema.Boolean),
|
||||
is_locked: Schema.optional(Schema.Boolean),
|
||||
head: Branch,
|
||||
base: Branch,
|
||||
merge_base: Schema.optional(Schema.String),
|
||||
created_at: Schema.String,
|
||||
updated_at: Schema.String,
|
||||
closed_at: Schema.NullOr(Schema.String),
|
||||
merged_at: Schema.NullOr(Schema.String),
|
||||
additions: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
deletions: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
changed_files: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
comments: Schema.optional(Schema.Int),
|
||||
labels: Schema.NullOr(Schema.Array(ForgejoLabel)),
|
||||
requested_reviewers: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
|
||||
});
|
||||
export const ForgejoComment = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
body: Schema.String,
|
||||
user: Schema.NullOr(ForgejoUser),
|
||||
created_at: Schema.String,
|
||||
html_url: Schema.optional(Schema.String),
|
||||
});
|
||||
export const ForgejoReview = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
body: Schema.String,
|
||||
user: Schema.NullOr(ForgejoUser),
|
||||
state: Schema.String,
|
||||
submitted_at: Schema.String,
|
||||
html_url: Schema.optional(Schema.String),
|
||||
comments_count: Schema.Int,
|
||||
});
|
||||
export const ForgejoReviewComment = Schema.Struct({
|
||||
...ForgejoComment.fields,
|
||||
path: Schema.String,
|
||||
position: Schema.Int,
|
||||
original_position: Schema.Int,
|
||||
commit_id: Schema.String,
|
||||
original_commit_id: Schema.String,
|
||||
resolver: Schema.NullOr(ForgejoUser),
|
||||
});
|
||||
export const ForgejoCommit = Schema.Struct({
|
||||
sha: Schema.String,
|
||||
author: Schema.NullOr(ForgejoUser),
|
||||
commit: Schema.Struct({
|
||||
message: Schema.String,
|
||||
committer: Schema.Struct({ date: Schema.String }),
|
||||
}),
|
||||
parents: Schema.Array(Schema.Struct({ sha: Schema.String })),
|
||||
stats: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ additions: Schema.Int, deletions: Schema.Int })),
|
||||
),
|
||||
});
|
||||
export const ForgejoStatus = Schema.Struct({
|
||||
context: Schema.String,
|
||||
status: Schema.String,
|
||||
description: Schema.NullOr(Schema.String),
|
||||
target_url: Schema.NullOr(Schema.String),
|
||||
updated_at: Schema.String,
|
||||
});
|
||||
export const ForgejoReaction = Schema.Struct({
|
||||
content: Schema.String,
|
||||
user: Schema.NullOr(ForgejoUser),
|
||||
});
|
||||
|
||||
export function forgejoActor(
|
||||
user: typeof ForgejoUser.Type | null | undefined,
|
||||
): PullRequestActor | null {
|
||||
return user?.login
|
||||
? { login: user.login, name: user.full_name || null, avatarUrl: user.avatar_url || null }
|
||||
: null;
|
||||
}
|
||||
|
||||
function toIsoUtc(value: string): string {
|
||||
return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso });
|
||||
}
|
||||
|
||||
export function forgejoChangeRequest(pr: typeof ForgejoPullRequest.Type) {
|
||||
return {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.html_url,
|
||||
author: forgejoActor(pr.user),
|
||||
headBranch: pr.head.ref,
|
||||
baseBranch: pr.base.ref,
|
||||
headRepositoryNameWithOwner: pr.head.repo?.full_name ?? null,
|
||||
state: pr.merged ? "merged" : pr.state === "closed" ? "closed" : "open",
|
||||
isDraft: pr.draft ?? /^(?:\[WIP\]|WIP:)/i.test(pr.title),
|
||||
// A false value also covers drafts and unfinished or failed conflict checks.
|
||||
mergeability: pr.mergeable === true ? "mergeable" : "unknown",
|
||||
additions: pr.additions ?? 0,
|
||||
deletions: pr.deletions ?? 0,
|
||||
createdAt: toIsoUtc(pr.created_at),
|
||||
updatedAt: toIsoUtc(pr.updated_at),
|
||||
closedAt: pr.closed_at === null ? null : toIsoUtc(pr.closed_at),
|
||||
mergedAt: pr.merged_at === null ? null : toIsoUtc(pr.merged_at),
|
||||
reviewRequestLogins: (pr.requested_reviewers ?? []).map((user) => user.login),
|
||||
labels: (pr.labels ?? []).map((label) => ({ name: label.name, color: label.color ?? null })),
|
||||
} satisfies ProviderChangeRequest;
|
||||
}
|
||||
|
||||
export function forgejoComment(comment: typeof ForgejoComment.Type): PullRequestComment {
|
||||
return {
|
||||
id: String(comment.id),
|
||||
kind: "issue-comment",
|
||||
author: forgejoActor(comment.user),
|
||||
body: comment.body,
|
||||
createdAt: toIsoUtc(comment.created_at),
|
||||
url: comment.html_url || null,
|
||||
path: null,
|
||||
reviewState: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function forgejoReview(review: typeof ForgejoReview.Type): PullRequestComment {
|
||||
return {
|
||||
id: `review:${review.id}`,
|
||||
kind: "review",
|
||||
author: forgejoActor(review.user),
|
||||
body: review.body,
|
||||
createdAt: toIsoUtc(review.submitted_at),
|
||||
url: review.html_url || null,
|
||||
path: null,
|
||||
reviewState:
|
||||
review.state === "REQUEST_CHANGES"
|
||||
? "CHANGES_REQUESTED"
|
||||
: review.state === "COMMENT"
|
||||
? "COMMENTED"
|
||||
: review.state,
|
||||
};
|
||||
}
|
||||
|
||||
export function forgejoReviewThread(
|
||||
comment: typeof ForgejoReviewComment.Type,
|
||||
): PullRequestReviewThread {
|
||||
const oldSide = comment.position === 0 && comment.original_position > 0;
|
||||
const line = oldSide ? comment.original_position : comment.position;
|
||||
return {
|
||||
id: String(comment.id),
|
||||
path: comment.path,
|
||||
line: line > 0 ? line : null,
|
||||
side: oldSide ? "left" : "right",
|
||||
isResolved: comment.resolver !== null,
|
||||
isOutdated: false,
|
||||
comments: [forgejoComment(comment)],
|
||||
};
|
||||
}
|
||||
|
||||
export function forgejoCommit(commit: typeof ForgejoCommit.Type): PullRequestCommit {
|
||||
const author = forgejoActor(commit.author);
|
||||
return {
|
||||
oid: commit.sha,
|
||||
messageHeadline: commit.commit.message.split("\n")[0] ?? "",
|
||||
committedDate: toIsoUtc(commit.commit.committer.date),
|
||||
authors: author ? [author] : [],
|
||||
...(commit.stats
|
||||
? { additions: commit.stats.additions, deletions: commit.stats.deletions }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function forgejoChecks(
|
||||
statuses: ReadonlyArray<typeof ForgejoStatus.Type>,
|
||||
): ReadonlyArray<PullRequestCheck> {
|
||||
return dedupeChecks(
|
||||
statuses.map((status) => ({
|
||||
workflowName: null,
|
||||
at: status.updated_at,
|
||||
check: {
|
||||
name: status.context || "check",
|
||||
description: status.description || null,
|
||||
url: status.target_url || null,
|
||||
status:
|
||||
status.status === "success"
|
||||
? "success"
|
||||
: status.status === "failure" || status.status === "error"
|
||||
? "failure"
|
||||
: "pending",
|
||||
},
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export const FORGEJO_REACTIONS: Record<PullRequestReactionContent, string> = {
|
||||
"thumbs-up": "+1",
|
||||
"thumbs-down": "-1",
|
||||
laugh: "laugh",
|
||||
hooray: "hooray",
|
||||
confused: "confused",
|
||||
heart: "heart",
|
||||
rocket: "rocket",
|
||||
eyes: "eyes",
|
||||
};
|
||||
export function forgejoReactions(
|
||||
reactions: ReadonlyArray<typeof ForgejoReaction.Type>,
|
||||
viewer: string,
|
||||
): ReadonlyArray<PullRequestReaction> {
|
||||
return Object.entries(FORGEJO_REACTIONS).flatMap(([content, emoji]) => {
|
||||
const matching = reactions.filter((reaction) => reaction.content === emoji);
|
||||
return matching.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
content: content as PullRequestReactionContent,
|
||||
count: matching.length,
|
||||
actors: matching.flatMap((reaction) =>
|
||||
reaction.user?.login && reaction.user.login !== viewer ? [reaction.user.login] : [],
|
||||
),
|
||||
viewerHasReacted: matching.some((reaction) => reaction.user?.login === viewer),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user