repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/files-widget/scanner.ts

Raw
File outline
/**
 * Background scanner for file-widget — handles line counting and directory scanning.
 * Extracted from browser.ts for testability and clarity.
 */

import { readdir, readFile, realpath, stat } from "node:fs/promises";
import { realpathSync, lstatSync, statSync } from "node:fs";
import { join, resolve, sep } from "node:path";

import {
  LINE_COUNT_BATCH_DELAY_MS,
  LINE_COUNT_BATCH_SIZE,
  MAX_LINE_COUNT_BYTES,
  MAX_TREE_DEPTH,
  SCAN_BATCH_DELAY_MS,
  SCAN_BATCH_SIZE,
  SAFE_MODE_ENTRY_THRESHOLD,
} from "./constants";
import { getIgnoredNames, sortChildren } from "./file-tree";
import type { FileNode } from "./types";

// ── Scan state ──────────────────────────────────────────────────────────

export interface ScanState {
  mode: "full" | "safe" | "none";
  isScanning: boolean;
  isPartial: boolean;
  pending: number;
  spinnerIndex: number;
}

// ── Helpers ─────────────────────────────────────────────────────────────

export function safeRealPathSync(path: string): string {
  try {
    return realpathSync(path);
  } catch {
    return resolve(path);
  }
}

function hasAncestorRealPath(node: FileNode | undefined, realPath: string): boolean {
  let current = node;
  while (current) {
    if (current.realPath === realPath) return true;
    current = current.parent;
  }
  return false;
}

async function getPathInfo(path: string, isSymlink: boolean): Promise<{ isDirectory: boolean; isSymlink: boolean; realPath?: string }> {
  try {
    const targetStat = await stat(path);
    return {
      isDirectory: targetStat.isDirectory(),
      isSymlink,
      realPath: targetStat.isDirectory() ? await realpath(path).catch(() => resolve(path)) : undefined,
    };
  } catch {
    return { isDirectory: false, isSymlink };
  }
}

// ── Scanner class ───────────────────────────────────────────────────────

export class FileScanner {
  private lineCountCache = new Map<string, { size: number; mtimeMs: number; count: number }>();
  private lineCountQueue: FileNode[] = [];
  private lineCountPending = new Set<string>();
  private lineCountTimer: ReturnType<typeof setTimeout> | null = null;

  private scanQueue: Array<{ node: FileNode; depth: number }> = [];
  private scanQueued = new Set<string>();
  private scanTimer: ReturnType<typeof setTimeout> | null = null;

  private ignored: Set<string>;
  private scanState: ScanState;
  private repo: boolean;
  private cwd: string;
  private agentModifiedFiles: Set<string>;
  private nodeByPath: Map<string, FileNode>;
  private requestRender: () => void;

  /** Called after any batch completes with updated stats */
  onUpdate?: () => void;

  constructor(
    cwd: string,
    repo: boolean,
    scanState: ScanState,
    agentModifiedFiles: Set<string>,
    nodeByPath: Map<string, FileNode>,
    requestRender: () => void,
  ) {
    this.cwd = cwd;
    this.repo = repo;
    this.scanState = scanState;
    this.agentModifiedFiles = agentModifiedFiles;
    this.nodeByPath = nodeByPath;
    this.requestRender = requestRender;
    this.ignored = getIgnoredNames();
  }

  // ── Public API ────────────────────────────────────────────────────

  get isLineCounting(): boolean {
    return this.lineCountPending.size > 0;
  }

  queueLineCount(node: FileNode, force = false): void {
    if (node.isDirectory) return;
    if (!force && node.lineCount !== undefined) return;
    if (this.lineCountPending.has(node.path)) return;
    this.lineCountPending.add(node.path);
    this.lineCountQueue.push(node);
    if (!this.lineCountTimer) {
      this.lineCountTimer = setTimeout(() => this.processLineCountBatch(), LINE_COUNT_BATCH_DELAY_MS);
    }
  }

  queueLineCountsForTree(rootNode: FileNode | null): void {
    if (!rootNode) return;
    const stack: FileNode[] = [rootNode];
    while (stack.length > 0) {
      const node = stack.pop();
      if (!node) continue;
      if (node.isDirectory) {
        if (node.children) {
          for (const child of node.children) stack.push(child);
        }
      } else {
        this.queueLineCount(node);
      }
    }
  }

  enqueueScan(node: FileNode, depth: number, force = false): void {
    if (depth > MAX_TREE_DEPTH) return;
    if (!force && this.scanState.mode === "safe" && depth > 0) return;
    if (node.children !== undefined || node.loading) return;
    if (this.scanQueued.has(node.path)) return;

    node.loading = true;
    this.scanQueued.add(node.path);
    this.scanQueue.push({ node, depth });
    this.scanState.pending = this.scanQueue.length;
    this.scanState.isScanning = true;

    if (!this.scanTimer) {
      this.scanTimer = setTimeout(() => this.processScanBatch(), this.getScanDelay());
    }
  }

  stop(): void {
    if (this.lineCountTimer) {
      clearTimeout(this.lineCountTimer);
      this.lineCountTimer = null;
    }
    if (this.scanTimer) {
      clearTimeout(this.scanTimer);
      this.scanTimer = null;
    }
  }

  // ── Line counting internals ──────────────────────────────────────

  private async updateLineCount(node: FileNode): Promise<void> {
    try {
      const fileStat = await stat(node.path);
      if (fileStat.size > MAX_LINE_COUNT_BYTES) {
        node.lineCount = undefined;
        return;
      }
      const cached = this.lineCountCache.get(node.path);
      if (cached && cached.size === fileStat.size && cached.mtimeMs === fileStat.mtimeMs) {
        node.lineCount = cached.count;
        return;
      }
      const content = await readFile(node.path, "utf-8");
      const count = content.split("\n").length;
      node.lineCount = count;
      this.lineCountCache.set(node.path, { size: fileStat.size, mtimeMs: fileStat.mtimeMs, count });
    } catch {
      node.lineCount = undefined;
    }
  }

  private async processLineCountBatch(): Promise<void> {
    this.lineCountTimer = null;
    const batch = this.lineCountQueue.splice(0, LINE_COUNT_BATCH_SIZE);
    if (batch.length === 0) return;

    await Promise.all(
      batch.map(async (node) => {
        await this.updateLineCount(node);
        this.lineCountPending.delete(node.path);
      }),
    );

    this.onUpdate?.();
    this.requestRender();

    if (this.lineCountQueue.length > 0) {
      this.lineCountTimer = setTimeout(() => this.processLineCountBatch(), LINE_COUNT_BATCH_DELAY_MS);
    }
  }

  // ── Directory scanning internals ─────────────────────────────────

  private shouldAutoScan(depth: number): boolean {
    if (this.repo) return false;
    if (this.scanState.mode === "safe") return depth <= 0;
    return depth <= MAX_TREE_DEPTH;
  }

  private getScanBatchSize(): number {
    return this.scanState.mode === "safe" ? 1 : SCAN_BATCH_SIZE;
  }

  private getScanDelay(): number {
    return this.scanState.mode === "safe" ? SCAN_BATCH_DELAY_MS * 4 : SCAN_BATCH_DELAY_MS;
  }

  private async scanDirectory(node: FileNode, depth: number): Promise<void> {
    try {
      const entries = await readdir(node.path, { withFileTypes: true });
      const sorted = [...entries].sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));

      if (node.path === this.cwd && this.scanState.mode === "full" && sorted.length >= SAFE_MODE_ENTRY_THRESHOLD) {
        this.scanState.mode = "safe";
        this.scanState.isPartial = true;
        this.scanQueue.length = 0;
        this.scanQueued.clear();
      }

      const dirs: FileNode[] = [];
      const files: FileNode[] = [];

      for (const entry of sorted) {
        if (this.ignored.has(entry.name) || entry.name.startsWith(".")) continue;
        const fullPath = join(node.path, entry.name);
        const childDepth = depth + 1;

        if (entry.isDirectory()) {
          const dirNode: FileNode = {
            name: entry.name,
            path: fullPath,
            isDirectory: true,
            realPath: await realpath(fullPath).catch(() => resolve(fullPath)),
            parent: node,
            children: undefined,
            expanded: childDepth < 1,
            hasChangedChildren: false,
          };
          dirs.push(dirNode);
          this.nodeByPath.set(fullPath, dirNode);
          if (this.shouldAutoScan(childDepth)) {
            this.enqueueScan(dirNode, childDepth);
          }
          continue;
        }

        if (entry.isSymbolicLink()) {
          const pathInfo = await getPathInfo(fullPath, true);
          if (pathInfo.isDirectory) {
            const isCycle = pathInfo.realPath ? hasAncestorRealPath(node, pathInfo.realPath) : false;
            const dirNode: FileNode = {
              name: entry.name,
              path: fullPath,
              isDirectory: true,
              isSymlink: true,
              realPath: pathInfo.realPath,
              parent: node,
              children: isCycle ? [] : undefined,
              expanded: childDepth < 1,
              hasChangedChildren: false,
            };
            dirs.push(dirNode);
            this.nodeByPath.set(fullPath, dirNode);
            if (!isCycle && this.shouldAutoScan(childDepth)) {
              this.enqueueScan(dirNode, childDepth);
            }
            continue;
          }

          const symlinkFileNode: FileNode = {
            name: entry.name,
            path: fullPath,
            isDirectory: false,
            isSymlink: true,
            parent: node,
            agentModified: this.agentModifiedFiles.has(fullPath),
          };
          files.push(symlinkFileNode);
          this.nodeByPath.set(fullPath, symlinkFileNode);
          this.queueLineCount(symlinkFileNode);
          continue;
        }

        const fileNode: FileNode = {
          name: entry.name,
          path: fullPath,
          isDirectory: false,
          parent: node,
          agentModified: this.agentModifiedFiles.has(fullPath),
        };
        files.push(fileNode);
        this.nodeByPath.set(fullPath, fileNode);
        this.queueLineCount(fileNode);
      }

      node.children = [...dirs, ...files];
    } catch {
      node.children = [];
    } finally {
      node.loading = false;
      this.scanQueued.delete(node.path);
    }
  }

  private async processScanBatch(): Promise<void> {
    this.scanTimer = null;
    const batch = this.scanQueue.splice(0, this.getScanBatchSize());
    if (batch.length === 0) {
      this.scanState.isScanning = false;
      this.scanState.pending = 0;
      return;
    }

    for (const item of batch) {
      await this.scanDirectory(item.node, item.depth);
    }

    this.scanState.pending = this.scanQueue.length;
    this.scanState.isScanning = this.scanQueue.length > 0;

    this.onUpdate?.();
    this.requestRender();

    if (this.scanQueue.length > 0) {
      this.scanTimer = setTimeout(() => this.processScanBatch(), this.getScanDelay());
    }
  }
}