@visulima/fs
Version:
Human friendly file system utilities for Node.js
57 lines (54 loc) • 2.67 kB
JavaScript
import { lstatSync, statSync, symlinkSync, readlinkSync } from 'node:fs';
import { toNamespacedPath, dirname, resolve } from '@visulima/path';
import { toPath } from '@visulima/path/utils';
import assertValidFileOrDirectoryPath from './assertValidFileOrDirectoryPath-BWWgA1wj.mjs';
import ensureDirSync from './ensureDirSync-Dm4az3YF.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 ensureSymlinkSync = /* @__PURE__ */ __name((target, linkName, type) => {
assertValidFileOrDirectoryPath(target);
assertValidFileOrDirectoryPath(linkName);
const targetRealPath = resolveSymlinkTarget(target, linkName);
linkName = toNamespacedPath(toPath(linkName));
try {
const linkStatInfo = lstatSync(linkName);
if (linkStatInfo.isSymbolicLink() && // eslint-disable-next-line security/detect-non-literal-fs-filename
isStatsIdentical(statSync(targetRealPath), statSync(linkName))) {
const sourceStat = statSync(targetRealPath);
const destinationStat = statSync(linkName);
if (isStatsIdentical(sourceStat, destinationStat)) {
return;
}
}
} catch {
}
const sourceStatInfo = lstatSync(targetRealPath);
const sourceFilePathType = getFileInfoType(sourceStatInfo);
ensureDirSync(dirname(linkName));
const symlinkType = type ?? (isWindows ? "junction" : sourceFilePathType === "dir" ? "dir" : "file");
try {
symlinkSync(toNamespacedPath(toPath(targetRealPath)), linkName, symlinkType);
} catch (error) {
if (error.code !== "EEXIST") {
throw error;
}
const linkStatInfo = lstatSync(linkName);
if (!linkStatInfo.isSymbolicLink()) {
throw new AlreadyExistsError("A " + getFileInfoType(linkStatInfo) + " already exists at the path: " + linkName);
}
const linkPath = readlinkSync(linkName);
const linkRealPath = toNamespacedPath(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");
export { ensureSymlinkSync as default };