CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 | /**
* Web file editor — create and edit files directly in the browser.
*/
import { Hono } from "hono";
import { Layout } from "../views/layout";
import { RepoHeader, RepoNav, Breadcrumb } from "../views/components";
import {
Container,
Flex,
Form,
FormGroup,
Input,
TextArea,
Button,
LinkButton,
EmptyState,
Text,
} from "../views/ui";
import {
getBlob,
getDefaultBranch,
getRepoPath,
repoExists,
} from "../git/repository";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { join } from "path";
const editor = new Hono<AuthEnv>();
editor.use("*", softAuth);
// New file form
editor.get("/:owner/:repo/new/:ref{.+$}", requireAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const refAndPath = c.req.param("ref");
// Parse ref — use first segment
const slashIdx = refAndPath.indexOf("/");
const ref = slashIdx === -1 ? refAndPath : refAndPath.slice(0, slashIdx);
const dirPath = slashIdx === -1 ? "" : refAndPath.slice(slashIdx + 1);
return c.html(
<Layout title={`New file — ${owner}/${repo}`} user={user}>
<RepoHeader owner={owner} repo={repo} />
<RepoNav owner={owner} repo={repo} active="code" />
<Container maxWidth={900}>
<h2 style="margin-bottom: 16px">Create new file</h2>
<form method="post" action={`/${owner}/${repo}/new/${ref}`}>
<input type="hidden" name="dir_path" value={dirPath} />
<FormGroup label="File path">
<Flex align="center" gap={4}>
{dirPath && (
<Text muted size={14}>
{dirPath}/
</Text>
)}
<Input
name="filename"
required
placeholder="filename.ts"
style="flex: 1"
autocomplete="off"
/>
</Flex>
</FormGroup>
<FormGroup label="Content">
<TextArea
name="content"
rows={20}
placeholder="Enter file content..."
mono
style="line-height: 1.5; tab-size: 2"
/>
</FormGroup>
<FormGroup label="Commit message">
<Input
name="message"
placeholder="Create new file"
required
/>
</FormGroup>
<Button type="submit" variant="primary">
Commit new file
</Button>
</Form>
</Container>
</Layout>
);
});
// Create file via commit
editor.post("/:owner/:repo/new/:ref", requireAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const ref = c.req.param("ref");
const body = await c.req.parseBody();
const dirPath = String(body.dir_path || "").trim();
const filename = String(body.filename || "").trim();
const content = String(body.content || "");
const message = String(body.message || `Create ${filename}`).trim();
if (!filename) return c.redirect(`/${owner}/${repo}`);
const fullPath = dirPath ? `${dirPath}/${filename}` : filename;
// Use git hash-object + update-index + write-tree + commit-tree
const repoDir = getRepoPath(owner, repo);
const run = async (cmd: string[], cwd: string, stdin?: string) => {
const proc = Bun.spawn(cmd, {
cwd,
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();
};
// Hash the new file content
const blobSha = await run(
["git", "hash-object", "-w", "--stdin"],
repoDir,
content
);
// Read current tree
const currentTreeSha = await run(
["git", "rev-parse", `${ref}^{tree}`],
repoDir
);
// Read current tree and add new entry
const treeContent = await run(["git", "ls-tree", "-r", ref], repoDir);
const entries = treeContent
.split("\n")
.filter(Boolean)
.map((line) => line + "\n")
.join("");
const newEntry = `100644 blob ${blobSha}\t${fullPath}\n`;
const newTreeSha = await run(
["git", "mktree"],
repoDir,
entries + newEntry
);
// Get parent commit
const parentSha = await run(
["git", "rev-parse", ref],
repoDir
);
// Create commit
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 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;
// Update branch ref
await run(
["git", "update-ref", `refs/heads/${ref}`, commitSha],
repoDir
);
return c.redirect(`/${owner}/${repo}/blob/${ref}/${fullPath}`);
});
// Edit file form
editor.get("/:owner/:repo/edit/:ref{.+$}", requireAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const refAndPath = c.req.param("ref");
// Parse ref/path
const slashIdx = refAndPath.indexOf("/");
if (slashIdx === -1) return c.text("Not found", 404);
const ref = refAndPath.slice(0, slashIdx);
const filePath = refAndPath.slice(slashIdx + 1);
const blob = await getBlob(owner, repo, ref, filePath);
if (!blob || blob.isBinary) {
return c.html(
<Layout title="Cannot edit" user={user}>
<EmptyState title={blob?.isBinary ? "Cannot edit binary file" : "File not found"} />
</Layout>,
404
);
}
return c.html(
<Layout title={`Editing ${filePath} — ${owner}/${repo}`} user={user}>
<RepoHeader owner={owner} repo={repo} />
<RepoNav owner={owner} repo={repo} active="code" />
<Breadcrumb owner={owner} repo={repo} ref={ref} path={filePath} />
<div style="max-width: 900px">
<form method="post" action={`/${owner}/${repo}/edit/${ref}/${filePath}`}>
<div class="form-group">
<textarea
name="content"
rows={25}
value={blob.content}
mono
style="line-height: 1.5; tab-size: 2; width: 100%"
/>
</FormGroup>
<FormGroup label="Commit message">
<Input
name="message"
placeholder={`Update ${filePath.split("/").pop()}`}
required
/>
</FormGroup>
<Flex gap={8}>
<Button type="submit" variant="primary">
Commit changes
</Button>
<LinkButton href={`/${owner}/${repo}/blob/${ref}/${filePath}`}>
Cancel
</LinkButton>
</Flex>
</Form>
</Container>
</Layout>
);
});
// Save edited file
editor.post("/:owner/:repo/edit/:ref{.+$}", requireAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const refAndPath = c.req.param("ref");
const slashIdx = refAndPath.indexOf("/");
if (slashIdx === -1) return c.redirect(`/${owner}/${repo}`);
const ref = refAndPath.slice(0, slashIdx);
const filePath = refAndPath.slice(slashIdx + 1);
const body = await c.req.parseBody();
const content = String(body.content || "");
const message = String(
body.message || `Update ${filePath.split("/").pop()}`
).trim();
const repoDir = getRepoPath(owner, repo);
const run = async (cmd: string[], cwd: string, stdin?: string) => {
const proc = Bun.spawn(cmd, {
cwd,
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();
};
// Hash new content
const blobSha = await run(
["git", "hash-object", "-w", "--stdin"],
repoDir,
content
);
// Read current tree, replace the file
const treeContent = await run(["git", "ls-tree", "-r", ref], repoDir);
const lines = treeContent.split("\n").filter(Boolean);
const updated = lines
.map((line) => {
const parts = line.match(/^(\d+) (\w+) ([0-9a-f]+)\t(.+)$/);
if (parts && parts[4] === filePath) {
return `${parts[1]} blob ${blobSha}\t${parts[4]}`;
}
return line;
})
.join("\n") + "\n";
const newTreeSha = await run(["git", "mktree"], repoDir, updated);
const parentSha = await run(["git", "rev-parse", ref], repoDir);
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 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/${ref}`, commitSha],
repoDir
);
return c.redirect(`/${owner}/${repo}/blob/${ref}/${filePath}`);
});
export default editor;
|