Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as PlatformError from "effect/PlatformError";
6
7const MAX_SYMLINK_HOPS = 40;
8
9const isNotFound = (error: PlatformError.PlatformError) => error.reason._tag === "NotFound";
10
11const isNotASymlink = (error: PlatformError.PlatformError) =>
12 isNotFound(error) ||
13 (error.cause instanceof Error && "code" in error.cause && error.cause.code === "EINVAL");
14
15/**
16 * Atomic writers rename onto this path so a linked file keeps its link. Fails
17 * on a cycle, an overly long chain, or an unreadable link rather than handing
18 * back a link that a rename would replace.
19 */
20export const resolveSymlinkTarget = (filePath: string) =>
21 Effect.gen(function* () {
22 const fs = yield* FileSystem.FileSystem;
23 const path = yield* Path.Path;
24 let current = path.resolve(filePath);
25 for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {
26 const link = yield* fs.readLink(current).pipe(
27 Effect.map(Option.some),
28 Effect.catchIf(isNotASymlink, () => Effect.succeedNone),
29 );
30 if (Option.isNone(link)) {
31 return current;
32 }
33 // A relative target is relative to where the link really lives, which
34 // differs from its lexical parent when that parent is itself a symlink.
35 const linkDirectory = yield* fs
36 .realPath(path.dirname(current))
37 .pipe(Effect.catchIf(isNotFound, () => Effect.succeed(path.dirname(current))));
38 current = path.resolve(linkDirectory, link.value);
39 }
40 return yield* PlatformError.systemError({
41 _tag: "Unknown",
42 module: "FileSystem",
43 method: "readLink",
44 description: "Too many levels of symbolic links",
45 pathOrDescriptor: filePath,
46 });
47 });