forked from denoland/deno_std
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ensure_symlink.ts
80 lines (70 loc) · 2.28 KB
/
ensure_symlink.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { dirname } from "../path/dirname.ts";
import { resolve } from "../path/resolve.ts";
import { ensureDir, ensureDirSync } from "./ensure_dir.ts";
import { getFileInfoType, toPathString } from "./_util.ts";
const isWindows = Deno.build.os === "windows";
function resolveSymlinkTarget(target: string | URL, linkName: string | URL) {
if (typeof target !== "string") return target; // URL is always absolute path
if (typeof linkName === "string") {
return resolve(dirname(linkName), target);
} else {
return new URL(target, linkName);
}
}
/**
* Ensures that the link exists, and points to a valid file.
* If the directory structure does not exist, it is created.
*
* @param target the source file path
* @param linkName the destination link path
*/
export async function ensureSymlink(
target: string | URL,
linkName: string | URL,
) {
const targetRealPath = resolveSymlinkTarget(target, linkName);
const srcStatInfo = await Deno.lstat(targetRealPath);
const srcFilePathType = getFileInfoType(srcStatInfo);
await ensureDir(dirname(toPathString(linkName)));
const options: Deno.SymlinkOptions | undefined = isWindows
? {
type: srcFilePathType === "dir" ? "dir" : "file",
}
: undefined;
try {
await Deno.symlink(target, linkName, options);
} catch (error) {
if (!(error instanceof Deno.errors.AlreadyExists)) {
throw error;
}
}
}
/**
* Ensures that the link exists, and points to a valid file.
* If the directory structure does not exist, it is created.
*
* @param target the source file path
* @param linkName the destination link path
*/
export function ensureSymlinkSync(
target: string | URL,
linkName: string | URL,
) {
const targetRealPath = resolveSymlinkTarget(target, linkName);
const srcStatInfo = Deno.lstatSync(targetRealPath);
const srcFilePathType = getFileInfoType(srcStatInfo);
ensureDirSync(dirname(toPathString(linkName)));
const options: Deno.SymlinkOptions | undefined = isWindows
? {
type: srcFilePathType === "dir" ? "dir" : "file",
}
: undefined;
try {
Deno.symlinkSync(target, linkName, options);
} catch (error) {
if (!(error instanceof Deno.errors.AlreadyExists)) {
throw error;
}
}
}