A member edits a file in the browser: a pencil, /edit/main/<path>, and a commit to main or to a new branch with a pull
Jonas Templestein, 2026-11-27 10:28 UTC · e91d55d167d528652170c69d11d8da36f78c7049 · parent 7f307d7
13 files changed
- M README.md
- M app.ts
- M package.json
- M pages.ts
- M pnpm-lock.yaml
- A public/branch-commit.js
- M public/page.css
- M public/page.js
- M tests/app.test.mjs
- A tests/branch-commit.test.mjs
- A tests/git-http.mjs
- M tests/pages.test.mjs
- M tests/serve.mjs
M README.md
@@ -9,6 +9,7 @@ / the repos /repos/<name> the repo's files and its README /repos/<name>/tree/main/<path> a folder, or a file +/repos/<name>/edit/main/<path> a file in a box, for a member to change and commit /repos/<name>/commits the newest commits /repos/<name>/commit/<oid> one commit: what it changed /repos/<name>/branches the branches, each with its pull or a compare link @@ -61,6 +62,22 @@ git push origin my-fix ``` +## Edit a file in the browser + +A member's page of a file has a pencil. It opens `/repos/<name>/edit/main/<path>`: the file's +text in a box, a commit message to change, and the choice of where the commit goes. + +- **Commit directly to main**: one call of the member's own `itx` + (`repos.get(repo).commitFiles`), pinned to the commit that the page read. Main is what the mind + runs a few seconds later. +- **Create a new branch and open a pull**: the page itself makes the commit and pushes the branch + as git does (`public/branch-commit.js`: the mind's repo API commits to main alone), then opens + the pull. + +The server has no write path for either: the first is the platform's, the second is the same +push that a member's git makes, and the repo's log says who pushed. A push from a page is taken +from this app's own page alone. + A repo's pulls are events on the repo's own context: `pulls.ts` says which. An agent opens a pull or comments by appending the same events, and merges with `itx.config.pullMerge(repo, number)`. @@ -70,6 +87,7 @@ - `pages.ts`: each page, as plain HTML - `pulls.ts`: what a pull is, and the merge - `public/`: what the browser runs. There is no build. +- `public/branch-commit.js`: the commit on a new branch that a member's page makes of an edit ## Try a change
M app.ts
@@ -4,6 +4,7 @@ // GET / the repos // GET /repos/<name> the repo's files and its README // GET /repos/<name>/tree/main/<path> a folder of it, or a file +// GET /repos/<name>/edit/main/<path> a file in a box, for a member to change and commit // GET /repos/<name>/commits its newest commits // GET /repos/<name>/commit/<oid> one commit: what it changed // GET /repos/<name>/branches its branches, each with its pull or a compare link @@ -24,7 +25,10 @@ // // WHO MAY WRITE. A member alone opens a pull, comments and merges: the page does each through the // member's own `itx` (public/mind.js, over the socket that `host.auth.memberPage` answers), so the -// platform records who did it. This file writes nothing of a pull. +// platform records who did it. This file writes nothing of a pull. A member's edit of a file is +// written the same way: a commit to main is `repos.get(repo).commitFiles` of the member's own +// itx, and a commit to a new branch is a push from the member's page to the remote below, which +// takes it as it takes any member's push. // // WHO GIT IS. The platform says it, as for a page: git sends a token of the mind for this one // host, which the `iterate` CLI's credential helper hands it (`npx iterate git setup <host>`), @@ -70,6 +74,7 @@ commitPage, commitsPage, comparePage, + editPage, nameOf, note, page, @@ -169,9 +174,13 @@ const me = signIn ? null : host.auth.principal(request)?.email?.split("@")[0] || "a member"; const view = { url, repo, isPublic, me }; const rest = match[3] || ""; + // the page that edits a file is a member's, on a public repo too + if (match[2] === "edit" && signIn) return signIn; try { using itx = host.getItx(); const handle = itx.repos.get(repo); + if (match[2] === "edit") + return await editPage(view, handle, rest, host.auth.principal(request)?.email || null); if (match[2] === "commits") return await commitsPage(view, handle); if (match[2] === "commit") return await commitPage(view, handle, itx, rest); if (match[2] === "branches") return await branchesPage(view, handle, itx); @@ -211,6 +220,13 @@ if (service !== "git-upload-pack" && service !== "git-receive-pack") return new Response("git: only smart HTTP is served here\n", { status: 403 }); const write = service === "git-receive-pack"; + // A PUSH FROM A PAGE IS THIS APP'S OWN PAGE'S. A browser says where a request comes from + // (`sec-fetch-site`), and git says nothing. A member's page pushes the branch of an edit + // (public/branch-commit.js) with the member's sign-in, which the browser sends by itself: a page + // of another site must not push with it. + const from = request.headers.get("sec-fetch-site"); + if (write && from && from !== "same-origin") + return new Response("git: a page of another site does not push here\n", { status: 403 }); // a member, as the boundary stamped them; another mind's stamp is no member's const stamped = host.auth.principal(request);
M package.json
@@ -11,6 +11,7 @@ }, "devDependencies": { "@cloudflare/workers-types": "^5.20261103.1", + "isomorphic-git": "1.44.19", "iterate": "link:../kernel/core/lib", "typescript": "^7.0.2", "zod": "4.6.5"
M pages.ts
@@ -12,6 +12,11 @@ // // Only `main` and the branches of open pulls are shown, and a file as text. A page shows people // by the name before the `@` of their address, and no address. +// +// A MEMBER EDITS A FILE on `/repos/<name>/edit/main/<path>`, GitHub's address for it: the file's +// text in a box, and under it the box that commits. The page here only reads, as every page: the +// commit is the member's own, made by the script (public/page.js says how, for main and for a +// new branch with a pull). import type { RepoLogEntry } from "iterate/api"; import type { IterateConfigEntrypoint } from "iterate/sdk"; import { z } from "zod"; @@ -29,7 +34,7 @@ /** A repo's pages: its name, then what of it. */ export const PAGE_PATH = - /^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|commits|commit|branches|pulls|pull|compare)(?:\/(.*))?)?$/; + /^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|edit|commits|commit|branches|pulls|pull|compare)(?:\/(.*))?)?$/; /** How many commits the list shows, and how far back a short oid is looked for. */ const COMMITS_SHOWN = 100; @@ -38,6 +43,9 @@ * are named with no diff. */ const DIFF_CHARACTERS_SHOWN = 600_000; +/** The largest file that the edit page offers, in characters: a box in a page holds no more well. */ +const EDIT_CHARACTERS = 1_000_000; + /** One file that differs between two commits. `sides` is its text before and after; null when * the page shows no diff, and `note` says why. */ const Change = z.object({ @@ -164,9 +172,78 @@ ? `<p class="note"><a href="${here}">As it reads</a></p>` : `<p class="note"><a href="${here}?plain">Its source</a></p>` : ""; - return other + fileText(path, text, plain); + // the pencil, for a member: GitHub's address for the page that edits this file + const pencil = view.me + ? `<p class="note"><a class="pencil" href="${editHref(view.repo, path)}" title="Edit this file">${PENCIL} Edit</a></p>` + : ""; + return other + pencil + fileText(path, text, plain); } +/** `/repos/<name>/edit/main/<path>`, for a member: the file's text in a box that the member + * changes, and the place where the script draws the box that commits. `email` is the member's + * address, which a commit on a new branch names as its author; the page shows it to nobody else. */ +export async function editPage(view: View, handle: Repo, rest: string, email: string | null) { + const { repo } = view; + const [branch, ...segments] = rest.split("/"); + if (branch !== "main") + return page(view, 404, "code", "Not found", note("Only main is edited here."), {}); + const path = segments.filter(Boolean).map(decodeURIComponent).join("/"); + const { commitOid, paths } = await handle.listFiles(); + if (!commitOid || !paths.includes(path)) { + const missing = note(`${nameOf(repo)} has no file ${path} on main.`); + return page(view, 404, "code", "Not found", missing, {}); + } + let text: string | null; + try { + text = await handle.readFile(path, { commitOid }); + } catch (error) { + if (/is not text/.test(error instanceof Error ? error.message : "")) text = null; + else throw error; + } + const file = `<a href="${treeHref(repo, path)}">${esc(path)}</a>`; + const title = `Edit ${path} · ${nameOf(repo)}`; + // A box in a page reads every line ending as a line feed. A file that ends every line with + // CR LF gets them back at the commit; one that mixes the two would be changed whole. + const lineFeeds = text === null ? 0 : text.split("\n").length - 1; + const returns = text === null ? 0 : text.split("\r").length - 1; + const crlf = returns > 0 && returns === lineFeeds && returns === text!.split("\r\n").length - 1; + const refusal = + text === null + ? "This file is not text, so it is not edited here. Change it in a clone." + : text.length > EDIT_CHARACTERS + ? "This file is too large to edit here. Change it in a clone." + : returns > 0 && !crlf + ? "This file mixes line endings, so it is not edited here. Change it in a clone." + : null; + const at = `<span class="at">main at <a href="${esc(repo)}/commit/${commitOid}"><code>${commitOid.slice(0, 7)}</code></a></span>`; + const head = `<p class="crumbs">Edit ${file}${at}</p>`; + if (refusal !== null || text === null) + return page(view, 200, "code", title, `<article class="edit">${head}${note(refusal || "")}</article>`, {}); + const shown = crlf ? text.replace(/\r\n/g, "\n") : text; + const main = [ + `<article class="edit">${head}`, + // a line break right after the tag is not part of a textarea's text: the file's own first + // line break would be lost without it + `<textarea id="edit-text" spellcheck="false" autocapitalize="off" autocomplete="off" aria-label="${esc(path)}">\n${esc(shown)}</textarea>`, + `<div id="commit"><p class="note">The box that commits is drawn by this page's script.</p></div></article>`, + ].join(""); + // a name for the branch that no branch has yet: the member's name, then the file's + const taken = new Set((await handle.branches()).map(({ name }) => name)); + const slug = (words: string) => words.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase(); + const stem = `${slug(view.me || "") || "member"}/edit-${slug(path.split("/").at(-1)!) || "file"}`; + let suggested = stem; + for (let count = 2; taken.has(suggested); count += 1) suggested = `${stem}-${count}`; + const edit = { + path, + commitOid, + crlf, + branch: suggested, + // as a squash names a pull's author (pulls.ts): the name before the `@`, and the address + author: email ? { name: view.me || email, email } : null, + }; + return page(view, 200, "code", title, main, { edit }); +} + /** A file's text as a `<pre>`, marked for the script: `data-markdown` is drawn as markdown (its * links are read against `data-dir`, the file's folder), `data-file` with the file's colours. */ function fileText(path: string, text: string, plain: boolean) { @@ -643,6 +720,11 @@ /** The page of a file or a folder; the repo's own page for its root. */ const treeHref = (repo: string, path: string) => esc(path ? `${repo}/tree/main/${path.split("/").map(encodeURIComponent).join("/")}` : repo); +/** The page that edits a file of main. */ +const editHref = (repo: string, path: string) => + esc(`${repo}/edit/main/${path.split("/").map(encodeURIComponent).join("/")}`); +/** A pencil (lucide's), drawn in the text's colour. */ +const PENCIL = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/></svg>`; /** A moment as `2026-11-24 15:39 UTC`: the same for every reader. */ const utcStamp = (timestamp: number) => `${new Date(timestamp).toISOString().slice(0, 16).replace("T", " ")} UTC`; @@ -668,5 +750,8 @@ "lucide-react": "https://esm.iterate.com/lucide-react@1.48.0?external=react,react-dom", "@pierre/trees/react": "https://esm.iterate.com/@pierre/trees@1.0.0/react?external=react,react-dom", "@pierre/diffs/react": "https://esm.iterate.com/@pierre/diffs@1.7.1/react?external=react,react-dom", + // git in the browser, for a member's commit on a new branch (public/branch-commit.js) + "isomorphic-git": "https://esm.iterate.com/isomorphic-git@1.44.19", + "isomorphic-git/http/web": "https://esm.iterate.com/isomorphic-git@1.44.19/http/web", }, });
M pnpm-lock.yaml
@@ -15,6 +15,9 @@ '@cloudflare/workers-types': specifier: ^5.20261103.1 version: 5.20261124.2 + isomorphic-git: + specifier: 1.44.19 + version: 1.44.19 iterate: specifier: link:../kernel/core/lib version: link:../kernel/core/lib @@ -150,11 +153,183 @@ cpu: [x64] os: [win32] + async-lock@1.5.0: + resolution: {integrity: sha512-JgULma1mWaHlyJ67lvicyel5Cq+k55bXafE0gyvJBdHkH0vdE/IGGDF1glNyRInisNS6pZL2oho96S6Hw68kfQ==} + + available-typed-arrays@1.0.7: + resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} + engines: {node: '>= 0.4'} + + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + call-bind@1.0.9: + resolution: {integrity: sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==} + engines: {node: '>= 0.4'} + + call-bound@1.0.4: + resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} + engines: {node: '>= 0.4'} + + clean-git-ref@2.0.1: + resolution: {integrity: sha512-bLSptAy2P0s6hU4PzuIMKmMJJSE6gLXGH1cntDu7bWJUksvuM+7ReOK61mozULErYvP6a15rnYl0zFDef+pyPw==} + + crc-32@1.2.2: + resolution: {integrity: sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==} + engines: {node: '>=0.8'} + hasBin: true + + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + diff3@0.0.3: + resolution: {integrity: sha512-iSq8ngPOt0K53A6eVr4d5Kn6GNrM2nQZtC740pzIriHtn4pOQ2lyzEXQMBeVcWERN0ye7fhBsk9PbLLQOnUx/g==} + + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + + for-each@0.3.5: + resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} + engines: {node: '>= 0.4'} + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + is-callable@1.2.7: + resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==} + engines: {node: '>= 0.4'} + + is-typed-array@1.1.15: + resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} + engines: {node: '>= 0.4'} + + isarray@2.0.5: + resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==} + + isomorphic-git@1.44.19: + resolution: {integrity: sha512-s4g8B1KBBYMop1dU/QqratyTjdhNTPMTP9dOBurGto8lBg6fRD4J5osy9fEY+vOj8W4/QpYMs6bzwhtM5K+6Vg==} + engines: {node: '>=14.17'} + hasBin: true + + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + minimisted@2.0.1: + resolution: {integrity: sha512-1oPjfuLQa2caorJUM8HV8lGgWCc0qqAO1MNv/k05G4qslmsndV/5WdNZrqCiyqiz3wohia2Ij2B7w2Dr7/IyrA==} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + pako@1.0.11: + resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} + + pify@4.0.1: + resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==} + engines: {node: '>=6'} + + possible-typed-array-names@1.1.0: + resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} + engines: {node: '>= 0.4'} + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + set-function-length@1.2.2: + resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} + engines: {node: '>= 0.4'} + + sha.js@2.4.12: + resolution: {integrity: sha512-8LzC5+bvI45BjpfXU8V5fdU2mfeKiQe1D1gIMn7XUlF3OTUrpdJpPPH4EMAnF0DsHHdSZqCdSss5qCmJKuiO3w==} + engines: {node: '>= 0.10'} + hasBin: true + + simple-concat@1.0.1: + resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} + + simple-get@4.0.1: + resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} + + to-buffer@1.2.2: + resolution: {integrity: sha512-db0E3UJjcFhpDhAF4tLo03oli3pwl3dbnzXOUIlRKrp+ldk/VUxzpWYZENsw2SZiuBjHAk7DfB0VU7NKdpb6sw==} + engines: {node: '>= 0.4'} + + typed-array-buffer@1.0.3: + resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} + engines: {node: '>= 0.4'} + typescript@7.0.2: resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} engines: {node: '>=16.20.0'} hasBin: true + which-typed-array@1.1.24: + resolution: {integrity: sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==} + engines: {node: '>= 0.4'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + zod@4.6.5: resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==} @@ -222,6 +397,181 @@ '@typescript/typescript-win32-x64@7.0.2': optional: true + async-lock@1.5.0: {} + + available-typed-arrays@1.0.7: + dependencies: + possible-typed-array-names: 1.1.0 + + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + call-bind@1.0.9: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + get-intrinsic: 1.3.0 + set-function-length: 1.2.2 + + call-bound@1.0.4: + dependencies: + call-bind-apply-helpers: 1.0.2 + get-intrinsic: 1.3.0 + + clean-git-ref@2.0.1: {} + + crc-32@1.2.2: {} + + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + diff3@0.0.3: {} + + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + + for-each@0.3.5: + dependencies: + is-callable: 1.2.7 + + function-bind@1.1.2: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + + gopd@1.2.0: {} + + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + + ignore@5.3.2: {} + + inherits@2.0.4: {} + + is-callable@1.2.7: {} + + is-typed-array@1.1.15: + dependencies: + which-typed-array: 1.1.24 + + isarray@2.0.5: {} + + isomorphic-git@1.44.19: + dependencies: + async-lock: 1.5.0 + clean-git-ref: 2.0.1 + crc-32: 1.2.2 + diff3: 0.0.3 + ignore: 5.3.2 + minimisted: 2.0.1 + pako: 1.0.11 + pify: 4.0.1 + sha.js: 2.4.12 + simple-get: 4.0.1 + + math-intrinsics@1.1.0: {} + + mimic-response@3.1.0: {} + + minimist@1.2.8: {} + + minimisted@2.0.1: + dependencies: + minimist: 1.2.8 + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + pako@1.0.11: {} + + pify@4.0.1: {} + + possible-typed-array-names@1.1.0: {} + + safe-buffer@5.2.1: {} + + set-function-length@1.2.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + function-bind: 1.1.2 + get-intrinsic: 1.3.0 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + + sha.js@2.4.12: + dependencies: + inherits: 2.0.4 + safe-buffer: 5.2.1 + to-buffer: 1.2.2 + + simple-concat@1.0.1: {} + + simple-get@4.0.1: + dependencies: + decompress-response: 6.0.0 + once: 1.4.0 + simple-concat: 1.0.1 + + to-buffer@1.2.2: + dependencies: + isarray: 2.0.5 + safe-buffer: 5.2.1 + typed-array-buffer: 1.0.3 + + typed-array-buffer@1.0.3: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-typed-array: 1.1.15 + typescript@7.0.2: optionalDependencies: '@typescript/typescript-aix-ppc64': 7.0.2 @@ -244,5 +594,17 @@ '@typescript/typescript-sunos-x64': 7.0.2 '@typescript/typescript-win32-arm64': 7.0.2 '@typescript/typescript-win32-x64': 7.0.2 + + which-typed-array@1.1.24: + dependencies: + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + call-bound: 1.0.4 + for-each: 0.3.5 + get-proto: 1.0.1 + gopd: 1.2.0 + has-tostringtag: 1.0.2 + + wrappy@1.0.2: {} zod@4.6.5: {}
A public/branch-commit.js
@@ -0,0 +1,156 @@ +// branch-commit.js — ONE COMMIT ON A NEW BRANCH, MADE IN THE MEMBER'S BROWSER AND PUSHED AS GIT +// PUSHES. page.js asks for this module when a member commits an edit "to a new branch". +// +// WHY THE BROWSER. The mind's repo API commits to `main` alone, and a pull is a branch. A commit +// needs the trees above the file as git holds them (each entry's mode), which only git's own wire +// gives. So the page does what a person's git does: a shallow fetch of main, one new blob, the +// trees above it, one commit, and a push of the new branch. The push goes to this app's own remote +// (../app.ts, `remote`) with the member's sign-in, so the app decides as for any push, and writes +// who pushed on the repo's log. The server has no write path for this. +// +// NOTHING IS KEPT: the fetched objects are in memory (`memoryFs`) and go with the page. + +/** The commit, in git's words, that `commitOnBranch` makes. + * + * `git`, `http`: isomorphic-git and its http client. `url`: the repo's remote. `parent`: the + * commit of main that the member read; main at another commit refuses the edit. `branch` must not + * exist. `author`: `{ name, email }`. It answers `{ commitOid }`, and throws in words for the + * member. */ +export async function commitOnBranch({ git, http, url, parent, branch, path, content, message, author, headers }) { + const fs = memoryFs(); + const dir = "/repo"; + const common = { fs, http, dir, url, headers }; + if (!isBranchName(branch)) throw new Error(`"${branch}" is no name for a branch`); + const refs = await git.listServerRefs({ http, url, headers, prefix: "refs/heads/", protocolVersion: 1 }); + if (refs.some(({ ref }) => ref === `refs/heads/${branch}`)) + throw new Error(`The branch ${branch} is there already: choose another name`); + const tip = refs.find(({ ref }) => ref === "refs/heads/main")?.oid; + if (tip !== parent) + throw new Error("main has moved since this page was loaded. Copy your text, reload the page, and edit again."); + + await git.clone({ ...common, ref: "main", depth: 1, singleBranch: true, noCheckout: true }); + const { commit } = await git.readCommit({ fs, dir, oid: parent }); + // the trees from the root down to the file's folder + const parts = path.split("/"); + const trees = [(await git.readTree({ fs, dir, oid: commit.tree })).tree]; + for (const part of parts.slice(0, -1)) { + const folder = trees.at(-1).find((entry) => entry.path === part && entry.type === "tree"); + if (!folder) throw new Error(`main has no file ${path}`); + trees.push((await git.readTree({ fs, dir, oid: folder.oid })).tree); + } + const file = trees.at(-1).find((entry) => entry.path === parts.at(-1) && entry.type === "blob"); + if (!file) throw new Error(`main has no file ${path}`); + // the new blob, then each tree above it with the one entry changed: every mode stays + let oid = await git.writeBlob({ fs, dir, blob: new TextEncoder().encode(content) }); + if (oid === file.oid) throw new Error("Nothing is changed"); + for (let depth = parts.length - 1; depth >= 0; depth -= 1) { + const tree = trees[depth].map((entry) => (entry.path === parts[depth] ? { ...entry, oid } : entry)); + oid = await git.writeTree({ fs, dir, tree }); + } + const who = { ...author, timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 }; + const commitOid = await git.writeCommit({ + fs, + dir, + commit: { message: message.trimEnd() + "\n", tree: oid, parent: [parent], author: who, committer: who }, + }); + await git.writeRef({ fs, dir, ref: `refs/heads/${branch}`, value: commitOid }); + const pushed = await git.push({ ...common, ref: branch, remoteRef: `refs/heads/${branch}` }); + const answer = pushed.refs?.[`refs/heads/${branch}`]; + if (!pushed.ok || (answer && !answer.ok)) + throw new Error(`The push was refused: ${answer?.error || pushed.error || "no reason given"}`); + return { commitOid }; +} + +/** A branch's name as this app's addresses hold one: letters, digits, `.`, `_`, `-` and `/`, with + * no empty part and no part that git refuses. Never `main`. */ +export function isBranchName(name) { + if (name === "main" || name === "HEAD" || name.length > 100) return false; + return name + .split("/") + .every((part) => /^[A-Za-z0-9_][A-Za-z0-9._-]*$/.test(part) && !part.endsWith(".") && !part.endsWith(".lock") && !part.includes("..")); +} + +/** The files isomorphic-git writes, in memory: what `fs.promises` of Node answers, for the calls + * it makes. A folder is a Map of its entries, a file is its bytes. */ +export function memoryFs() { + const root = new Map(); + const failure = (code, path) => Object.assign(new Error(`${code}: ${path}`), { code }); + const partsOf = (path) => path.split("/").filter(Boolean); + const find = (path) => { + let node = root; + for (const part of partsOf(path)) { + if (!(node instanceof Map)) throw failure("ENOTDIR", path); + if (!node.has(part)) throw failure("ENOENT", path); + node = node.get(part); + } + return node; + }; + const parentOf = (path) => { + const parts = partsOf(path); + const folder = find(parts.slice(0, -1).join("/")); + if (!(folder instanceof Map)) throw failure("ENOTDIR", path); + return [folder, parts.at(-1)]; + }; + const stat = async (path) => { + const node = find(path); + const isFolder = node instanceof Map; + return { + type: isFolder ? "dir" : "file", + mode: isFolder ? 0o40000 : 0o100644, + size: isFolder ? 0 : node.length, + ino: 0, + mtimeMs: 0, + ctimeMs: 0, + uid: 1, + gid: 1, + dev: 1, + isFile: () => !isFolder, + isDirectory: () => isFolder, + isSymbolicLink: () => false, + }; + }; + const promises = { + async readFile(path, options) { + const node = find(path); + if (node instanceof Map) throw failure("EISDIR", path); + const encoding = typeof options === "string" ? options : options?.encoding; + return encoding ? new TextDecoder().decode(node) : node; + }, + async writeFile(path, data) { + const [folder, name] = parentOf(path); + if (folder.get(name) instanceof Map) throw failure("EISDIR", path); + folder.set(name, typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data)); + }, + async unlink(path) { + const [folder, name] = parentOf(path); + if (!folder.delete(name)) throw failure("ENOENT", path); + }, + async readdir(path) { + const node = find(path); + if (!(node instanceof Map)) throw failure("ENOTDIR", path); + return [...node.keys()]; + }, + async mkdir(path) { + const [folder, name] = parentOf(path); + if (!name) return; + if (folder.has(name)) throw failure("EEXIST", path); + folder.set(name, new Map()); + }, + async rmdir(path) { + const [folder, name] = parentOf(path); + const node = folder.get(name); + if (!(node instanceof Map)) throw failure("ENOENT", path); + if (node.size) throw failure("ENOTEMPTY", path); + folder.delete(name); + }, + stat, + lstat: stat, + async readlink(path) { + throw failure("EINVAL", path); + }, + async symlink(_target, path) { + throw failure("EPERM", path); + }, + }; + return { promises }; +}
M public/page.css
@@ -126,3 +126,19 @@ .merge { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0.75rem 0; } .merge .box { margin: 0; } h1 code { font-size: 0.9em; } + +/* ── the page that edits a file ── */ +.edit { margin: 1rem 1rem 3rem; } +.edit > .crumbs { margin-bottom: 0.75rem; } +.pencil { display: inline-flex; align-items: center; gap: 0.3rem; } +#edit-text { display: block; width: 100%; min-height: 60vh; padding: 0.75rem; + border: 1px solid var(--input); border-radius: 0.5rem; background: var(--background); + font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.8125rem; line-height: 1.5; + tab-size: 2; white-space: pre; overflow: auto; resize: vertical; } +#commit h2 { margin: 0; } +.box .choice { display: flex; align-items: baseline; gap: 0.5rem; } +.box .choice input { width: auto; } +/* the branch's name is asked for when the commit goes to a new branch */ +.box input[name="branch"] { display: none; max-width: 24rem; + font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.75rem; } +.box:has(input[value="branch"]:checked) input[name="branch"] { display: block; }
M public/page.js
@@ -5,6 +5,7 @@ // - each diff, when the reader scrolls near it, in the place of its plain text // - on a pull, for a member: the conversation with its reply boxes, a comment box on any line // of a diff, and the buttons that merge or close; on a compare page, the box that opens a pull +// - on the page that edits a file, for a member: the box that commits the edit // // WHAT A MEMBER WRITES IS ONE APPEND to the repo's context (../pulls.ts says which events), through // the member's own itx (mind.js). The page then shows what was written from what it sent: it does @@ -260,6 +261,89 @@ <//>`; } +// ── AN EDIT: the box that commits what the member changed in the file's box ── + +/** THE COMMIT OF AN EDIT, as GitHub offers it: a message that the member may change, and where + * the commit goes. + * + * to main one call of the member's own itx: `repos.get(repo).commitFiles`, pinned to + * the commit that this page read, so an edit never lands over a commit that + * the member did not see. Main is what the mind runs. + * to a new branch the page makes the commit and pushes the branch as git does + * (branch-commit.js), then opens the pull with one event. + * + * Then the page goes to what was made: the commit, or the pull. */ +function EditBox() { + const { path, commitOid, crlf, author } = data.edit; + const box = document.getElementById("edit-text"); + const send = async ({ title, description, where, branch }) => { + const text = box.value; + if (text === box.defaultValue) throw new Error("Nothing is changed."); + // the file's own line endings, which the box showed as line feeds + const content = crlf ? text.replace(/\n/g, "\r\n") : text; + const body = description.trim(); + const message = title.trim() + (body ? "\n\n" + body : ""); + if (where === "main") { + const repo = (await mind()).repos.get(data.repo); + const made = await repo.commitFiles({ message, parent: commitOid, changes: [{ path, content }] }); + if (!made.commitOid) throw new Error("Nothing is changed."); + edited = true; + location.assign(data.repo + "/commit/" + made.commitOid); + return; + } + const [{ default: git }, { default: http }, { commitOnBranch }] = await Promise.all([ + import("isomorphic-git"), + import("isomorphic-git/http/web"), + import("/branch-commit.js"), + ]); + const name = branch.trim(); + const edit = { parent: commitOid, branch: name, path, content, message, author }; + await commitOnBranch({ git, http, url: location.origin + data.repo, ...edit }); + edited = true; + const pull = data.repo + "/compare/" + name.split("/").map(encodeURIComponent).join("/"); + try { + await append("pull/opened", { branch: name, title: title.trim(), body }); + } catch (error) { + // the branch is pushed: the compare page opens the pull + const why = error instanceof Error ? error.message : String(error); + throw new Error("The branch " + name + " is pushed, and the pull was not opened (" + why + "). Open it from Branches."); + } + location.assign(pull); + }; + return html`<${Form} button="Commit changes" send=${send}> + <h2>Commit changes</h2> + <input name="title" defaultValue=${"Update " + path.split("/").at(-1)} aria-label="Commit message" required /> + <textarea name="description" placeholder="Add an extended description (optional)"></textarea> + <label className="choice"> + <input type="radio" name="where" value="main" defaultChecked /> + <span>Commit directly to <code>main</code>. The mind runs main a few seconds later.</span> + </label> + <label className="choice"> + <input type="radio" name="where" value="branch" /> + <span>Create a new branch for this commit and open a pull.</span> + </label> + <input name="branch" defaultValue=${data.edit.branch} aria-label="The new branch's name" /> + <//>`; +} + +/** True once the edit is committed: the page may then go with no question. */ +let edited = false; +function drawEdit() { + const place = document.getElementById("commit"); + if (!place || !data.edit) return; + const box = document.getElementById("edit-text"); + createRoot(place).render(html`<${EditBox} />`); + // a Tab in the box is a tab in the file + box.addEventListener("keydown", (event) => { + if (event.key !== "Tab" || event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) return; + event.preventDefault(); + box.setRangeText("\t", box.selectionStart, box.selectionEnd, "end"); + }); + addEventListener("beforeunload", (event) => { + if (!edited && box.value !== box.defaultValue) event.preventDefault(); + }); +} + // ── THE DIFFS ── let MultiFileDiff; @@ -459,3 +543,4 @@ drawContent(); drawDiffs(); drawPull(); +drawEdit();
M tests/app.test.mjs
@@ -228,6 +228,36 @@ ]); }); +test("a push from a page is taken from this app's own page alone: another site's page pushes nothing with the member's sign-in", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const push = (site, path = "git-receive-pack", method = "POST") => + git.fetch( + new Request(`https://git.example.com/repos/kernel/${path}`, { + method, + headers: { ...asMember, ...(site && { "sec-fetch-site": site }) }, + ...(method === "POST" && { body: "the pack, for refs/heads/add-b" }), + }), + mind, + ); + + for (const site of ["cross-site", "same-site", "none"]) { + const refused = await push(site); + assert.equal(refused.status, 403, site); + assert.equal(await refused.text(), "git: a page of another site does not push here\n"); + } + assert.equal((await push("cross-site", "info/refs?service=git-receive-pack", "GET")).status, 403); + assert.deepEqual([remote.requests.length, mind.minted.length, mind.appended.length], [0, 0, 0]); + + // the app's own page, as a member's edit pushes its branch + const own = await push("same-origin"); + assert.equal(await own.text(), "unpack ok\nok refs/heads/add-b\n"); + assert.deepEqual(mind.appended.map(({ event }) => event.payload), [{ by: "ada@example.com", refs: ["refs/heads/add-b"] }]); + // a read is as it was, wherever it comes from: nothing of it is the member's to lose + assert.equal((await push("cross-site", "info/refs?service=git-upload-pack", "GET")).status, 200); +}); + test("with no sign-in, a repo that is not public and a repo that is not there get the same answer, and so does a push", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote);
A tests/branch-commit.test.mjs
@@ -0,0 +1,92 @@ +// tests/branch-commit.test.mjs — the commit that a member's page makes on a new branch +// (../public/branch-commit.js), pushed to git's own http-backend over a repo that git made. +// Run it from the repo's root with `node --test "tests/*.test.mjs"`. +import assert from "node:assert/strict"; +import { chmodSync } from "node:fs"; +import { join } from "node:path"; +import { test } from "node:test"; +import git from "isomorphic-git"; +import http from "isomorphic-git/http/node"; +import { commitOnBranch, isBranchName } from "../public/branch-commit.js"; +import { repoWith } from "./fixtures.mjs"; +import { gitServer } from "./git-http.mjs"; + +const author = { name: "ada@example.com", email: "ada@example.com" }; + +async function served(history) { + const site = repoWith(history); + const server = await gitServer({ "/repos/site": site.folder }); + return { + site, + url: `${server.origin}/repos/site`, + seen: server.seen, + async [Symbol.asyncDispose]() { + await server.close(); + site[Symbol.dispose](); + }, + }; +} + +test("an edit becomes one commit on a new branch: the file's new text, main as its parent, every other entry as it was", async () => { + await using at = await served([ + { message: "Start", files: { "README.md": "# site\n", "src/deep/hello.ts": "export const hello = 1;\n", "run.sh": "#!/bin/sh\n" } }, + ]); + const { site, url } = at; + // a file that runs keeps its mode through an edit of another file + chmodSync(join(site.folder, "run.sh"), 0o755); + const tip = site.more({ message: "It runs", files: {} }); + assert.match(site.git("ls-tree", "main", "run.sh"), /^100755 /); + + const { commitOid } = await commitOnBranch({ + git, http, url, author, + parent: tip, + branch: "ada/fix-hello", + path: "src/deep/hello.ts", + content: "export const hello = 2;\n", + message: "Update src/deep/hello.ts\n\nIt was one.", + }); + + assert.equal(site.git("rev-parse", "ada/fix-hello"), commitOid); + assert.equal(site.git("rev-parse", "main"), tip, "main is where it was"); + assert.equal(site.git("log", "-1", "--format=%P|%an|%ae|%B", "ada/fix-hello").trim(), `${tip}|ada@example.com|ada@example.com|Update src/deep/hello.ts\n\nIt was one.`); + assert.equal(site.git("show", "ada/fix-hello:src/deep/hello.ts"), "export const hello = 2;"); + assert.equal(site.git("diff", "--name-status", "main", "ada/fix-hello"), "M\tsrc/deep/hello.ts"); + assert.match(site.git("ls-tree", "ada/fix-hello", "run.sh"), /^100755 /); + assert.equal(site.git("fsck", "--strict", "--no-dangling"), ""); +}); + +test("a file at the root is edited too", async () => { + await using at = await served([{ message: "Start", files: { "README.md": "# site\n", "a/b.txt": "b\n" } }]); + const { site, url } = at; + await commitOnBranch({ git, http, url, author, parent: site.commits[0], branch: "readme", path: "README.md", content: "# The site\n", message: "Update README.md" }); + assert.equal(site.git("show", "readme:README.md"), "# The site"); + assert.equal(site.git("diff", "--name-status", "main", "readme"), "M\tREADME.md"); +}); + +test("nothing is pushed when main has moved, the branch is there, the name is bad, the file is gone or the text is the same", async () => { + await using at = await served([ + { message: "Start", files: { "README.md": "# site\n" } }, + { on: "taken", message: "A branch", files: { "x.txt": "x\n" } }, + { message: "Main moves", files: { "more.txt": "more\n" } }, + ]); + const { site, url, seen } = at; + const [first, , tip] = site.commits; + const edit = { git, http, url, author, parent: tip, branch: "new", path: "README.md", content: "# changed\n", message: "Update README.md" }; + + await assert.rejects(commitOnBranch({ ...edit, parent: first }), /main has moved since this page was loaded/); + await assert.rejects(commitOnBranch({ ...edit, branch: "taken" }), /The branch taken is there already/); + await assert.rejects(commitOnBranch({ ...edit, branch: "main" }), /no name for a branch/); + await assert.rejects(commitOnBranch({ ...edit, branch: "a b" }), /no name for a branch/); + await assert.rejects(commitOnBranch({ ...edit, path: "gone.md" }), /main has no file gone.md/); + await assert.rejects(commitOnBranch({ ...edit, path: "nowhere/gone.md" }), /main has no file nowhere\/gone.md/); + await assert.rejects(commitOnBranch({ ...edit, content: "# site\n" }), /Nothing is changed/); + + assert.ok(!seen.some((request) => request.endsWith("git-receive-pack")), "no push was sent"); + assert.equal(site.git("for-each-ref", "--format=%(refname:short)", "refs/heads/"), "main\ntaken"); +}); + +test("a branch's name is one that the app's addresses and git both take", () => { + for (const name of ["fix", "ada/fix-hello", "v1.2_x", "a/b/c"]) assert.ok(isBranchName(name), name); + for (const name of ["main", "HEAD", "", "a b", "/a", "a/", "a//b", ".a", "a..b", "a.lock", "a.", "-", "a~1", "a:b", "a\\b", "x".repeat(101)]) + assert.ok(!isBranchName(name), name); +});
A tests/git-http.mjs
@@ -0,0 +1,73 @@ +// tests/git-http.mjs — GIT'S OWN SMART HTTP OVER A FOLDER OF REPOS, on this machine: what +// Cloudflare Artifacts is to the app when it runs. `git http-backend` answers each request, as a +// CGI program. The tests of a branch commit push to it, and serve.mjs sends the page's git there. +import { spawn } from "node:child_process"; +import { createServer } from "node:http"; + +/** Answers one of git's requests for the repo in `folder`. `verb` is the rest of git's address + * (`info/refs`, `git-upload-pack`, `git-receive-pack`), `search` the query with its `?`. */ +export function gitBackend({ folder, verb, search, method, headers, body }) { + return new Promise((resolve, reject) => { + const backend = spawn("git", ["-c", "http.receivepack=true", "-c", "uploadpack.allowFilter=true", "http-backend"], { + env: { + PATH: process.env.PATH, + GIT_CONFIG_GLOBAL: "/dev/null", + GIT_CONFIG_SYSTEM: "/dev/null", + GIT_PROJECT_ROOT: folder, + GIT_HTTP_EXPORT_ALL: "1", + PATH_INFO: `/.git/${verb}`, + QUERY_STRING: (search || "").replace(/^\?/, ""), + REQUEST_METHOD: method, + CONTENT_TYPE: headers["content-type"] || "", + ...(headers["git-protocol"] && { GIT_PROTOCOL: headers["git-protocol"] }), + ...(headers["content-encoding"] && { HTTP_CONTENT_ENCODING: headers["content-encoding"] }), + REMOTE_USER: "tester", + }, + }); + const chunks = []; + backend.stdout.on("data", (chunk) => chunks.push(chunk)); + backend.on("error", reject); + backend.on("close", () => { + const out = Buffer.concat(chunks); + const split = out.indexOf("\r\n\r\n"); + const answerHeaders = {}; + let status = 200; + for (const line of out.subarray(0, split).toString().split("\r\n")) { + const [name, ...value] = line.split(": "); + if (name.toLowerCase() === "status") status = Number(value.join(": ").split(" ")[0]); + else answerHeaders[name.toLowerCase()] = value.join(": "); + } + resolve({ status, headers: answerHeaders, body: out.subarray(split + 4) }); + }); + backend.stdin.end(body); + }); +} + +/** A server of the repos in `folders` (by path, `/repos/<name>`), at `http://127.0.0.1:<port>`. + * `seen` lists each request as `POST /repos/<name>/git-receive-pack`. */ +export async function gitServer(folders) { + const seen = []; + const server = createServer(async (request, response) => { + const url = new URL(request.url, "http://localhost"); + const match = /^(\/repos\/[^/]+)\/(info\/refs|git-upload-pack|git-receive-pack)$/.exec(url.pathname); + if (!match || !folders[match[1]]) return response.writeHead(404).end("no repo\n"); + seen.push(`${request.method} ${url.pathname}`); + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + const answer = await gitBackend({ + folder: folders[match[1]], + verb: match[2], + search: url.search, + method: request.method, + headers: request.headers, + body: Buffer.concat(chunks), + }); + response.writeHead(answer.status, answer.headers).end(answer.body); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { + origin: `http://127.0.0.1:${server.address().port}`, + seen, + close: () => new Promise((resolve) => server.close(resolve)), + }; +}
M tests/pages.test.mjs
@@ -277,4 +277,89 @@ // ── the fixtures ── /** What worker.ts hands the app: the mind's icon. */ +test("a member's file page has the pencil, to GitHub's address for an edit; anyone else's has none", async () => { + using kernel = repoWith([{ message: "Start", files: { "core/my sdk.ts": "export const one = 1;\n" } }]); + const folders = { "/repos/kernel": kernel.folder }; + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const read = async (member) => + (await git.fetch(new Request("https://git.example.com/repos/kernel/tree/main/core/my%20sdk.ts"), localMind({ folders, member }))).text(); + + assert.ok((await read("ada@example.com")).includes(`<a class="pencil" href="/repos/kernel/edit/main/core/my%20sdk.ts" title="Edit this file">`)); + assert.ok(!(await read(null)).includes("/edit/main/")); +}); + +test("the edit page is a member's: the file's text in a box, and what the commit needs; anyone else gets the sign-in, on a public repo too", async () => { + using kernel = repoWith([ + { message: "Start", files: { "core/sdk.ts": "\nconst html = `</textarea><b>${1 < 2}</b>`;\n", "README.md": "# kernel\n" } }, + { on: "ada/edit-sdk-ts", message: "Taken", files: { "x.txt": "x\n" } }, + ]); + const folders = { "/repos/kernel": kernel.folder }; + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const address = "https://git.example.com/repos/kernel/edit/main/core/sdk.ts"; + + const stranger = localMind({ folders, member: null }); + const refused = await git.fetch(new Request(address), stranger); + assert.equal(refused.status, 401); + assert.deepEqual(stranger.asked, [], "the repo was not read"); + + const answer = await git.fetch(new Request(address), localMind({ folders, member: "ada@example.com" })); + const html = await answer.text(); + assert.equal(answer.status, 200); + // the text is text, and its first line break is kept: a textarea drops one after its tag + assert.ok(html.includes(`aria-label="core/sdk.ts">\n\nconst html = \`</textarea><b>\${1 < 2}</b>\`;\n</textarea>`)); + assert.ok(html.includes(`<div id="commit">`)); + assert.ok(html.includes(`Edit <a href="/repos/kernel/tree/main/core/sdk.ts">core/sdk.ts</a>`)); + // the branch's name is one that no branch has; the author is the member, for their own page + assert.deepEqual(dataOf(html), { + repo: "/repos/kernel", + me: "ada", + edit: { + path: "core/sdk.ts", + commitOid: kernel.commits[0], + crlf: false, + branch: "ada/edit-sdk-ts-2", + author: { name: "ada", email: "ada@example.com" }, + }, + }); +}); + +test("the edit page keeps a file's CR LF line endings, and offers no edit of what a box would change whole", async () => { + using site = repoWith([ + { + message: "Start", + files: { + "dos.txt": "one\r\ntwo\r\n", + "mixed.txt": "one\r\ntwo\n", + "logo.png": Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 3]), + "big.txt": "x".repeat(1_000_001), + }, + }, + ]); + const mind = localMind({ folders: { "/repos/site": site.folder }, member: "ada@example.com" }); + const git = gitApp({ public: [], ...look }); + const read = async (path) => { + const answer = await git.fetch(new Request(`https://git.example.com/repos/site/edit/${path}`), mind); + return { status: answer.status, html: await answer.text() }; + }; + + const dos = await read("main/dos.txt"); + assert.ok(dos.html.includes(`>\none\ntwo\n</textarea>`)); + assert.equal(dataOf(dos.html).edit.crlf, true); + + for (const [path, words] of [ + ["main/mixed.txt", "This file mixes line endings"], + ["main/logo.png", "This file is not text"], + ["main/big.txt", "This file is too large"], + ]) { + const { status, html } = await read(path); + assert.equal(status, 200, path); + assert.ok(html.includes(words), path); + assert.ok(!html.includes("<textarea"), path); + assert.equal(dataOf(html).edit, undefined, path); + } + assert.equal((await read("main/gone.txt")).status, 404); + assert.equal((await read("main")).status, 404); + assert.equal((await read("a-branch/dos.txt")).status, 404); +}); + const look = { icon: () => new Response("the icon") };
M tests/serve.mjs
@@ -1,6 +1,6 @@ // tests/serve.mjs — THE APP ON THIS MACHINE, to try a change before a push: // -// node tests/serve.mjs then open http://git.localhost:4173 +// node tests/serve.mjs then open http://git.localhost:4173 (PORT=… for another) // VISITOR=anyone node tests/serve.mjs as someone who is no member // // It serves COPIES of the repos cloned beside this one, made in a temporary folder that goes when @@ -9,7 +9,8 @@ // // The mind is local-mind.mjs. What a member's page writes goes to it too: this server answers the // page's /mind.js with a module of its own (below), in the place of the one that dials the mind. -// Git itself is not served here (no clone, no push). +// Git itself is served by git's own http-backend over the same copies (git-http.mjs), in the place +// of Cloudflare Artifacts: a clone, and the push of a branch that a member's page makes of an edit. import "@repos/stdlib/testing/mind-loader.mjs"; import { execFileSync } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -17,6 +18,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { mergePull } from "../pulls.ts"; +import { gitBackend } from "./git-http.mjs"; import { localMind } from "./local-mind.mjs"; const { gitApp } = await import("../app.ts"); @@ -30,6 +32,8 @@ const folders = {}; for (const name of ["kernel", "stdlib", "dash", "tasks", "git", "config"]) { + // a workspace need not hold every repo + if (!existsSync(join(workspace, name))) continue; folders[`/repos/${name}`] = join(copies, name); execFileSync("git", ["clone", "--quiet", "--branch", "main", join(workspace, name), folders[`/repos/${name}`]]); } @@ -67,16 +71,19 @@ }; export const itx = { cd: (path) => ({ append: (event) => ask("/local-mind/append", { path, event }) }), + repos: { get: (repo) => ({ commitFiles: (input) => ask("/local-mind/commit", { repo, input }) }) }, config: { pullMerge: (repo, number) => ask("/local-mind/merge", { repo, number }) }, }; `; const written = async (path, body) => { if (path === "/local-mind/append") return mind.as(visitor).cd(body.path).append(body.event); + if (path === "/local-mind/commit") + return mind.getItx().repos.get(body.repo).commitFiles({ author: { name: visitor, email: visitor }, ...body.input }); if (path === "/local-mind/merge") return mergePull(mind.getItx(), body.repo, body.number); }; -const port = 4173; +const port = Number(process.env.PORT) || 4173; createServer(async (request, response) => { const { pathname } = new URL(request.url, "http://localhost"); if (pathname === "/mind.js") { @@ -100,6 +107,16 @@ } catch (error) { response.writeHead(400).end(error instanceof Error ? error.message : String(error)); } + return; + } + const wire = /^(\/repos\/[^/]+)\/(info\/refs|git-upload-pack|git-receive-pack)$/.exec(pathname); + if (wire && folders[wire[1]]) { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + const { search } = new URL(request.url, "http://localhost"); + const sent = { folder: folders[wire[1]], verb: wire[2], search, method: request.method, headers: request.headers, body: Buffer.concat(chunks) }; + const answered = await gitBackend(sent); + response.writeHead(answered.status, answered.headers).end(answered.body); return; } const answer = await git.fetch(new Request(`http://${request.headers.host}${request.url}`), mind);