import type { CaptureFile } from "./task-run"; /** One row of the changed-files tree: a folder with children, or a file. */ export interface FileNode { /** The label: a folder chain with no sibling reads as one name, `internal/app`. */ name: string; path: string; file?: CaptureFile; children: FileNode[]; } /** * Groups changed files by directory, folders before files, each sorted by name. * A folder that holds only one folder is merged into it, so a deep path does not * cost a row per directory. */ export function fileTree(files: CaptureFile[]): FileNode[] { const root: FileNode = { name: "", path: "", children: [] }; for (const file of files) { const parts = (file.path || "").split("/").filter(Boolean); let node = root; parts.forEach((part, index) => { const path = parts.slice(0, index + 1).join("/"); const leaf = index === parts.length - 1; let child = node.children.find((entry) => entry.path === path && !entry.file === !leaf); if (!child) { child = { name: part, path, children: [], ...(leaf ? { file } : {}) }; node.children.push(child); } node = child; }); } const finish = (nodes: FileNode[]): FileNode[] => nodes .map((node) => { let current = { ...node, children: finish(node.children) }; while (!current.file && current.children.length === 1 && !current.children[0].file) { const only = current.children[0]; current = { ...only, name: `${current.name}/${only.name}` }; } return current; }) .sort((a, b) => Number(!!a.file) - Number(!!b.file) || a.name.localeCompare(b.name)); return finish(root.children); }