file-walk.ts
This file
Path
packages/project/src/code/file-walk.ts
67 lines · 2.0 KiB · TypeScript
Last changed by
Merge build/comments-project into mainoscabrielbefore adoption49efd2a
History of this fileTake it
Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 1why, one step back1// A store answers a few dozen calls a second, and walking a path by its folders costs two to three calls a commit; reading a small file whole costs one.Walk a small file's history by reading it whole at each commit: one call a commit instead of its foldersoscabrielbefore adoption8310fed
lines 2–67why, one step back2import { RepoHost, Revision } from "@repo/artifacts/repo-host";3import type { RepoNotFound } from "@repo/artifacts/repo-host";4import { BlobSha } from "@repo/protocol/ids";5import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";6import { Effect, Option } from "effect";78export const FILE_WALK_CAP = 256 * 1024;910const encoder = new TextEncoder();1112const hex = (digest: ArrayBuffer) =>13 [...new Uint8Array(digest)]14 .map((byte) => byte.toString(16).padStart(2, "0"))15 .join("");1617export const blobIdOf = (bytes: Uint8Array): Effect.Effect<BlobSha> =>18 Effect.gen(function* () {19 const header = encoder.encode(`blob ${bytes.byteLength}\0`);20 const raw = new Uint8Array(header.byteLength + bytes.byteLength);2122 raw.set(header);23 raw.set(bytes, header.byteLength);2425 const digest = yield* Effect.promise(() =>26 crypto.subtle.digest("SHA-1", raw)27 );2829 return BlobSha.make(hex(digest));30 });3132export const fileAt = (33 repo: RepoName,34 commit: CommitSha,35 path: RepoPath36): Effect.Effect<Option.Option<Uint8Array>, RepoNotFound, RepoHost> =>37 RepoHost.use((host) =>38 host.readFile(repo, Revision.Commit({ sha: commit }), path)39 );4041export interface FileVersion {42 readonly blob: BlobSha;43 readonly bytes: Uint8Array;44}4546export const versionAt = (47 repo: RepoName,48 commit: CommitSha,49 path: RepoPath50): Effect.Effect<Option.Option<FileVersion>, RepoNotFound, RepoHost> =>51 Effect.flatMap(fileAt(repo, commit, path), (read) =>52 Option.match(read, {53 onNone: () => Effect.succeedNone,54 onSome: (bytes) =>55 Effect.map(blobIdOf(bytes), (blob) => Option.some({ blob, bytes })),56 })57 );5859export const walkableAt = (60 repo: RepoName,61 commit: CommitSha,62 path: RepoPath63): Effect.Effect<Option.Option<FileVersion>, RepoNotFound, RepoHost> =>64 Effect.map(65 versionAt(repo, commit, path),66 Option.filter(({ bytes }) => bytes.byteLength <= FILE_WALK_CAP)67 );