import { FileType, FsError, FsErrorCode, exists, isDirectory, isFile, listDir, mkdir, readFile, rmdir, unlink, } from 'zena:fs'; import {dirname, join2} from 'zena:path'; /** * Small filesystem helpers over zena:fs. Workspace paths are * slash-separated and relative to a root prefix; `withRoot` joins them * without normalizing, so the root may be absolute ('/tmp/x') or '' * for the current directory. */ /** * Joins and normalizes two workspace paths. The workspace root is `''` * throughout zebra — it keys the root package and appears in `.zebra/` state — * where zena:path spells it `'.'`, so `joinWorkspace('packages/zebra', * '../..')` is `''`. */ export function joinWorkspace(base: String, rel: String): String { let joined = join2(base, rel); return if (joined == '.') '' else joined; } export function withRoot(root: String, path: String): String { if (root == '') { return if (path == '') '.' else path; } if (path == '') { return root; } return `${root}/${path}`; } /** Creates a directory and its ancestors; safe under concurrent mkdirs. */ export async function ensureDir(path: String): Future { if (path == '' || path == '.' || await exists(path)) { return; } await ensureDir(dirname(path)); try { await mkdir(path); } catch (e) { if (!(e is FsError) || e.code != FsErrorCode.Exist) { throw e; } } } /** Creates the directory a file will be written into. */ export async function ensureParentDir(path: String): Future { await ensureDir(dirname(path)); } export async function deleteIfExists(path: String): Future { if (!(await isFile(path))) { return; } try { await unlink(path); } catch (e) { if (!(e is FsError) || e.code != FsErrorCode.NotFound) { throw e; } } } export async function readFileOrNull(path: String): Future { if (!(await isFile(path))) { return null; } return await readFile(path); } /** Recursively removes a file or directory tree if it exists. */ export async function removeTreeIfExists(path: String): Future { if (await isDirectory(path)) { try { for (let entry in await listDir(path)) { if (entry.name == '.' || entry.name == '..') { continue; } let child = `${path}/${entry.name}`; if (entry.fileType == FileType.Directory) { await removeTreeIfExists(child); } else { try { await unlink(child); } catch (e) { if (!(e is FsError) || e.code != FsErrorCode.NotFound) { throw e; } } } } await rmdir(path); } catch (e) { if (!(e is FsError) || e.code != FsErrorCode.NotFound) { throw e; } } return; } if (await exists(path)) { try { await unlink(path); } catch (e) { if (!(e is FsError) || e.code != FsErrorCode.NotFound) { throw e; } } } }