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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
|
import { Hono } from "hono";
import { eq, and } from "drizzle-orm";
import { db } from "../db";
import {
repositories,
users,
pullRequests,
mergeQueueEntries,
branchProtection,
} from "../db/schema";
import { Layout } from "../views/layout";
import { RepoHeader } from "../views/components";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
listBranches,
getDefaultBranch,
renameBranch as gitRenameBranch,
setHeadBranch,
} from "../git/repository";
import {
planRename,
branchValidationMessage,
shouldRewriteProtectionPattern,
} from "../lib/branch-rename";
import { audit } from "../lib/notify";
const branchRenameRoutes = new Hono<AuthEnv>();
branchRenameRoutes.use("*", softAuth);
async function resolveOwned(
c: Parameters<
Parameters<typeof branchRenameRoutes.get>[1]
>[0],
ownerName: string,
repoName: string
): Promise<{ owner: typeof users.$inferSelect; repo: typeof repositories.$inferSelect } | null> {
try {
const [owner] = await db
.select()
.from(users)
.where(eq(users.username, ownerName))
.limit(1);
if (!owner) return null;
const user = c.get("user");
if (!user || user.id !== owner.id) 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;
}
}
branchRenameRoutes.get(
"/:owner/:repo/settings/branches",
requireAuth,
async (c) => {
const { owner: ownerName, repo: repoName } = c.req.param();
const user = c.get("user")!;
const error = c.req.query("error");
const success = c.req.query("success");
const resolved = await resolveOwned(c, ownerName, repoName);
if (!resolved) {
return c.html(
<Layout title="Unauthorized" user={user}>
<div class="empty-state">
<h2>Unauthorized</h2>
<p>Only the repository owner can manage branches.</p>
</div>
</Layout>,
403
);
}
const branches = await listBranches(ownerName, repoName);
const defaultBranch =
(await getDefaultBranch(ownerName, repoName)) ||
resolved.repo.defaultBranch;
return c.html(
<Layout
title={`Branches — ${ownerName}/${repoName}`}
user={user}
>
<RepoHeader owner={ownerName} repo={repoName} />
<div style="max-width: 720px">
<h2 style="margin-bottom: 16px">Branches</h2>
{error && (
<div class="auth-error">{decodeURIComponent(error)}</div>
)}
{success && (
<div class="auth-success">{decodeURIComponent(success)}</div>
)}
<p style="color: var(--text-muted); font-size: 13px; margin-bottom: 16px">
Renaming a branch updates open PRs that target it, branch
protection rules with an exact-match pattern, and the default
branch pointer (if applicable). History is preserved — only
the ref name changes.
</p>
{branches.length === 0 ? (
<div class="empty-state">
<p>No branches yet. Push some commits to get started.</p>
</div>
) : (
<table style="width: 100%; border-collapse: collapse">
<thead>
<tr>
<th style="text-align: left; padding: 8px; border-bottom: 1px solid var(--border)">
Branch
</th>
<th style="text-align: right; padding: 8px; border-bottom: 1px solid var(--border)">
Rename
</th>
</tr>
</thead>
<tbody>
{branches.map((b) => (
<tr>
<td style="padding: 8px; border-bottom: 1px solid var(--border); font-family: var(--font-mono); font-size: 13px">
{b}
{b === defaultBranch && (
<span
class="issue-badge badge-open"
style="margin-left: 8px; font-size: 10px; padding: 1px 6px"
>
default
</span>
)}
</td>
<td style="padding: 8px; border-bottom: 1px solid var(--border); text-align: right">
<form
method="POST"
action={`/${ownerName}/${repoName}/settings/branches/rename`}
style="display: inline-flex; gap: 6px"
>
<input type="hidden" name="from" value={b} />
<input
type="text"
name="to"
placeholder="new name"
required
style="padding: 4px 8px; font-size: 12px; width: 180px"
/>
<button
type="submit"
class="btn"
style="padding: 4px 10px; font-size: 12px"
>
Rename
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</Layout>
);
}
);
branchRenameRoutes.post(
"/:owner/:repo/settings/branches/rename",
requireAuth,
async (c) => {
const { owner: ownerName, repo: repoName } = c.req.param();
const user = c.get("user")!;
const body = await c.req.parseBody();
const from = String(body.from || "").trim();
const to = String(body.to || "").trim();
const base = `/${ownerName}/${repoName}/settings/branches`;
const resolved = await resolveOwned(c, ownerName, repoName);
if (!resolved) {
return c.redirect(`/${ownerName}/${repoName}`);
}
const existing = await listBranches(ownerName, repoName);
const defaultBranch =
(await getDefaultBranch(ownerName, repoName)) ||
resolved.repo.defaultBranch;
const plan = planRename({
from,
to,
existingBranches: existing,
defaultBranch,
});
if (!plan.ok) {
const msg = (() => {
switch (plan.reason) {
case "same_name":
return "New name must differ from the current name.";
case "from_missing":
return `Branch '${from}' does not exist.`;
case "to_exists":
return `A branch named '${to}' already exists.`;
case "invalid_from":
return `Source name is invalid: ${
plan.detail ? branchValidationMessage(plan.detail) : "invalid"
}`;
case "invalid_to":
return plan.detail
? branchValidationMessage(plan.detail)
: "Invalid branch name.";
}
})();
return c.redirect(`${base}?error=${encodeURIComponent(msg)}`);
}
const moved = await gitRenameBranch(ownerName, repoName, plan.from, plan.to);
if (!moved) {
return c.redirect(
`${base}?error=${encodeURIComponent("git rename failed — check repository state.")}`
);
}
let cascadeErr: string | null = null;
try {
if (plan.updatesDefault) {
await setHeadBranch(ownerName, repoName, plan.to);
await db
.update(repositories)
.set({ defaultBranch: plan.to, updatedAt: new Date() })
.where(eq(repositories.id, resolved.repo.id));
}
await db
.update(pullRequests)
.set({ baseBranch: plan.to, updatedAt: new Date() })
.where(
and(
eq(pullRequests.repositoryId, resolved.repo.id),
eq(pullRequests.baseBranch, plan.from)
)
);
await db
.update(pullRequests)
.set({ headBranch: plan.to, updatedAt: new Date() })
.where(
and(
eq(pullRequests.repositoryId, resolved.repo.id),
eq(pullRequests.headBranch, plan.from)
)
);
await db
.update(mergeQueueEntries)
.set({ baseBranch: plan.to })
.where(
and(
eq(mergeQueueEntries.repositoryId, resolved.repo.id),
eq(mergeQueueEntries.baseBranch, plan.from)
)
);
const protections = await db
.select()
.from(branchProtection)
.where(eq(branchProtection.repositoryId, resolved.repo.id));
for (const p of protections) {
if (shouldRewriteProtectionPattern(p.pattern, plan.from)) {
try {
await db
.update(branchProtection)
.set({ pattern: plan.to, updatedAt: new Date() })
.where(eq(branchProtection.id, p.id));
} catch {
}
}
}
} catch (err) {
cascadeErr =
err instanceof Error ? err.message : "cascade update failed";
}
try {
await audit({
userId: user.id,
repositoryId: resolved.repo.id,
action: "branch.rename",
targetId: resolved.repo.id,
metadata: {
from: plan.from,
to: plan.to,
updatesDefault: plan.updatesDefault,
},
});
} catch {
}
if (cascadeErr) {
return c.redirect(
`${base}?error=${encodeURIComponent(
`Branch renamed but some cascades failed: ${cascadeErr}`
)}`
);
}
return c.redirect(
`${base}?success=${encodeURIComponent(
`Renamed '${plan.from}' → '${plan.to}'.`
)}`
);
}
);
export default branchRenameRoutes;
|