Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/application/ReferenceSourceImportEntries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { posix } from "node:path";
import { logicalPathEscapesRoot } from "../domain/artifactIdentity.js";
import {
createReferenceSourcePathLookup,
isPortableAbsoluteReferenceTarget,
type ReferenceSourcePathLookup,
} from "../domain/referenceSourcePathIdentity.js";
import {
Expand Down Expand Up @@ -190,15 +189,24 @@ const appendReadEntry = (
});
return;
}
if (entry.targetState === "unknown") {
output.entries.push({
path: entry.path,
kind: "symlink",
target: null,
target_state: "unknown",
classifications,
limitations: [entry.limitation],
});
return;
}
output.entries.push({
path: entry.path,
kind: "symlink",
// The reader resolves inventory identities from its root; the persisted
// graph represents relative symlink targets from the link's directory.
// Only canonical internal identities are root-relative. Missing targets
// retain their path components, relative to the link's directory when local.
target:
entry.targetState === "internal" ||
(entry.targetState === "missing" &&
!isPortableAbsoluteReferenceTarget(entry.target))
entry.targetState === "internal"
? posix.relative(posix.dirname(entry.path), entry.target) || "."
: entry.target,
target_state: entry.targetState,
Expand Down
6 changes: 4 additions & 2 deletions src/application/ReferenceSourceImportPolicy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { lstat, realpath, stat } from "node:fs/promises";
import { join, resolve } from "node:path";
import { join } from "node:path";

import ignore from "ignore";
import {
Expand Down Expand Up @@ -63,7 +63,9 @@ const resolveRoot = async (
`Reference source root is not a directory: ${requestedRoot}`,
),
);
const canonicalRoot = await realpath(resolve(requestedRoot));
// Let the filesystem interpret symlinks before parent components, exactly
// as it did for stat(); lexical normalization can select a different tree.
const canonicalRoot = await realpath(requestedRoot);
if (isAborted(signal))
return err(failure("cancelled", "Reference source import cancelled"));
return ok(canonicalRoot);
Expand Down
31 changes: 19 additions & 12 deletions src/reference/ReferenceSourceReaderEntries.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { BigIntStats, Dir, Dirent } from "node:fs";
import { opendir, readlink, realpath } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { join, normalize, sep } from "node:path";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactCleanupAttempt } from "../artifacts/ArtifactResourceScope.js";
import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js";
Expand Down Expand Up @@ -342,27 +342,34 @@ const readSymlinkTarget = async (
path: string,
): Promise<ReferenceSourceEntry> => {
const rawTarget = await readlink(absolute);
const lexicalTarget = resolve(dirname(absolute), rawTarget);
if (!isPathWithinRoot(root, lexicalTarget))
return {
status: "read",
kind: "symlink",
path,
target: lexicalTarget,
targetState: "external",
};
let canonicalTarget: string;
try {
canonicalTarget = await realpath(lexicalTarget);
// Resolve the observed link itself: normalizing its target first can change
// both the selected file and whether it lies inside the reference root.
// This observes metadata only; traversal never reads a symlink's contents.
canonicalTarget = await realpath(absolute);
} catch (cause: unknown) {
const code =
cause instanceof Error ? Reflect.get(cause, "code") : undefined;
if (code !== "ENOENT" && code !== "ENOTDIR") throw cause;
// The graph accepts normalized relative identities. A failed resolution
// cannot justify collapsing parent steps or directory intent into one;
// retain the observation as a limitation instead of naming another file.
const nativeTarget = rawTarget.replaceAll("/", sep);
if (normalize(nativeTarget) !== nativeTarget || nativeTarget.endsWith(sep))
return {
status: "read",
kind: "symlink",
path,
target: null,
targetState: "unknown",
limitation: `Symbolic link target ${JSON.stringify(rawTarget)} could not be resolved (${code}); its path intent cannot be normalized without changing the observation.`,
};
return {
status: "read",
kind: "symlink",
path,
target: pathFromRoot(root, lexicalTarget),
target: nativeTarget.split(sep).join("/"),
targetState: "missing",
};
}
Expand Down
10 changes: 9 additions & 1 deletion src/reference/ReferenceSourceReaderTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,18 @@ export type ReferenceSourceEntry =
readonly status: "read";
readonly kind: "symlink";
readonly path: string;
/** Internal and relative missing targets are resolved from the inventory root. */
/** Internal targets are root-relative; missing targets are link-relative, with native separators converted to '/'. */
readonly target: string;
readonly targetState: "internal" | "external" | "missing";
}
| {
readonly status: "read";
readonly kind: "symlink";
readonly path: string;
readonly target: null;
readonly targetState: "unknown";
readonly limitation: string;
}
| {
readonly status: "failed";
readonly kind: "file" | "directory" | "symlink" | "other" | "unknown";
Expand Down
38 changes: 37 additions & 1 deletion tests/boundary/cli/referenceSourceDirectoryImports.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdir, writeFile } from "node:fs/promises";
import { mkdir, realpath, symlink, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";

Expand All @@ -12,6 +12,42 @@ import { cliTest } from "../../support/cli/cliFixture.js";
describe.skipIf(process.platform === "win32")(
"compiled reference-source directory imports",
() => {
cliTest(
"imports the selected root before resolving symlink parent components",
async ({ cli }) => {
const workspace = await createTestTempDirectory(
"rea-reference-selected-root-",
);
const selectedRoot = join(workspace, "actual", "source");
await mkdir(join(workspace, "actual", "nested"), { recursive: true });
await mkdir(selectedRoot);
await mkdir(join(workspace, "source"));
await writeFile(join(selectedRoot, "selected.ts"), "export {};\n");
await writeFile(join(workspace, "source", "decoy.ts"), "export {};\n");
await symlink("actual/nested", join(workspace, "current"));
const selected = "current/../source";
expect(await realpath(`${workspace}/${selected}`)).toBe(selectedRoot);
const run = (root: string) =>
cli.run({
arguments: ["import-reference-source", root, "--json"],
cwd: workspace,
});
const control = await run(selectedRoot);
expect(control.exitCode).toBe(0);
const expected = historicalSourceGraphSchema.parse(control.json);
expect(expected.entries.map(({ path }) => path)).toEqual([
"selected.ts",
]);
for (const root of [selected, `${workspace}/${selected}`]) {
const result = await run(root);
expect(result.exitCode).toBe(0);
expect(historicalSourceGraphSchema.parse(result.json)).toEqual(
expected,
);
}
},
);

cliTest(
"resolves directory spellings without selecting similarly named files",
async ({ cli }) => {
Expand Down
106 changes: 105 additions & 1 deletion tests/boundary/filesystem/referenceSourceImport.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import fs from "node:fs";
import { chmod, mkdir, rm, symlink, writeFile } from "node:fs/promises";
import {
chmod,
mkdir,
realpath,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";

import { add, commit, init } from "isomorphic-git";
Expand Down Expand Up @@ -88,6 +95,103 @@ describe("reference source import projections", () => {
});
});

describe("reference source selected symlink paths", () => {
it.skipIf(process.platform === "win32")(
"records physical link targets and retains unresolved path intent",
async () => {
const workspace = await createTestTempDirectory(
"rea-reference-link-targets-",
);
const root = join(workspace, "source");
const outside = join(workspace, "outside");
await mkdir(join(root, "actual", "nested"), { recursive: true });
await mkdir(join(outside, "nested"), { recursive: true });
await writeFile(join(root, "target.js"), "export const decoy = 1;\n");
await writeFile(join(root, "actual", "target.js"), "export {};\n");
await writeFile(join(outside, "private.js"), "OUTSIDE_NOT_READ");
await symlink("actual/nested", join(root, "current"));
await symlink("../outside/nested", join(root, "outward"));
await symlink(root, join(outside, "back"));
const targets = new Map([
["relative.js", "current/../target.js"],
["absolute.js", `${root}/current/../target.js`],
["return.js", "../outside/back/actual/target.js"],
["external.js", "../outside/private.js"],
["escape.js", "outward/../private.js"],
["missing.js", "absent.js"],
["literal-backslash.js", "literal\\absent.js"],
["actual/missing.js", "../absent.js"],
["broken.js", "absent/../target.js"],
["absolute-broken.js", `${root}/absent/../target.js`],
["not-directory.js", "target.js/../target.js"],
["directory-intent.js", "target.js/"],
]);
for (const [name, target] of targets)
await symlink(target, join(root, name));
const expectedTarget = join(root, "actual", "target.js");
for (const name of ["relative.js", "absolute.js", "return.js"])
expect(await realpath(join(root, name))).toBe(expectedTarget);
const ambiguous = [
"broken.js",
"absolute-broken.js",
"not-directory.js",
"directory-intent.js",
];
for (const name of ambiguous)
await expect(realpath(join(root, name))).rejects.toMatchObject({
code: expect.stringMatching(/^(?:ENOENT|ENOTDIR)$/u),
});

const imported = await importTree(root);
if (!imported.ok) throw imported.error;
const entries = new Map(
imported.value.entries.map((entry) => [entry.path, entry]),
);
for (const name of ["relative.js", "absolute.js", "return.js"])
expect(entries.get(name)).toMatchObject({
kind: "symlink",
target: "actual/target.js",
target_state: "internal",
limitations: [],
});
for (const name of ["external.js", "escape.js"])
expect(entries.get(name)).toMatchObject({
kind: "symlink",
target: join(outside, "private.js"),
target_state: "external",
});
expect(entries.get("missing.js")).toMatchObject({
kind: "symlink",
target: "absent.js",
target_state: "missing",
});
expect(entries.get("actual/missing.js")).toMatchObject({
kind: "symlink",
target: "../absent.js",
target_state: "missing",
});
expect(entries.get("literal-backslash.js")).toMatchObject({
kind: "symlink",
target: "literal\\absent.js",
target_state: "missing",
});
for (const name of ambiguous)
expect(entries.get(name)).toMatchObject({
kind: "symlink",
target: null,
target_state: "unknown",
limitations: [expect.stringContaining(targets.get(name) ?? "")],
});
expect(
imported.value.entries
.filter(({ kind }) => kind === "file")
.map(({ path }) => path),
).toEqual(["actual/target.js", "target.js"]);
expect(JSON.stringify(imported.value)).not.toContain("OUTSIDE_NOT_READ");
},
);
});

describe("reference source symlink import", () => {
it.each([
{ target: "dist", reason: "default-ignored", pattern: "dist/" },
Expand Down
Loading