UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

59 lines (55 loc) 2.82 kB
'use strict'; const node_fs = require('node:fs'); const path = require('@visulima/path'); const utils = require('@visulima/path/utils'); const assertValidFileOrDirectoryPath = require('./assertValidFileOrDirectoryPath-BMbgA-eI.cjs'); const ensureDirSync = require('./ensureDirSync-DHmWi3CF.cjs'); const getFileInfoType = require('./get-file-info-type-BlryFnpp.cjs'); const isStatsIdentical = require('./is-stats-identical-BfdEfO6i.cjs'); const resolveSymlinkTarget = require('./resolve-symlink-target-DImIddt6.cjs'); const AlreadyExistsError = require('./AlreadyExistsError-DpxtwQot.cjs'); 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 ensureSymlinkSync = /* @__PURE__ */ __name((target, linkName, type) => { assertValidFileOrDirectoryPath(target); assertValidFileOrDirectoryPath(linkName); const targetRealPath = resolveSymlinkTarget.resolveSymlinkTarget(target, linkName); linkName = path.toNamespacedPath(utils.toPath(linkName)); try { const linkStatInfo = node_fs.lstatSync(linkName); if (linkStatInfo.isSymbolicLink() && // eslint-disable-next-line security/detect-non-literal-fs-filename isStatsIdentical.isStatsIdentical(node_fs.statSync(targetRealPath), node_fs.statSync(linkName))) { const sourceStat = node_fs.statSync(targetRealPath); const destinationStat = node_fs.statSync(linkName); if (isStatsIdentical.isStatsIdentical(sourceStat, destinationStat)) { return; } } } catch { } const sourceStatInfo = node_fs.lstatSync(targetRealPath); const sourceFilePathType = getFileInfoType.getFileInfoType(sourceStatInfo); ensureDirSync(path.dirname(linkName)); const symlinkType = type ?? (isWindows ? "junction" : sourceFilePathType === "dir" ? "dir" : "file"); try { node_fs.symlinkSync(path.toNamespacedPath(utils.toPath(targetRealPath)), linkName, symlinkType); } catch (error) { if (error.code !== "EEXIST") { throw error; } const linkStatInfo = node_fs.lstatSync(linkName); if (!linkStatInfo.isSymbolicLink()) { throw new AlreadyExistsError("A " + getFileInfoType.getFileInfoType(linkStatInfo) + " already exists at the path: " + linkName); } const linkPath = node_fs.readlinkSync(linkName); const linkRealPath = path.toNamespacedPath(path.resolve(linkPath)); if (linkRealPath !== targetRealPath) { throw new AlreadyExistsError( // eslint-disable-next-line @typescript-eslint/restrict-plus-operands "A symlink targeting to an undesired path already exists: " + linkName + " -> " + linkRealPath ); } } }, "ensureSymlinkSync"); module.exports = ensureSymlinkSync;