Cloudflare Git

Repos/herdr-appPublic

main
228 lines · 14.4 KBRaw
// A lazy file browser for the focused pane's folder; a clicked file opens in its own tab (file-view).
import { View, div, svg } from "gpui-kit";
import { v_flex, h_flex } from "gpui-base";
import { spaces, panes, focused, exec, watchFolder, theme, window, run } from "herdr";

function location() {
  const space = spaces().find(s => s.active), f = focused();
  const pane = f?.pane ? panes().find(p => p.pane === f.pane) : null;
  const on = f?.pane === null ? (f.terminal?.includes("/") ? f.terminal.split("/")[0] : null) : space?.machine ?? null;
  const cwd = pane?.cwd || f?.cwd;
  // A pane with no folder (a file tab) keeps the folder already shown, not the space's saved one.
  if (cwd || !last || last.space !== space?.id) last = { cwd: cwd || space?.folder, on, space: space?.id };
  return last;
}
let last = null;
const PER_FOLDER = 500, TOTAL = 5000;

async function directory(path, on) {
  const windowsDirectory = async () => {
    // Windows PowerShell otherwise uses the console code page; exec decodes UTF-8.
    // Links keep directory attributes even when dangling; check their target.
    // Other reparse points (OneDrive's folders) have no LinkType and are folders.
    // PowerShell reads curly single quotes as quotes too, so they're doubled like '.
    const r = await exec("powershell", ["-NoProfile", "-Command", "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); & { param($p) @(Get-ChildItem -LiteralPath $p -Force -ErrorAction Stop | Where-Object Name -ne '.git' | Select-Object -First 501 | ForEach-Object { @{ name=$_.Name; dir=($_.PSIsContainer -and (-not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -or -not $_.LinkType -or ($_.Target -and [IO.Directory]::Exists(([IO.Path]::Combine([IO.Path]::GetDirectoryName($_.FullName), $_.Target[0])))))) } }) | ConvertTo-Json -Compress } '" + path.replace(/['‘’‚‛]/g, "$&$&") + "'"], { on });
    if (r.code !== 0) throw new Error(r.stderr || "Cannot list this folder");
    const result = JSON.parse(r.stdout || "[]");
    return Array.isArray(result) ? result : [result];
  };
  if (!on && window()?.platform === "windows") return windowsDirectory();
  const script = 'n=0; for p in "$1"/* "$1"/.[!.]* "$1"/..?*; do [ -e "$p" ] || [ -L "$p" ] || continue; name=${p##*/}; [ "$name" = .git ] && continue; if [ -d "$p" ]; then kind=d; else kind=f; fi; printf "%s\\0%s\\0" "$kind" "$name"; n=$((n+1)); [ "$n" -gt 500 ] && break; done; test -d "$1"';
  let r;
  try { r = await exec("sh", ["-c", script, "files", path], { on }); }
  catch (e) {
    if (on && String(e).includes("cannot start sh: program not found")) return windowsDirectory();
    throw e;
  }
  if (r.code !== 0) throw new Error(r.stderr || "Cannot list this folder");
  const fields = r.stdout.split("\0"), out = [];
  for (let i = 0; i + 1 < fields.length; i += 2) out.push({ name: fields[i + 1], dir: fields[i] === "d" });
  return out;
}

export default class Files extends View {
  // A file already open in this space (a file-view tab named by its path) is selected, not opened twice.
  // A new one goes last (tab.new puts it beside the selected tab).
  open(file) {
    const tabs = spaces().find(s => s.active)?.tabs ?? [];
    const tab = tabs.find(t => t.name === file && panes().some(p => p.tab === t.id && p.mod === "file-view"));
    if (tab) return run("tab.select", { id: tab.id });
    run("tab.new", { name: file, mod: "file-view", props: { file, on: this.on } });
    run("tab.move", { index: tabs.length + 1 });
  }

  init(_props, cx) {
    this.saved = new Map(); this.picked = new Map(); this.checkouts = []; this.menu = false;
    this.entries = new Map(); this.folders = new Set(); this.pending = new Set(); this.marks = {}; this.counts = {};
    this.refresh(cx);
    cx.timer.every(10000, cx => this.refresh(cx));
  }

  watch(root, cx) {
    if (this.on || this.watched === root) return;
    this.watched = root;
    const context = this.context;
    cx.spawn(async cx => {
      try { while (this.context === context) { await watchFolder(root); if (this.current(context)) this.refresh(cx); } }
      catch { if (this.context === context) this.watched = null; }
    });
  }

  // The pane's folder, or the worktree picked for it in the header.
  place() {
    const loc = location(), cwd = this.picked.get(JSON.stringify(loc)) ?? loc.cwd;
    return { cwd, on: loc.on, base: JSON.stringify(loc), key: JSON.stringify({ ...loc, cwd }) };
  }

  current(context) {
    return this.context === context && this.place().key === context.key;
  }

  // The checkout holding a folder: the deepest one, since a worktree can sit inside the main checkout.
  checkout(path) {
    return this.checkouts.filter(c => path === c.path || path?.startsWith(c.path + "/")).sort((a, b) => b.path.length - a.path.length)[0];
  }

  pick(checkout, cx) {
    const { base } = this.place(), loc = JSON.parse(base);
    // The checkout holding the pane's own folder goes back to following the pane.
    if (this.checkout(loc.cwd) === checkout) this.picked.delete(base);
    else this.picked.set(base, checkout.path);
    this.menu = false;
    this.refresh(cx);
    cx.notify();
  }

  async loadFolder(path, context) {
    const { on, cwd: root } = context;
    const entries = await directory(path ? `${root}/${path}` : root, on);
    if (!this.current(context) || (path && !this.folders.has(path))) return;
    const used = [...this.entries.entries()].filter(([p]) => p !== path).reduce((n, [, e]) => n + e.length, 0);
    this.entries.set(path, entries.slice(0, Math.max(0, Math.min(PER_FOLDER, TOTAL - used))).sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name)));
    if (entries.length > PER_FOLDER || used + entries.length > TOTAL) this.limited = true;
  }

  refresh(cx) {
    const { cwd, on, base, key: next } = this.place();
    if (next !== this.context?.key) {
      if (this.context) this.saved.set(this.context.key, { folders: this.folders });
      const saved = this.saved.get(next);
      this.context = { key: next, cwd, on }; this.root = cwd; this.on = on; this.entries = new Map(); this.folders = new Set(saved?.folders);
      this.pending = new Set(); this.marks = {}; this.counts = {}; this.watched = null; this.error = null; this.limited = false;
      this.loading = false; this.menu = false;
    }
    if (!cwd || this.loading) return;
    const context = this.context;
    this.loading = true;
    this.limited = false;
    cx.spawn(async cx => {
      try {
        // Every checkout of the repo (`git worktree list`), asked from the pane's folder so a removed worktree drops out.
        const list = await exec("git", ["worktree", "list", "--porcelain"], { cwd: JSON.parse(base).cwd, on }).catch(() => null);
        const checkouts = list?.code === 0 ? list.stdout.split(/\n\n+/).map(b => b.split("\n")).filter(l => !l.some(x => x === "bare" || x.startsWith("prunable")))
          .map(l => ({ path: l.find(x => x.startsWith("worktree "))?.slice(9), branch: l.find(x => x.startsWith("branch "))?.slice(7).replace(/^refs\/heads\//, "") ?? "detached" })).filter(c => c.path) : [];
        // How many files each checkout has changed, so the worktree list shows where an agent's work is.
        await Promise.all(checkouts.map(async c => {
          const r = await exec("git", ["--no-optional-locks", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all"], { cwd: c.path, on }).catch(() => null);
          c.changes = r?.code === 0 ? r.stdout.split("\0").filter(Boolean).length : 0;
        }));
        if (!this.current(context)) return;
        this.checkouts = checkouts;
        if (this.picked.has(base) && !checkouts.some(c => c.path === cwd)) { this.picked.delete(base); return; }
        for (const path of ["", ...this.folders]) {
          if (!this.current(context)) return;
          await this.loadFolder(path, context);
        }
        const top = await exec("git", ["rev-parse", "--show-toplevel"], { cwd, on }).catch(() => null);
        const marks = {}, counts = {};
        if (top?.code === 0) {
          // Writes nothing under .git (index lock, fsmonitor cookie): the folder watch would refresh again.
          const status = await exec("git", ["--no-optional-locks", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all"], { cwd, on }).catch(() => null);
          if (status?.code === 0) for (const entry of status.stdout.split("\0").filter(Boolean).slice(0, TOTAL)) {
            const xy = entry.slice(0, 2);
            marks[`${top.stdout.trim()}/${entry.slice(3)}`] = xy === "??" || xy.includes("A") ? "A" : xy.includes("U") ? "U" : xy.includes("D") ? "D" : "M";
          }
          // Each folder counts the changed files under it, at any depth; it reads as added only if they all are.
          const repo = top.stdout.trim();
          for (const [file, mark] of Object.entries(marks))
            for (let dir = file.slice(0, file.lastIndexOf("/")); dir.length > repo.length; dir = dir.slice(0, dir.lastIndexOf("/"))) {
              const c = counts[dir] ??= { n: 0, added: true };
              c.n++; c.added &&= mark === "A";
            }
        }
        if (!this.current(context)) return;
        this.marks = marks; this.counts = counts; this.error = null; this.watch(cwd, cx);
      } catch (e) { if (this.current(context)) this.error = String(e); }
      finally { if (this.context === context) this.loading = false; cx.notify(); }
    });
  }

  toggle(path, cx) {
    if (this.folders.has(path)) {
      for (const folder of [...this.folders]) if (folder === path || folder.startsWith(path + "/")) {
        this.folders.delete(folder);
        this.entries.delete(folder);
      }
    } else {
      this.folders.add(path);
      if (!this.entries.has(path) && !this.pending.has(path)) {
        const context = this.context;
        this.pending.add(path);
        cx.spawn(async cx => {
          try { await this.loadFolder(path, context); }
          catch (e) { if (this.current(context)) this.error = String(e); }
          finally { if (this.context === context) this.pending.delete(path); cx.notify(); }
        });
      }
    }
    cx.notify();
  }

  rows(prefix, depth, out, t) {
    if (out.length >= TOTAL || depth > 40) return out;
    for (const entry of this.entries.get(prefix) ?? []) {
      if (out.length >= TOTAL) break;
      const path = prefix ? `${prefix}/${entry.name}` : entry.name, open = this.folders.has(path), abs = `${this.root}/${path}`;
      const count = entry.dir ? this.counts[abs] : null, mark = entry.dir ? count && (count.added ? "A" : "M") : this.marks[abs];
      const color = mark === "A" ? t.ansi2 : mark === "D" || mark === "U" ? t.ansi1 : mark ? t.blocked : null;
      out.push(h_flex().id(`file-${path}`).h(28).flex_none().pl(8 + depth * 18).pr(8).gap(7).items_center().rounded(7).cursor_pointer().hover(s => s.bg(t.hover))
        .on_click((_e, cx) => entry.dir ? this.toggle(path, cx) : this.open(`${this.root}/${path}`))
        .child(entry.dir ? svg(`mods/files-tabs/chevron-${open ? "down" : "right"}.svg`).size(12).flex_none().text_color(t.dim) : div().w(12).flex_none())
        .child(svg(`mods/files-tabs/${entry.dir ? "folder" : "file"}.svg`).size(14).flex_none().text_color(t.muted))
        .child(div().flex_1().min_w(0).truncate().when(Boolean(color), el => el.text_color(color)).child(entry.name))
        // Counts and letters share one 18px column at the right edge.
        .when(Boolean(color), el => el.child(div().h(18).min_w(18).px(5).flex_none().flex().items_center().justify_center().rounded(9).text_size(11).text_color(color)
          .when(Boolean(count), e => e.bg(color + "26").font_bold()).child(count ? String(count.n) : mark))));
      if (entry.dir && open) this.rows(path, depth + 1, out, t);
    }
    return out;
  }

  render(cx) {
    if (this.place().key !== this.context?.key) this.refresh(cx);
    const t = theme(), shown = this.checkout(this.root), many = this.checkouts.length > 1;
    const changes = n => div().h(18).min_w(18).px(5).flex_none().flex().items_center().justify_center().rounded(9).text_size(11).font_bold().text_color(t.blocked).bg(t.blocked + "26").child(String(n));
    // Changes in the checkouts not shown, as a hint on the closed list.
    const elsewhere = this.checkouts.filter(c => c !== shown).reduce((n, c) => n + (c.changes ?? 0), 0);
    return v_flex().id("files").size_full().min_h(0).rounded(10).overflow_hidden().bg(t.background).border_1().border_color(t.border).text_color(t.foreground).text_size(13)
      .child(h_flex().h(42).flex_none().px(14).gap(8).items_center().border_b(1).border_color(t.border)
        .child(div().font_semibold().child("Files"))
        .child(div().flex_1())
        .when(!many, el => el.child(div().min_w(0).truncate().text_size(12).text_color(t.dim).child(this.root?.split(/[\\/]/).pop() ?? "")))
        // Several worktrees: the shown one's branch opens a list of them under the header.
        .when(many, el => el.child(h_flex().id("files-worktree").min_w(0).h(26).px(8).gap(5).items_center().rounded(6).cursor_pointer().text_size(12).text_color(t.dim)
          .hover(s => s.bg(t.hover).text_color(t.foreground)).on_click((_e, cx) => { this.menu = !this.menu; cx.notify(); })
          .child(div().min_w(0).truncate().child(shown?.branch ?? this.root?.split(/[\\/]/).pop() ?? ""))
          .when(elsewhere > 0, e => e.child(changes(elsewhere)))
          .child(svg(`mods/files-tabs/chevron-${this.menu ? "up" : "down"}.svg`).size(12).flex_none()))))
      .when(many && this.menu, el => el.child(v_flex().flex_none().p(6).border_b(1).border_color(t.border).children(this.checkouts.map((c, i) =>
        h_flex().id(`worktree-${i}`).h(28).px(8).gap(7).items_center().rounded(7).cursor_pointer().hover(s => s.bg(t.hover))
          .on_click((_e, cx) => this.pick(c, cx))
          .child(div().flex_1().min_w(0).truncate().when(c === shown, e => e.font_semibold()).child(c.branch))
          .child(div().flex_none().text_size(11).text_color(t.dim).child(i === 0 ? "main checkout" : c.path.split(/[\\/]/).pop()))
          .when(c.changes > 0, e => e.child(changes(c.changes)))))))
      .child(v_flex().id("files-tree").flex_1().min_h(0).overflow_y_scrollbar().p(6).children(this.rows("", 0, [], t))
        .when(Boolean(this.error) || !this.entries.get("")?.length, el => el.child(div().p(8).text_size(12).text_color(t.dim).child(this.error || (this.loading ? "Loading files…" : this.root ? "No files" : "No folder"))))
        .when(this.limited, el => el.child(div().p(8).text_size(11).text_color(t.dim).child("File list limited to 500 entries per folder and 5,000 total"))));
  }
}