iterate.com / git

git clone https://git.iterate.com/repos/git

git / tests / git-http.mjsmain at 517348b

// 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)),
  };
}