iterate.com / git

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

git / public / branch-commit.jsmain at 517348b

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