1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
|
import { Hono } from "hono";
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import {
prComments,
pullRequests,
repositories,
users,
} from "../db/schema";
import { requireAuth, softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { getBlob, getRepoPath } from "../git/repository";
import {
applySuggestionToContent,
extractSuggestions,
} from "../lib/code-suggestions";
const codeSuggestions = new Hono<AuthEnv>();
async function resolveRepo(ownerName: string, repoName: string) {
try {
const [owner] = await db
.select()
.from(users)
.where(eq(users.username, ownerName))
.limit(1);
if (!owner) return null;
const [repo] = await db
.select()
.from(repositories)
.where(
and(
eq(repositories.ownerId, owner.id),
eq(repositories.name, repoName)
)
)
.limit(1);
if (!repo) return null;
return { owner, repo };
} catch {
return null;
}
}
codeSuggestions.post(
"/:owner/:repo/pulls/:number/comments/:commentId/apply-suggestion",
softAuth,
requireAuth,
async (c) => {
const { owner: ownerName, repo: repoName, number, commentId } =
c.req.param();
const user = c.get("user")!;
const prNumber = parseInt(number, 10);
if (!Number.isFinite(prNumber)) return c.text("bad pr number", 400);
const resolved = await resolveRepo(ownerName, repoName);
if (!resolved) return c.text("not found", 404);
if (
resolved.repo.isPrivate &&
user.id !== resolved.owner.id
) {
return c.text("not found", 404);
}
const [pr] = await db
.select()
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, resolved.repo.id),
eq(pullRequests.number, prNumber)
)
)
.limit(1);
if (!pr) return c.text("pr not found", 404);
if (pr.state !== "open") {
return c.redirect(`/${ownerName}/${repoName}/pulls/${prNumber}`);
}
const [comment] = await db
.select()
.from(prComments)
.where(
and(
eq(prComments.id, commentId),
eq(prComments.pullRequestId, pr.id)
)
)
.limit(1);
if (!comment) return c.text("comment not found", 404);
if (!comment.filePath || !comment.lineNumber) {
return c.text("comment has no file anchor", 400);
}
const allowed =
user.id === resolved.owner.id ||
user.id === pr.authorId ||
user.id === comment.authorId;
if (!allowed) return c.text("forbidden", 403);
const form = await c.req.parseBody().catch(() => ({}));
const rawIdx = (form as Record<string, unknown>).index;
const idx =
typeof rawIdx === "string" && rawIdx.trim() !== ""
? parseInt(rawIdx, 10)
: 0;
const blocks = extractSuggestions(comment.body);
if (!Number.isFinite(idx) || idx < 0 || idx >= blocks.length) {
return c.text("no such suggestion", 400);
}
const suggestion = blocks[idx].content;
const headRef = pr.headBranch;
let blob: { content: string; isBinary: boolean } | null = null;
try {
blob = await getBlob(
ownerName,
repoName,
headRef,
comment.filePath
);
} catch {
blob = null;
}
if (!blob || blob.isBinary) {
return c.text("file missing or binary", 400);
}
const applied = applySuggestionToContent({
content: blob.content,
startLine: comment.lineNumber,
endLine: comment.lineNumber,
suggestion,
});
if (!applied.ok) {
return c.text(`apply failed: ${applied.reason}`, 400);
}
const repoDir = getRepoPath(ownerName, repoName);
const run = async (cmd: string[], stdin?: string) => {
const proc = Bun.spawn(cmd, {
cwd: repoDir,
stdout: "pipe",
stderr: "pipe",
stdin: stdin !== undefined ? "pipe" : undefined,
});
if (stdin !== undefined && proc.stdin) {
proc.stdin.write(new TextEncoder().encode(stdin));
proc.stdin.end();
}
const stdout = await new Response(proc.stdout).text();
await proc.exited;
return stdout.trim();
};
try {
const blobSha = await run(
["git", "hash-object", "-w", "--stdin"],
applied.content
);
const treeContent = await run(["git", "ls-tree", "-r", headRef]);
const updated =
treeContent
.split("\n")
.filter(Boolean)
.map((line) => {
const parts = line.match(/^(\d+) (\w+) ([0-9a-f]+)\t(.+)$/);
if (parts && parts[4] === comment.filePath) {
return `${parts[1]} blob ${blobSha}\t${parts[4]}`;
}
return line;
})
.join("\n") + "\n";
const newTreeSha = await run(["git", "mktree"], updated);
const parentSha = await run(["git", "rev-parse", headRef]);
const env = {
GIT_AUTHOR_NAME: user.displayName || user.username,
GIT_AUTHOR_EMAIL: user.email,
GIT_COMMITTER_NAME: user.displayName || user.username,
GIT_COMMITTER_EMAIL: user.email,
};
const message = `Apply suggestion from #${prNumber}\n\nCo-authored-by: ${
user.displayName || user.username
} <${user.email}>`;
const commitProc = Bun.spawn(
["git", "commit-tree", newTreeSha, "-p", parentSha, "-m", message],
{
cwd: repoDir,
stdout: "pipe",
stderr: "pipe",
env: { ...process.env, ...env },
}
);
const commitSha = (await new Response(commitProc.stdout).text()).trim();
await commitProc.exited;
await run([
"git",
"update-ref",
`refs/heads/${headRef}`,
commitSha,
]);
} catch (err) {
console.error("[apply-suggestion]", err);
return c.text("commit failed", 500);
}
return c.redirect(
`/${ownerName}/${repoName}/pulls/${prNumber}#comment-${comment.id}`
);
}
);
export default codeSuggestions;
|