UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

53 lines (50 loc) 2.58 kB
import { lstat, stat, symlink, readlink } from 'node:fs/promises'; import { toNamespacedPath, dirname, resolve } from '@visulima/path'; import { toPath } from '@visulima/path/utils'; import assertValidFileOrDirectoryPath from './assertValidFileOrDirectoryPath-BWWgA1wj.mjs'; import ensureDir from './ensureDir-BnA_fY1A.mjs'; import { g as getFileInfoType } from './get-file-info-type-ButUVD6d.mjs'; import { i as isStatsIdentical } from './is-stats-identical-ByTYZ2Aw.mjs'; import { r as resolveSymlinkTarget } from './resolve-symlink-target-BbpEHdU2.mjs'; import AlreadyExistsError from './AlreadyExistsError-GK7J9fVA.mjs'; var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); const isWindows = process.platform === "win32" || /^(?:msys|cygwin)$/.test(process.env.OSTYPE); const ensureSymlink = /* @__PURE__ */ __name(async (target, linkName, type) => { assertValidFileOrDirectoryPath(target); assertValidFileOrDirectoryPath(linkName); const targetRealPath = resolveSymlinkTarget(target, linkName); linkName = toNamespacedPath(toPath(linkName)); try { const linkStatInfo = await lstat(linkName); if (linkStatInfo.isSymbolicLink() && // eslint-disable-next-line security/detect-non-literal-fs-filename isStatsIdentical(await stat(targetRealPath), await stat(linkName))) { const [sourceStat, destinationStat] = await Promise.all([stat(targetRealPath), stat(linkName)]); if (isStatsIdentical(sourceStat, destinationStat)) { return; } } } catch { } const sourceStatInfo = await lstat(targetRealPath); const sourceFilePathType = getFileInfoType(sourceStatInfo); await ensureDir(dirname(linkName)); const symlinkType = type ?? (isWindows ? "junction" : sourceFilePathType === "dir" ? "dir" : "file"); try { await symlink(toNamespacedPath(toPath(targetRealPath)), linkName, symlinkType); } catch (error) { if (error.code !== "EEXIST") { throw error; } const linkStatInfo = await lstat(linkName); if (!linkStatInfo.isSymbolicLink()) { throw new AlreadyExistsError("A " + getFileInfoType(linkStatInfo) + " already exists at the path: " + linkName); } const linkPath = await readlink(linkName); const linkRealPath = toNamespacedPath(resolve(linkPath)); if (linkRealPath !== targetRealPath) { throw new AlreadyExistsError("A symlink targeting to an undesired path already exists: " + linkName + " -> " + linkRealPath); } } }, "ensureSymlink"); export { ensureSymlink as default };