Repository navigation
Expand file tree
/
Copy pathWorkspaceFileSystem.ts
More file actions
514 lines (485 loc) · 18.8 KB
/
Copy pathWorkspaceFileSystem.ts
File metadata and controls
514 lines (485 loc) · 18.8 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import type {
FilesystemEntryMetadata,
FilesystemGetMetadataInput,
FilesystemGetMetadataResult,
ProjectReadFileInput,
ProjectReadFileResult,
ProjectWriteFileInput,
ProjectWriteFileResult,
} from "@t3tools/contracts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as KnownWorkspaces from "./KnownWorkspaces.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
// Windows also reaches `.git` through trailing dots or spaces, a `:` stream
// suffix, or the 8.3 short name `GIT~1`. Names compare upcased, as NTFS does.
const isGitMetadataName = (segment: string) => {
const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase();
return name === ".GIT" || name === "GIT~1";
};
export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
"WorkspaceFileSystemOperationError",
{
workspaceRoot: Schema.String,
relativePath: Schema.String,
resolvedPath: Schema.String,
operationPath: Schema.String,
operation: Schema.Literals([
"realpath-workspace-root",
"realpath-target",
"open",
"stat",
"read",
"close",
"make-directory",
"write-file",
]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
}
}
export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
"WorkspaceFilePathEscapeError",
{
workspaceRoot: Schema.String,
relativePath: Schema.String,
resolvedWorkspaceRoot: Schema.String,
resolvedPath: Schema.String,
},
) {
override get message(): string {
return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
}
}
export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
"WorkspacePathNotFileError",
{
workspaceRoot: Schema.String,
relativePath: Schema.String,
resolvedPath: Schema.String,
},
) {
override get message(): string {
return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
}
}
export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
"WorkspaceBinaryFileError",
{
workspaceRoot: Schema.String,
relativePath: Schema.String,
resolvedPath: Schema.String,
},
) {
override get message(): string {
return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
}
}
export const WorkspaceFileSystemError = Schema.Union([
WorkspaceFileSystemOperationError,
WorkspaceFilePathEscapeError,
WorkspacePathNotFileError,
WorkspaceBinaryFileError,
]);
export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
export class WorkspaceFileSystem extends Context.Service<
WorkspaceFileSystem,
{
readonly getMetadata: (
input: FilesystemGetMetadataInput,
) => Effect.Effect<FilesystemGetMetadataResult>;
readonly readFile: (
input: ProjectReadFileInput,
) => Effect.Effect<
ProjectReadFileResult,
WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
>;
/** Writes inside a known workspace only. */
readonly writeFile: (
input: ProjectWriteFileInput,
) => Effect.Effect<
ProjectWriteFileResult,
| WorkspaceFileSystemError
| WorkspacePaths.WorkspacePathOutsideRootError
| KnownWorkspaces.UnknownWorkspaceError
>;
}
>()("t3/workspace/WorkspaceFileSystem") {}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
if (!path.isAbsolute(expandedPath)) return null;
const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
if (stat._tag === "None") return null;
if (stat.value.type === "Directory") return { kind: "directory" } as const;
if (stat.value.type !== "File") return { kind: "other" } as const;
let mimeType: string | undefined;
if (path.extname(expandedPath) === "" && stat.value.size > 0) {
mimeType = yield* Effect.tryPromise({
try: async () => {
const handle = await NodeFSP.open(
expandedPath,
NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK,
);
try {
if (!(await handle.stat()).isFile()) return undefined;
const buffer = Buffer.alloc(512);
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
return fileHeaderMimeType(buffer.subarray(0, bytesRead));
} finally {
await handle.close();
}
},
catch: () => undefined,
}).pipe(Effect.catch(() => Effect.succeed(undefined)));
}
return {
kind: "file",
byteLength: Number(stat.value.size),
...(mimeType === undefined ? {} : { mimeType }),
} satisfies FilesystemEntryMetadata;
});
const getMetadata: WorkspaceFileSystem["Service"]["getMetadata"] = Effect.fn(
"WorkspaceFileSystem.getMetadata",
)(function* (input) {
const paths = [...new Set(input.paths)];
const entries = yield* Effect.forEach(paths, metadataForPath, { concurrency: 8 });
const byPath = new Map(paths.map((value, index) => [value, entries[index] ?? null]));
return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
});
/** Both paths must already be real paths. */
const isInsideRealRoot = (realWorkspaceRoot: string, realPath: string) => {
const relative = path.relative(realWorkspaceRoot, realPath);
return !(
relative.startsWith(`..${path.sep}`) ||
relative === ".." ||
path.isAbsolute(relative)
);
};
/**
* Git runs config and hooks from its own folders, so a write never lands in one:
* a `.git` entry, or a repository folder under another name such as `.bare`.
* Folders are checked upward to a linked worktree's top, which holds a `.git`
* file, since worktrees can sit inside a bare repository. `absolutePath` must
* be normalized.
*/
const isInGitFolder = async (absolutePath: string) => {
if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
const [head, commondir, objects, refs, dotGit] = await Promise.all(
["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
// Any other failure leaves the folder unknown, so the write is refused.
if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
throw error;
}),
),
);
// What git reads as a repository: HEAD, plus objects and refs here or in
// the folder a `commondir` file names, as in a linked worktree's git folder.
if (head && (commondir || (objects && refs))) return true;
if (dotGit?.isFile() || path.dirname(folder) === folder) return false;
}
};
/**
* Workspace-relative paths must stay inside the root, symlinks included. An
* absolute path reads a host file in place, such as a report an agent wrote to a
* temp directory; it gets no root check.
*/
const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
input: ProjectReadFileInput,
) {
const requestedPath = input.relativePath.trim();
if (path.isAbsolute(requestedPath)) {
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(requestedPath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: requestedPath,
operationPath: requestedPath,
operation: "realpath-target",
cause,
}),
});
return { relativePath: requestedPath, realTargetPath };
}
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(path.resolve(input.cwd)),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
if (!isInsideRealRoot(realWorkspaceRoot, realTargetPath)) {
return yield* new WorkspaceFilePathEscapeError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedWorkspaceRoot: realWorkspaceRoot,
resolvedPath: realTargetPath,
});
}
return { relativePath: target.relativePath, realTargetPath };
});
const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
"WorkspaceFileSystem.readFile",
)(function* (input) {
const target = yield* resolveReadTarget(input);
const realTargetPath = target.realTargetPath;
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
// Non-blocking so a FIFO cannot hang the open; the stat below rejects
// it. Regular files ignore the flag. Windows lacks it.
try: () =>
NodeFSP.open(
realTargetPath,
NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
);
});
/**
* Resolves the file a write targets. The deepest existing ancestor resolves to
* its real path before the root check, so neither the file nor the directories
* created for it can follow a symlink out of the root. A dangling symlink is
* rejected rather than written through.
*/
const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
input: ProjectWriteFileInput,
) {
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
// Resolve `..` in cwd the way the relative path was resolved, before following links.
try: () => NodeFSP.realpath(path.resolve(input.cwd)),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
// Split the host path, not the display relativePath: on POSIX `\` is a file name character.
const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
const realTargetPath = yield* Effect.tryPromise({
try: async () => {
for (let depth = segments.length; depth > 0; depth--) {
const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
try {
return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
} catch (error) {
// Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
const exists = await NodeFSP.lstat(candidate).then(
() => true,
() => false,
);
if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
}
}
return path.join(realWorkspaceRoot, ...segments);
},
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
// The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
Effect.tryPromise({
try: () => isInGitFolder(checkedPath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: checkedPath,
operation: "stat",
cause,
}),
}),
);
if (
!isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
(yield* inGitFolder(realTargetPath)) ||
(yield* inGitFolder(namedTargetPath))
) {
return yield* new WorkspaceFilePathEscapeError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedWorkspaceRoot: realWorkspaceRoot,
resolvedPath: realTargetPath,
});
}
return { relativePath: target.relativePath, realTargetPath };
});
const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
"WorkspaceFileSystem.writeFile",
)(function* (input) {
yield* knownWorkspaces.assertContains(input.cwd);
const target = yield* resolveWriteTarget(input);
const realTargetPath = target.realTargetPath;
yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: path.dirname(realTargetPath),
operation: "make-directory",
cause,
}),
),
);
yield* Effect.tryPromise({
// A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
try: () =>
NodeFSP.writeFile(realTargetPath, input.contents, {
flag:
NodeFS.constants.O_WRONLY |
NodeFS.constants.O_CREAT |
NodeFS.constants.O_TRUNC |
(NodeFS.constants.O_NOFOLLOW ?? 0),
}),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "write-file",
cause,
}),
});
yield* workspaceEntries.refresh(input.cwd);
return { relativePath: target.relativePath };
});
return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
});
export const layer = Layer.effect(WorkspaceFileSystem, make);