The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not. |
| 2 | import * as NodeChildProcess from "node:child_process"; |
| 3 | import * as NodeFS from "node:fs"; |
| 4 | import * as NodeNet from "node:net"; |
| 5 | import * as NodePath from "node:path"; |
| 6 | import * as NodeURL from "node:url"; |
| 7 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 8 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 9 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 10 | import { assert, it, describe } from "@effect/vitest"; |
| 11 | import { afterAll, vi } from "vite-plus/test"; |
| 12 | import * as Cause from "effect/Cause"; |
| 13 | import * as Clock from "effect/Clock"; |
| 14 | import * as Deferred from "effect/Deferred"; |
| 15 | import * as Duration from "effect/Duration"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import * as Exit from "effect/Exit"; |
| 18 | import * as FileSystem from "effect/FileSystem"; |
| 19 | import * as Fiber from "effect/Fiber"; |
| 20 | import * as Layer from "effect/Layer"; |
| 21 | import * as Option from "effect/Option"; |
| 22 | import * as Path from "effect/Path"; |
| 23 | import * as Queue from "effect/Queue"; |
| 24 | import * as PlatformError from "effect/PlatformError"; |
| 25 | import * as Ref from "effect/Ref"; |
| 26 | import * as Result from "effect/Result"; |
| 27 | import * as Scope from "effect/Scope"; |
| 28 | import * as Schema from "effect/Schema"; |
| 29 | import * as Sink from "effect/Sink"; |
| 30 | import * as Stream from "effect/Stream"; |
| 31 | import * as TestClock from "effect/testing/TestClock"; |
| 32 | import * as Tracer from "effect/Tracer"; |
| 33 | import { ChildProcess, ChildProcessSpawner, CommandLine } from "effect/process"; |
| 34 | |
| 35 | import { |
| 36 | DEFAULT_SERVER_SETTINGS, |
| 37 | GitCommandError, |
| 38 | ProjectId, |
| 39 | ReviewDiffPreviewInput, |
| 40 | VcsRef, |
| 41 | VcsListRefsResult, |
| 42 | type ReviewDiffFileContentsInput, |
| 43 | type ReviewDiffPreviewResult, |
| 44 | type WorktreeSubmodules, |
| 45 | } from "@t3tools/contracts"; |
| 46 | import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; |
| 47 | import * as ServerConfig from "../config.ts"; |
| 48 | import { |
| 49 | isNonRepositoryGitStderr, |
| 50 | makeGitVcsDriverCore, |
| 51 | parseGitCheckoutProgressLine, |
| 52 | splitNullSeparatedGitStdoutPaths, |
| 53 | windowsLongPathConfigEnv, |
| 54 | } from "./GitVcsDriverCore.ts"; |
| 55 | import { autoPullProjects } from "../serverRuntimeStartup.ts"; |
| 56 | import * as GitVcsDriver from "./GitVcsDriver.ts"; |
| 57 | import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; |
| 58 | import { gitConfigEnv } from "./VcsProcess.ts"; |
| 59 | |
| 60 | const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError)); |
| 61 | const decodeVcsRef = Schema.decodeUnknownSync(VcsRef); |
| 62 | const decodeVcsListRefsResult = Schema.decodeUnknownSync(VcsListRefsResult); |
| 63 | |
| 64 | const layerServerConfig = ServerConfig.layerTest(process.cwd(), { |
| 65 | prefix: "t3-git-vcs-driver-test-", |
| 66 | }); |
| 67 | const layerTest = GitVcsDriver.layer.pipe( |
| 68 | Layer.provideMerge(layerServerConfig), |
| 69 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 70 | ); |
| 71 | |
| 72 | const makeNonRepositoryHandle = () => |
| 73 | ChildProcessSpawner.makeHandle({ |
| 74 | pid: ChildProcessSpawner.ProcessId(1), |
| 75 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)), |
| 76 | isRunning: Effect.succeed(false), |
| 77 | kill: () => Effect.void, |
| 78 | unref: Effect.succeed(Effect.void), |
| 79 | stdin: Sink.drain, |
| 80 | stdout: Stream.empty, |
| 81 | stderr: Stream.encodeText(Stream.make("fatal: not a git repository")), |
| 82 | all: Stream.empty, |
| 83 | getInputFd: () => Sink.drain, |
| 84 | getOutputFd: () => Stream.empty, |
| 85 | }); |
| 86 | |
| 87 | const makeSuccessfulHandle = (stdout: string) => |
| 88 | ChildProcessSpawner.makeHandle({ |
| 89 | pid: ChildProcessSpawner.ProcessId(1), |
| 90 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), |
| 91 | isRunning: Effect.succeed(false), |
| 92 | kill: () => Effect.void, |
| 93 | unref: Effect.succeed(Effect.void), |
| 94 | stdin: Sink.drain, |
| 95 | stdout: Stream.encodeText(Stream.make(stdout)), |
| 96 | stderr: Stream.empty, |
| 97 | all: Stream.empty, |
| 98 | getInputFd: () => Sink.drain, |
| 99 | getOutputFd: () => Stream.empty, |
| 100 | }); |
| 101 | |
| 102 | const makeFailedHandle = (stderr: string) => |
| 103 | ChildProcessSpawner.makeHandle({ |
| 104 | ...makeNonRepositoryHandle(), |
| 105 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), |
| 106 | stderr: Stream.encodeText(Stream.make(stderr)), |
| 107 | }); |
| 108 | |
| 109 | // Releases the lock as soon as a matching git command fails on it, before the driver retries. |
| 110 | const makeDriverReleasingLock = ( |
| 111 | matches: (args: ReadonlyArray<string>) => boolean, |
| 112 | lockPath: string, |
| 113 | ) => |
| 114 | Effect.gen(function* () { |
| 115 | const failures = yield* Ref.make(0); |
| 116 | const fileSystem = yield* FileSystem.FileSystem; |
| 117 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 118 | const spawner = ChildProcessSpawner.make((command) => |
| 119 | Effect.gen(function* () { |
| 120 | const handle = yield* delegate.spawn(command); |
| 121 | if (!ChildProcess.isStandardCommand(command) || !matches(command.args.map(String))) |
| 122 | return handle; |
| 123 | return ChildProcessSpawner.makeHandle({ |
| 124 | ...handle, |
| 125 | exitCode: handle.exitCode.pipe( |
| 126 | Effect.tap((exitCode) => |
| 127 | exitCode === 0 |
| 128 | ? Effect.void |
| 129 | : Ref.update(failures, (count) => count + 1).pipe( |
| 130 | Effect.andThen(fileSystem.remove(lockPath, { force: true })), |
| 131 | Effect.orDie, |
| 132 | ), |
| 133 | ), |
| 134 | ), |
| 135 | }); |
| 136 | }), |
| 137 | ); |
| 138 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 139 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 140 | Effect.provide(layerServerConfig), |
| 141 | ); |
| 142 | return { driver, failures }; |
| 143 | }); |
| 144 | |
| 145 | describe("isNonRepositoryGitStderr", () => { |
| 146 | it.each([ |
| 147 | "fatal: not a git repository (or any of the parent directories): .git", |
| 148 | "fatal: not a git repository: /missing-git-directory", |
| 149 | // Git 2.56+ wording for a `.git` gitfile that points at a missing directory. |
| 150 | "fatal: gitfile does not point to a valid repository: /tmp/worktrees/feature/.git", |
| 151 | "FATAL: GITFILE DOES NOT POINT TO A VALID REPOSITORY: /tmp/x/.git", |
| 152 | ])("classifies %j as a non-repository", (stderr) => { |
| 153 | assert.isTrue(isNonRepositoryGitStderr(stderr)); |
| 154 | }); |
| 155 | |
| 156 | it.each([ |
| 157 | "", |
| 158 | "fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.", |
| 159 | "fatal: Unable to create '/repo/.git/index.lock': File exists.", |
| 160 | "fatal: invalid gitfile format: /repo/.git", |
| 161 | ])("does not classify %j as a non-repository", (stderr) => { |
| 162 | assert.isFalse(isNonRepositoryGitStderr(stderr)); |
| 163 | }); |
| 164 | }); |
| 165 | |
| 166 | it.effect("runs background Git in its own lane so user commands never queue behind it", () => |
| 167 | Effect.gen(function* () { |
| 168 | const gate = yield* Deferred.make<void>(); |
| 169 | const starts = yield* Queue.unbounded<string>(); |
| 170 | const spawner = ChildProcessSpawner.make((command) => |
| 171 | Effect.gen(function* () { |
| 172 | yield* Queue.offer( |
| 173 | starts, |
| 174 | ChildProcess.isStandardCommand(command) ? String(command.args[0]) : "", |
| 175 | ); |
| 176 | return ChildProcessSpawner.makeHandle({ |
| 177 | ...makeSuccessfulHandle("ok"), |
| 178 | exitCode: Deferred.await(gate).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), |
| 179 | }); |
| 180 | }), |
| 181 | ); |
| 182 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 183 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 184 | Effect.provide(layerServerConfig), |
| 185 | ); |
| 186 | const run = (args: ReadonlyArray<string>) => |
| 187 | driver.execute({ operation: "test.gitLane", cwd: "/repo", args: [...args] }); |
| 188 | const background = yield* Effect.forEach( |
| 189 | Array.from({ length: 12 }), |
| 190 | () => run(["background"]), |
| 191 | { |
| 192 | concurrency: "unbounded", |
| 193 | }, |
| 194 | ).pipe(Effect.provideService(GitVcsDriver.BackgroundGitWork, true), Effect.forkChild); |
| 195 | const foreground = yield* Effect.forEach(Array.from({ length: 4 }), () => run(["foreground"]), { |
| 196 | concurrency: "unbounded", |
| 197 | }).pipe(Effect.forkChild); |
| 198 | |
| 199 | yield* TestClock.adjust("2 seconds"); |
| 200 | const started = yield* Queue.takeAll(starts); |
| 201 | assert.deepStrictEqual([...started].toSorted(), [ |
| 202 | "background", |
| 203 | "background", |
| 204 | "foreground", |
| 205 | "foreground", |
| 206 | "foreground", |
| 207 | "foreground", |
| 208 | ]); |
| 209 | yield* Deferred.succeed(gate, undefined); |
| 210 | assert.equal((yield* Fiber.join(background)).length, 12); |
| 211 | assert.equal((yield* Fiber.join(foreground)).length, 4); |
| 212 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 213 | ); |
| 214 | |
| 215 | describe("Git output collection", () => { |
| 216 | // Git writes in arbitrary chunk sizes; one byte per chunk splits every |
| 217 | // multibyte character across reads. |
| 218 | const byteChunks = (text: string) => |
| 219 | Stream.fromIterable(Array.from(new TextEncoder().encode(text), (byte) => Uint8Array.of(byte))); |
| 220 | const makeDriver = (output: { stdout?: string; stderr?: string }) => |
| 221 | makeGitVcsDriverCore().pipe( |
| 222 | Effect.provideService( |
| 223 | ChildProcessSpawner.ChildProcessSpawner, |
| 224 | ChildProcessSpawner.make(() => |
| 225 | Effect.succeed( |
| 226 | ChildProcessSpawner.makeHandle({ |
| 227 | ...makeSuccessfulHandle(""), |
| 228 | stdout: byteChunks(output.stdout ?? ""), |
| 229 | stderr: byteChunks(output.stderr ?? ""), |
| 230 | }), |
| 231 | ), |
| 232 | ), |
| 233 | ), |
| 234 | ); |
| 235 | |
| 236 | it.effect("returns the same split UTF-8 and NUL output with and without line callbacks", () => |
| 237 | Effect.gen(function* () { |
| 238 | const stdout = "a\\b\0雪\nlast "; |
| 239 | const stderr = "Receiving é\r\nUpdating 雪\rdone"; |
| 240 | const driver = yield* makeDriver({ stdout, stderr }); |
| 241 | const input = { operation: "test.chunkedGitOutput", cwd: "/repo", args: ["status"] }; |
| 242 | const expected = { |
| 243 | exitCode: 0, |
| 244 | stdout, |
| 245 | stderr, |
| 246 | stdoutTruncated: false, |
| 247 | stderrTruncated: false, |
| 248 | }; |
| 249 | |
| 250 | assert.deepEqual(yield* driver.execute(input), expected); |
| 251 | |
| 252 | const stdoutLines: string[] = []; |
| 253 | const stderrLines: string[] = []; |
| 254 | const withCallbacks = yield* driver.execute({ |
| 255 | ...input, |
| 256 | progress: { |
| 257 | onStdoutLine: (line) => Effect.sync(() => void stdoutLines.push(line)), |
| 258 | onStderrLine: (line) => Effect.sync(() => void stderrLines.push(line)), |
| 259 | }, |
| 260 | }); |
| 261 | assert.deepEqual(withCallbacks, expected); |
| 262 | assert.deepEqual(stdoutLines, ["a\\b\0雪", "last "]); |
| 263 | assert.deepEqual(stderrLines, ["Receiving é", "Updating 雪", "done"]); |
| 264 | }).pipe( |
| 265 | Effect.provide( |
| 266 | layerServerConfig.pipe( |
| 267 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 268 | ), |
| 269 | ), |
| 270 | ), |
| 271 | ); |
| 272 | |
| 273 | it.effect("caps output without line callbacks", () => |
| 274 | Effect.gen(function* () { |
| 275 | const driver = yield* makeDriver({ stderr: "é雪\rdone" }); |
| 276 | const input = { |
| 277 | operation: "test.cappedGitOutput", |
| 278 | cwd: "/repo", |
| 279 | args: ["status"], |
| 280 | maxOutputBytes: 3, |
| 281 | }; |
| 282 | |
| 283 | const truncated = yield* driver.execute({ ...input, appendTruncationMarker: true }); |
| 284 | assert.equal(truncated.stderr, "é\uFFFD"); |
| 285 | assert.isTrue(truncated.stderrTruncated); |
| 286 | |
| 287 | const error = yield* driver.execute(input).pipe(Effect.flip); |
| 288 | assert.equal(error.outputLength, 4); |
| 289 | assert.include(error.detail, "exceeded 3 bytes"); |
| 290 | }).pipe( |
| 291 | Effect.provide( |
| 292 | layerServerConfig.pipe( |
| 293 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 294 | ), |
| 295 | ), |
| 296 | ), |
| 297 | ); |
| 298 | }); |
| 299 | |
| 300 | const makeTmpDir = ( |
| 301 | prefix = "git-vcs-driver-test-", |
| 302 | ): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> => |
| 303 | Effect.gen(function* () { |
| 304 | const fileSystem = yield* FileSystem.FileSystem; |
| 305 | return yield* fileSystem.makeTempDirectoryScoped({ prefix }); |
| 306 | }); |
| 307 | |
| 308 | const writeTextFile = ( |
| 309 | cwd: string, |
| 310 | relativePath: string, |
| 311 | contents: string, |
| 312 | ): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> => |
| 313 | Effect.gen(function* () { |
| 314 | const fileSystem = yield* FileSystem.FileSystem; |
| 315 | const pathService = yield* Path.Path; |
| 316 | const filePath = pathService.join(cwd, relativePath); |
| 317 | yield* fileSystem.makeDirectory(pathService.dirname(filePath), { recursive: true }); |
| 318 | yield* fileSystem.writeFileString(filePath, contents); |
| 319 | }); |
| 320 | |
| 321 | const makeReviewDiffFileContentsInput = ( |
| 322 | cwd: string, |
| 323 | overrides: Partial<Omit<ReviewDiffFileContentsInput, "cwd">> = {}, |
| 324 | ): ReviewDiffFileContentsInput => ({ |
| 325 | cwd, |
| 326 | sourceKind: "working-tree", |
| 327 | changeType: "change", |
| 328 | baseRef: "HEAD", |
| 329 | headRef: null, |
| 330 | oldPath: "README.md", |
| 331 | newPath: "README.md", |
| 332 | ...overrides, |
| 333 | }); |
| 334 | |
| 335 | const git = ( |
| 336 | cwd: string, |
| 337 | args: ReadonlyArray<string>, |
| 338 | env?: NodeJS.ProcessEnv, |
| 339 | ): Effect.Effect<string, GitCommandError, GitVcsDriver.GitVcsDriver> => |
| 340 | Effect.gen(function* () { |
| 341 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 342 | const result = yield* driver.execute({ |
| 343 | operation: "GitVcsDriver.test.git", |
| 344 | cwd, |
| 345 | args, |
| 346 | ...(env ? { env } : {}), |
| 347 | timeoutMs: 10_000, |
| 348 | }); |
| 349 | return result.stdout.trim(); |
| 350 | }); |
| 351 | |
| 352 | const [, gitMajor, gitMinor] = |
| 353 | /(\d+)\.(\d+)/u.exec(NodeChildProcess.execFileSync("git", ["--version"], { encoding: "utf8" })) ?? |
| 354 | []; |
| 355 | const gitHasReftable = Number(gitMajor) > 2 || (Number(gitMajor) === 2 && Number(gitMinor) >= 45); |
| 356 | |
| 357 | const gitWithStdin = ( |
| 358 | cwd: string, |
| 359 | args: ReadonlyArray<string>, |
| 360 | stdin: string, |
| 361 | ): Effect.Effect<string, GitCommandError, GitVcsDriver.GitVcsDriver> => |
| 362 | Effect.flatMap(GitVcsDriver.GitVcsDriver, (driver) => |
| 363 | driver.execute({ operation: "GitVcsDriver.test.git", cwd, args, stdin, timeoutMs: 10_000 }), |
| 364 | ).pipe(Effect.map((result) => result.stdout.trim())); |
| 365 | |
| 366 | // Git blocks file submodule transports (CVE-2022-39253) despite repo config; local fixtures need env permission. |
| 367 | const withGitFileProtocol = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 368 | Effect.flatMap(HostProcess.Environment, (env) => |
| 369 | effect.pipe( |
| 370 | Effect.provideService(HostProcess.Environment, { ...env, GIT_ALLOW_PROTOCOL: "file" }), |
| 371 | ), |
| 372 | ); |
| 373 | |
| 374 | const initRepoWithCommit = ( |
| 375 | cwd: string, |
| 376 | ): Effect.Effect< |
| 377 | { readonly initialBranch: string }, |
| 378 | GitCommandError | PlatformError.PlatformError, |
| 379 | GitVcsDriver.GitVcsDriver | FileSystem.FileSystem | Path.Path |
| 380 | > => |
| 381 | Effect.gen(function* () { |
| 382 | const fileSystem = yield* FileSystem.FileSystem; |
| 383 | const pathService = yield* Path.Path; |
| 384 | // Git commits whatever already sits in cwd, so only an empty one can take the shared copy. |
| 385 | const empty = |
| 386 | !(yield* fileSystem.exists(cwd)) || (yield* fileSystem.readDirectory(cwd)).length === 0; |
| 387 | if (empty) { |
| 388 | if (!repoTemplate) { |
| 389 | const template = yield* fileSystem.makeTempDirectory({ |
| 390 | prefix: "git-vcs-driver-template-", |
| 391 | }); |
| 392 | yield* commitInitialRepo(template); |
| 393 | repoTemplate = template; |
| 394 | } |
| 395 | yield* fileSystem.copy(repoTemplate, cwd); |
| 396 | } else { |
| 397 | yield* commitInitialRepo(cwd); |
| 398 | } |
| 399 | const head = yield* fileSystem.readFileString(pathService.join(cwd, ".git", "HEAD")); |
| 400 | return { initialBranch: head.trim().replace(/^ref: refs\/heads\//, "") }; |
| 401 | }); |
| 402 | |
| 403 | const commitInitialRepo = (cwd: string, initArgs: ReadonlyArray<string> = []) => |
| 404 | Effect.gen(function* () { |
| 405 | const fileSystem = yield* FileSystem.FileSystem; |
| 406 | const pathService = yield* Path.Path; |
| 407 | yield* git(cwd, ["init", ...initArgs]); |
| 408 | // Newer Git detaches auto-maintenance after commit; its lock file would race the template copy. |
| 409 | yield* fileSystem.writeFileString( |
| 410 | pathService.join(cwd, ".git", "config"), |
| 411 | "[user]\n\temail = test@test.com\n\tname = Test\n[maintenance]\n\tauto = false\n", |
| 412 | { flag: "a" }, |
| 413 | ); |
| 414 | yield* writeTextFile(cwd, "README.md", "# test\n"); |
| 415 | yield* git(cwd, ["add", "."]); |
| 416 | yield* git(cwd, ["commit", "-m", "initial commit"]); |
| 417 | }); |
| 418 | |
| 419 | // Most tests start from the same one-commit repository; they copy it instead of spawning git. |
| 420 | let repoTemplate: string | undefined; |
| 421 | afterAll(() => { |
| 422 | if (repoTemplate) NodeFS.rmSync(repoTemplate, { recursive: true, force: true }); |
| 423 | }); |
| 424 | |
| 425 | it.effect.each(["root", "nested", "worktree"] as const)( |
| 426 | "skips clean filters while the %s index is locked and resumes after unlock", |
| 427 | (location) => |
| 428 | Effect.gen(function* () { |
| 429 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 430 | const fs = yield* FileSystem.FileSystem; |
| 431 | const path = yield* Path.Path; |
| 432 | const repository = yield* makeTmpDir(); |
| 433 | yield* initRepoWithCommit(repository); |
| 434 | const cwd = location === "worktree" ? yield* makeTmpDir() : repository; |
| 435 | if (location === "worktree") { |
| 436 | yield* git(repository, ["worktree", "add", "--detach", cwd]); |
| 437 | } |
| 438 | yield* git(cwd, ["config", "filter.probe.clean", "echo clean >> .filter-runs; cat"]); |
| 439 | yield* writeTextFile(cwd, ".gitattributes", "asset.bin filter=probe\n"); |
| 440 | yield* writeTextFile(cwd, ".gitignore", ".filter-runs\n"); |
| 441 | yield* writeTextFile(cwd, "asset.bin", "original\n"); |
| 442 | yield* git(cwd, ["add", "."]); |
| 443 | yield* git(cwd, ["commit", "-m", "filtered asset"]); |
| 444 | NodeFS.utimesSync(path.join(cwd, "asset.bin"), 1, 1); |
| 445 | const runsPath = path.join(cwd, ".filter-runs"); |
| 446 | yield* fs.remove(runsPath, { force: true }); |
| 447 | const indexPath = yield* git(cwd, ["rev-parse", "--git-path", "index"]); |
| 448 | const lockPath = `${path.resolve(cwd, indexPath)}.lock`; |
| 449 | yield* fs.writeFileString(lockPath, ""); |
| 450 | const statusCwd = location === "nested" ? path.join(cwd, "nested") : cwd; |
| 451 | yield* fs.makeDirectory(statusCwd, { recursive: true }); |
| 452 | |
| 453 | for (let poll = 0; poll < 3; poll++) { |
| 454 | const result = yield* driver.statusDetailsLocal(statusCwd).pipe(Effect.result); |
| 455 | assert.isTrue(Result.isFailure(result)); |
| 456 | if (Result.isFailure(result)) assert.include(result.failure.detail, "index is locked"); |
| 457 | } |
| 458 | assert.isFalse(yield* fs.exists(runsPath)); |
| 459 | assert.isTrue(yield* fs.exists(lockPath)); |
| 460 | |
| 461 | yield* fs.remove(lockPath); |
| 462 | const status = yield* driver.statusDetailsLocal(statusCwd); |
| 463 | assert.isFalse(status.hasWorkingTreeChanges); |
| 464 | assert.include(yield* fs.readFileString(runsPath), "clean"); |
| 465 | }).pipe(Effect.provide(layerTest)), |
| 466 | ); |
| 467 | |
| 468 | it.effect.each(["origin", "github"] as const)( |
| 469 | "recognizes %s as the primary remote after a driver mutation", |
| 470 | (remoteName) => |
| 471 | Effect.gen(function* () { |
| 472 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 473 | const cwd = yield* makeTmpDir(); |
| 474 | const remote = yield* makeTmpDir("git-vcs-driver-remote-"); |
| 475 | yield* initRepoWithCommit(cwd); |
| 476 | yield* git(remote, ["init", "--bare"]); |
| 477 | |
| 478 | assert.equal((yield* driver.statusDetailsLocal(cwd)).hasOriginRemote, false); |
| 479 | assert.equal((yield* driver.listRefs({ cwd })).hasPrimaryRemote, false); |
| 480 | |
| 481 | yield* driver.ensureRemote({ cwd, preferredName: remoteName, url: remote }); |
| 482 | |
| 483 | assert.equal((yield* driver.statusDetailsLocal(cwd)).hasOriginRemote, true); |
| 484 | assert.equal((yield* driver.listRefs({ cwd })).hasPrimaryRemote, true); |
| 485 | }).pipe(Effect.provide(layerTest)), |
| 486 | ); |
| 487 | |
| 488 | it.effect( |
| 489 | "refreshes remote status after external init while refs still cache a non-repository", |
| 490 | () => |
| 491 | Effect.gen(function* () { |
| 492 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 493 | const fs = yield* FileSystem.FileSystem; |
| 494 | const cwd = yield* fs.realPath(yield* makeTmpDir()); |
| 495 | assert.isFalse((yield* driver.listRefs({ cwd })).isRepo); |
| 496 | yield* git(cwd, ["init"]); |
| 497 | |
| 498 | assert.isFalse((yield* driver.statusDetailsLocal(cwd)).hasOriginRemote); |
| 499 | yield* driver.ensureRemote({ cwd, preferredName: "origin", url: cwd }); |
| 500 | assert.isTrue((yield* driver.statusDetailsLocal(cwd)).hasOriginRemote); |
| 501 | }).pipe(Effect.provide(layerTest)), |
| 502 | ); |
| 503 | |
| 504 | it.effect.each([ |
| 505 | { hookExitCode: 0, commonDirFailure: "none" }, |
| 506 | { hookExitCode: 1, commonDirFailure: "none" }, |
| 507 | { hookExitCode: 0, commonDirFailure: "error" }, |
| 508 | { hookExitCode: 1, commonDirFailure: "error" }, |
| 509 | { hookExitCode: 0, commonDirFailure: "non-repository" }, |
| 510 | { hookExitCode: 1, commonDirFailure: "non-repository" }, |
| 511 | ])( |
| 512 | "invalidates sibling worktree refs and status after checkout hook exit $hookExitCode with common-dir failure $commonDirFailure", |
| 513 | ({ hookExitCode, commonDirFailure }) => |
| 514 | Effect.scoped( |
| 515 | Effect.gen(function* () { |
| 516 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 517 | const spawnedArgs: Array<ReadonlyArray<string>> = []; |
| 518 | let invalidationFailure = "none"; |
| 519 | const spawner = ChildProcessSpawner.make((command) => |
| 520 | Effect.gen(function* () { |
| 521 | if (!ChildProcess.isStandardCommand(command)) { |
| 522 | return yield* Effect.die("expected a standard Git command"); |
| 523 | } |
| 524 | spawnedArgs.push(command.args.map(String)); |
| 525 | if (invalidationFailure !== "none" && command.args.includes("--git-common-dir")) { |
| 526 | if (invalidationFailure === "non-repository") return makeNonRepositoryHandle(); |
| 527 | return ChildProcessSpawner.makeHandle({ |
| 528 | ...makeNonRepositoryHandle(), |
| 529 | stderr: Stream.encodeText(Stream.make("fatal: could not read repository metadata")), |
| 530 | }); |
| 531 | } |
| 532 | return yield* delegate.spawn(command); |
| 533 | }), |
| 534 | ); |
| 535 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 536 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 537 | ); |
| 538 | const cwd = yield* makeTmpDir(); |
| 539 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 540 | const path = yield* Path.Path; |
| 541 | const fs = yield* FileSystem.FileSystem; |
| 542 | const siblingPath = path.join(yield* makeTmpDir("git-worktrees-"), "sibling"); |
| 543 | yield* git(cwd, ["worktree", "add", "-b", "cache-sibling", siblingPath, "HEAD"]); |
| 544 | |
| 545 | const before = yield* driver.listRefs({ cwd: siblingPath, refresh: true }); |
| 546 | assert.isTrue(before.refs.find((ref) => ref.name === "cache-sibling")?.current); |
| 547 | const statusBefore = yield* driver.statusDetailsLocal(siblingPath); |
| 548 | assert.isFalse(statusBefore.hasOriginRemote); |
| 549 | assert.isFalse(statusBefore.isDefaultBranch); |
| 550 | yield* driver.listRefs({ cwd, refresh: true }); |
| 551 | yield* git(cwd, ["checkout", "-b", "creator-current"]); |
| 552 | yield* writeTextFile( |
| 553 | cwd, |
| 554 | ".git/hooks/post-checkout", |
| 555 | "#!/bin/sh\n" + |
| 556 | "git remote add origin https://example.invalid/repo.git || exit 2\n" + |
| 557 | "git update-ref refs/remotes/origin/cache-sibling HEAD || exit 2\n" + |
| 558 | "git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/cache-sibling || exit 2\n" + |
| 559 | `exit ${hookExitCode}\n`, |
| 560 | ); |
| 561 | yield* fs.chmod(path.join(cwd, ".git/hooks/post-checkout"), 0o755); |
| 562 | const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "created"); |
| 563 | spawnedArgs.length = 0; |
| 564 | invalidationFailure = commonDirFailure; |
| 565 | |
| 566 | const created = yield* driver |
| 567 | .createWorktree({ |
| 568 | cwd, |
| 569 | path: worktreePath, |
| 570 | refName: initialBranch, |
| 571 | newRefName: "feature/cache-created", |
| 572 | }) |
| 573 | .pipe(Effect.result); |
| 574 | |
| 575 | assert.equal(Result.isSuccess(created), hookExitCode === 0); |
| 576 | if (Result.isFailure(created)) { |
| 577 | assert.equal(created.failure.operation, "GitVcsDriver.createWorktree"); |
| 578 | assert.equal(created.failure.detail, "git worktree add failed"); |
| 579 | assert.equal(created.failure.exitCode, hookExitCode); |
| 580 | } |
| 581 | const metadataQueries = spawnedArgs.filter((args) => args.includes("--git-common-dir")); |
| 582 | assert.deepStrictEqual( |
| 583 | metadataQueries, |
| 584 | Array.from({ length: 2 }, () => ["rev-parse", "--git-common-dir"]), |
| 585 | ); |
| 586 | assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref"))); |
| 587 | invalidationFailure = "none"; |
| 588 | |
| 589 | spawnedArgs.length = 0; |
| 590 | const creatorStatus = yield* driver.statusDetailsLocal(cwd); |
| 591 | assert.equal(creatorStatus.branch, "creator-current"); |
| 592 | assert.isTrue(spawnedArgs.some((args) => args.includes("--git-common-dir"))); |
| 593 | const siblingRefs = yield* driver.listRefs({ cwd: siblingPath }); |
| 594 | const createdRef = siblingRefs.refs.find((ref) => ref.name === "feature/cache-created"); |
| 595 | assert.isDefined(createdRef?.worktreePath); |
| 596 | assert.equal( |
| 597 | NodeFS.realpathSync.native(createdRef!.worktreePath!), |
| 598 | NodeFS.realpathSync.native(worktreePath), |
| 599 | ); |
| 600 | assert.isTrue(siblingRefs.hasPrimaryRemote); |
| 601 | assert.isTrue(siblingRefs.refs.find((ref) => ref.name === "cache-sibling")?.current); |
| 602 | const statusAfter = yield* driver.statusDetailsLocal(siblingPath); |
| 603 | assert.isTrue(statusAfter.hasOriginRemote); |
| 604 | assert.isTrue(statusAfter.isDefaultBranch); |
| 605 | const creatorRefs = yield* driver.listRefs({ cwd }); |
| 606 | assert.isTrue(creatorRefs.refs.find((ref) => ref.name === "creator-current")?.current); |
| 607 | assert.isFalse(creatorRefs.refs.find((ref) => ref.name === initialBranch)?.current); |
| 608 | }), |
| 609 | ).pipe(Effect.provide(layerTest)), |
| 610 | ); |
| 611 | |
| 612 | it.effect.each(["branch", "detached", "nested", "aliased-root", "aliased-nested"] as const)( |
| 613 | "discovers only the common directory during worktree creation from %s", |
| 614 | (location) => |
| 615 | Effect.scoped( |
| 616 | Effect.gen(function* () { |
| 617 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 618 | const spawnedArgs: Array<ReadonlyArray<string>> = []; |
| 619 | const spawner = ChildProcessSpawner.make((command) => { |
| 620 | if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); |
| 621 | return delegate.spawn(command); |
| 622 | }); |
| 623 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 624 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 625 | ); |
| 626 | const cwd = yield* makeTmpDir(); |
| 627 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 628 | const path = yield* Path.Path; |
| 629 | if (location === "detached") yield* git(cwd, ["checkout", "--detach"]); |
| 630 | const isNested = location === "nested" || location === "aliased-nested"; |
| 631 | const physicalCwd = isNested ? path.join(cwd, "nested") : cwd; |
| 632 | const fs = yield* FileSystem.FileSystem; |
| 633 | yield* fs.makeDirectory(physicalCwd, { recursive: true }); |
| 634 | const isAliased = location === "aliased-root" || location === "aliased-nested"; |
| 635 | const creationCwd = isAliased |
| 636 | ? path.join(yield* makeTmpDir("git-alias-"), "link") |
| 637 | : physicalCwd; |
| 638 | if (isAliased) NodeFS.symlinkSync(physicalCwd, creationCwd, "junction"); |
| 639 | const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "cold"); |
| 640 | |
| 641 | yield* driver.createWorktree({ |
| 642 | cwd: creationCwd, |
| 643 | path: worktreePath, |
| 644 | refName: initialBranch, |
| 645 | newRefName: "feature/cold", |
| 646 | }); |
| 647 | |
| 648 | assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 2); |
| 649 | assert.isFalse(spawnedArgs.some((args) => args.includes("--show-toplevel"))); |
| 650 | assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref"))); |
| 651 | spawnedArgs.length = 0; |
| 652 | const originalStatus = yield* driver.statusDetailsLocal(creationCwd); |
| 653 | assert.equal(originalStatus.branch, location === "detached" ? null : initialBranch); |
| 654 | const originalRefs = yield* driver.listRefs({ cwd: creationCwd }); |
| 655 | assert.equal(originalRefs.isAtRepositoryRoot, !isNested); |
| 656 | assert.deepStrictEqual( |
| 657 | originalRefs.refs.filter((ref) => ref.current).map((ref) => ref.name), |
| 658 | location === "detached" ? [] : [initialBranch], |
| 659 | ); |
| 660 | assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1); |
| 661 | const refs = yield* driver.listRefs({ cwd: worktreePath }); |
| 662 | assert.isTrue(refs.refs.find((ref) => ref.name === "feature/cold")?.current); |
| 663 | assert.equal( |
| 664 | yield* git(worktreePath, ["rev-parse", "HEAD"]), |
| 665 | yield* git(cwd, ["rev-parse", "HEAD"]), |
| 666 | ); |
| 667 | }), |
| 668 | ).pipe(Effect.provide(layerTest)), |
| 669 | ); |
| 670 | |
| 671 | it.effect.each(["bare", "unborn"] as const)( |
| 672 | "invalidates a %s repository after worktree creation", |
| 673 | (state) => |
| 674 | Effect.scoped( |
| 675 | Effect.gen(function* () { |
| 676 | const source = yield* makeTmpDir(); |
| 677 | const cwd = yield* makeTmpDir("git-discovery-fallback-"); |
| 678 | if (state === "bare") { |
| 679 | yield* initRepoWithCommit(source); |
| 680 | yield* git(source, ["clone", "--bare", source, cwd]); |
| 681 | } else { |
| 682 | yield* git(cwd, ["init"]); |
| 683 | } |
| 684 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 685 | const spawnedArgs: Array<ReadonlyArray<string>> = []; |
| 686 | const spawner = ChildProcessSpawner.make((command) => { |
| 687 | if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); |
| 688 | return delegate.spawn( |
| 689 | state === "bare" ? ChildProcess.setEnv(command, { GIT_DIR: cwd }) : command, |
| 690 | ); |
| 691 | }); |
| 692 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 693 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 694 | ); |
| 695 | const path = yield* Path.Path; |
| 696 | const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "fallback"); |
| 697 | const result = yield* driver |
| 698 | .createWorktree({ |
| 699 | cwd, |
| 700 | path: worktreePath, |
| 701 | refName: "HEAD", |
| 702 | newRefName: "feature/fallback", |
| 703 | }) |
| 704 | .pipe(Effect.result); |
| 705 | assert.equal(Result.isSuccess(result), state === "bare"); |
| 706 | if (Result.isFailure(result)) { |
| 707 | assert.equal(result.failure.operation, "GitVcsDriver.createWorktree.createBranch"); |
| 708 | assert.equal(result.failure.detail, "git branch failed"); |
| 709 | } |
| 710 | assert.equal( |
| 711 | spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, |
| 712 | state === "bare" ? 2 : 1, |
| 713 | ); |
| 714 | assert.isFalse(spawnedArgs.some((args) => args[0] === "symbolic-ref")); |
| 715 | spawnedArgs.length = 0; |
| 716 | const refs = yield* driver.listRefs({ cwd }); |
| 717 | assert.isTrue(refs.isRepo); |
| 718 | if (state === "bare") { |
| 719 | assert.isTrue(refs.refs.some((ref) => ref.name === "feature/fallback")); |
| 720 | } else { |
| 721 | assert.isEmpty(refs.refs); |
| 722 | } |
| 723 | assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1); |
| 724 | }), |
| 725 | ).pipe(Effect.provide(layerTest)), |
| 726 | ); |
| 727 | |
| 728 | it.effect("reads the project's own repository when the server inherited GIT_DIR", () => |
| 729 | Effect.scoped( |
| 730 | Effect.gen(function* () { |
| 731 | const path = yield* Path.Path; |
| 732 | const cwd = yield* makeTmpDir(); |
| 733 | const other = yield* makeTmpDir(); |
| 734 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 735 | yield* initRepoWithCommit(other); |
| 736 | yield* git(other, ["switch", "-c", "other-repository"]); |
| 737 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 738 | yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); |
| 739 | vi.stubEnv("GIT_DIR", path.join(other, ".git")); |
| 740 | assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, initialBranch); |
| 741 | const refs = yield* driver.listRefs({ cwd }); |
| 742 | assert.isFalse(refs.refs.some((ref) => ref.name === "other-repository")); |
| 743 | }), |
| 744 | ).pipe(Effect.provide(layerTest)), |
| 745 | ); |
| 746 | |
| 747 | it.effect("reads a branch whose name starts with a parenthesis as attached", () => |
| 748 | Effect.scoped( |
| 749 | Effect.gen(function* () { |
| 750 | const cwd = yield* makeTmpDir(); |
| 751 | yield* initRepoWithCommit(cwd); |
| 752 | yield* git(cwd, ["switch", "-c", "(topic"]); |
| 753 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 754 | const status = yield* driver.statusDetailsLocal(cwd, { includeDivergence: false }); |
| 755 | assert.equal(status.branch, "(topic"); |
| 756 | }), |
| 757 | ).pipe(Effect.provide(layerTest)), |
| 758 | ); |
| 759 | |
| 760 | it.effect.each(["an existing", "a new"] as const)( |
| 761 | "follows a checkout of %s branch made outside the driver after refs were cached", |
| 762 | (branch) => |
| 763 | Effect.scoped( |
| 764 | Effect.gen(function* () { |
| 765 | const cwd = yield* makeTmpDir(); |
| 766 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 767 | if (branch === "an existing") yield* git(cwd, ["branch", "feature/outside"]); |
| 768 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 769 | yield* driver.listRefs({ cwd }); |
| 770 | |
| 771 | yield* git( |
| 772 | cwd, |
| 773 | branch === "an existing" |
| 774 | ? ["switch", "feature/outside"] |
| 775 | : ["switch", "-c", "feature/outside"], |
| 776 | ); |
| 777 | |
| 778 | const refs = (yield* driver.listRefs({ cwd })).refs; |
| 779 | const previous = refs.find((ref) => ref.name === initialBranch); |
| 780 | assert.isTrue(refs.find((ref) => ref.name === "feature/outside")?.current); |
| 781 | assert.isFalse(previous?.current); |
| 782 | assert.isNull(previous?.worktreePath ?? null); |
| 783 | }), |
| 784 | ).pipe(Effect.provide(layerTest)), |
| 785 | ); |
| 786 | |
| 787 | it.effect.each(["on a branch", "detached", "unborn"] as const)( |
| 788 | "reuses the cached repository layout for review requests when %s", |
| 789 | (state) => |
| 790 | Effect.scoped( |
| 791 | Effect.gen(function* () { |
| 792 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 793 | const spawnedArgs: Array<ReadonlyArray<string>> = []; |
| 794 | const spawner = ChildProcessSpawner.make((command) => { |
| 795 | if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); |
| 796 | return delegate.spawn(command); |
| 797 | }); |
| 798 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 799 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 800 | ); |
| 801 | const discoveries = () => { |
| 802 | const spawned = (matches: (args: ReadonlyArray<string>) => boolean) => |
| 803 | spawnedArgs.filter(matches).length; |
| 804 | const counts = { |
| 805 | commonDir: spawned((args) => args.includes("--git-common-dir")), |
| 806 | worktreeRoot: spawned((args) => args.includes("--show-toplevel")), |
| 807 | branch: spawned((args) => args.includes("symbolic-ref") && args.includes("HEAD")), |
| 808 | }; |
| 809 | spawnedArgs.length = 0; |
| 810 | return counts; |
| 811 | }; |
| 812 | const warm = { commonDir: 0, worktreeRoot: 0, branch: 0 }; |
| 813 | const branchRead = { ...warm, branch: 1 }; |
| 814 | const cwd = yield* makeTmpDir(); |
| 815 | if (state === "unborn") { |
| 816 | yield* git(cwd, ["init", "-b", "main"]); |
| 817 | } else { |
| 818 | yield* initRepoWithCommit(cwd); |
| 819 | yield* writeTextFile(cwd, "committed.txt", "committed\n"); |
| 820 | yield* git(cwd, ["add", "."]); |
| 821 | yield* git(cwd, ["commit", "-m", "add file"]); |
| 822 | if (state === "detached") yield* git(cwd, ["checkout", "--detach"]); |
| 823 | } |
| 824 | yield* writeTextFile(cwd, "new.txt", "new\n"); |
| 825 | spawnedArgs.length = 0; |
| 826 | |
| 827 | const workingTreeFile = { |
| 828 | cwd, |
| 829 | file: { path: "new.txt", previousPath: null, sourceKind: "working-tree" }, |
| 830 | } as const; |
| 831 | const workingTree = yield* driver.getReviewDiffPreview(workingTreeFile); |
| 832 | assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 1 }); |
| 833 | assert.deepStrictEqual( |
| 834 | workingTree.sources |
| 835 | .find((source) => source.kind === "working-tree")! |
| 836 | .files!.map((file) => file.path), |
| 837 | ["new.txt"], |
| 838 | ); |
| 839 | yield* driver.getReviewDiffPreview(workingTreeFile); |
| 840 | assert.deepStrictEqual(discoveries(), warm); |
| 841 | |
| 842 | if (state !== "unborn") { |
| 843 | const commitSha = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 844 | const commit = yield* driver.getReviewDiffPreview({ |
| 845 | cwd, |
| 846 | commitSha, |
| 847 | file: { path: "committed.txt", previousPath: null, sourceKind: "commit" }, |
| 848 | }); |
| 849 | assert.deepStrictEqual(discoveries(), warm); |
| 850 | assert.include(commit.sources[0]!.diff, "+committed"); |
| 851 | } |
| 852 | |
| 853 | const headRef = (preview: Effect.Success<ReturnType<typeof driver.getReviewDiffPreview>>) => |
| 854 | preview.sources.find((entry) => entry.kind === "branch-range")!.headRef; |
| 855 | const general = yield* driver.getReviewDiffPreview({ cwd }); |
| 856 | assert.deepStrictEqual(discoveries(), branchRead); |
| 857 | assert.equal( |
| 858 | headRef(general), |
| 859 | state === "detached" ? "HEAD" : yield* git(cwd, ["branch", "--show-current"]), |
| 860 | ); |
| 861 | |
| 862 | // A checkout made outside the driver is visible to the next request. |
| 863 | if (state !== "detached") yield* git(cwd, ["checkout", "-b", "outside-checkout"]); |
| 864 | const afterCheckout = yield* driver.getReviewDiffPreview({ cwd }); |
| 865 | assert.deepStrictEqual(discoveries(), branchRead); |
| 866 | if (state !== "detached") assert.equal(headRef(afterCheckout), "outside-checkout"); |
| 867 | |
| 868 | yield* driver.getReviewBranchCommits({ cwd }); |
| 869 | assert.deepStrictEqual(discoveries(), branchRead); |
| 870 | |
| 871 | // A cached layout must not outlive a removed cwd. |
| 872 | yield* (yield* FileSystem.FileSystem).remove(cwd, { recursive: true }); |
| 873 | assert.isEmpty((yield* driver.getReviewDiffPreview(workingTreeFile)).sources); |
| 874 | assert.isEmpty((yield* driver.getReviewDiffPreview({ cwd })).sources); |
| 875 | }), |
| 876 | ).pipe(Effect.provide(layerTest)), |
| 877 | ); |
| 878 | |
| 879 | it.effect.each([ |
| 880 | { kind: "working-tree", request: { sourceKind: "working-tree" } }, |
| 881 | { kind: "commit", request: { sourceKind: "commit", commitSha: "HEAD" } }, |
| 882 | ] as const)("keeps $kind review requests safe without a worktree root", ({ request }) => |
| 883 | Effect.scoped( |
| 884 | Effect.gen(function* () { |
| 885 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 886 | const bareRoot = yield* makeTmpDir("git-review-bare-"); |
| 887 | const spawner = ChildProcessSpawner.make((command) => |
| 888 | delegate.spawn( |
| 889 | ChildProcess.isStandardCommand(command) && command.options.cwd === bareRoot |
| 890 | ? ChildProcess.setEnv(command, { GIT_DIR: bareRoot }) |
| 891 | : command, |
| 892 | ), |
| 893 | ); |
| 894 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 895 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 896 | ); |
| 897 | const path = yield* Path.Path; |
| 898 | const file = { path: "README.md", previousPath: null, sourceKind: request.sourceKind }; |
| 899 | const input = (cwd: string) => ({ |
| 900 | cwd, |
| 901 | file, |
| 902 | ...("commitSha" in request ? { commitSha: request.commitSha } : {}), |
| 903 | }); |
| 904 | const source = yield* makeTmpDir(); |
| 905 | yield* initRepoWithCommit(source); |
| 906 | yield* git(source, ["clone", "--bare", source, bareRoot]); |
| 907 | const nonRepository = yield* makeTmpDir(); |
| 908 | for (const cwd of [bareRoot, nonRepository, path.join(nonRepository, "missing")]) { |
| 909 | assert.isEmpty((yield* driver.getReviewDiffPreview(input(cwd))).sources); |
| 910 | } |
| 911 | |
| 912 | const brokenConfig = yield* makeTmpDir(); |
| 913 | yield* initRepoWithCommit(brokenConfig); |
| 914 | yield* writeTextFile(brokenConfig, ".git/config", "[broken"); |
| 915 | const error = yield* driver.getReviewDiffPreview(input(brokenConfig)).pipe(Effect.flip); |
| 916 | assert.equal(error.operation, "GitVcsDriver.resolveRepositoryPaths.commonDir"); |
| 917 | }), |
| 918 | ).pipe(Effect.provide(layerTest)), |
| 919 | ); |
| 920 | |
| 921 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 922 | "preserves embedded newlines in repository paths after worktree creation", |
| 923 | () => |
| 924 | Effect.scoped( |
| 925 | Effect.gen(function* () { |
| 926 | const path = yield* Path.Path; |
| 927 | const fs = yield* FileSystem.FileSystem; |
| 928 | const cwd = path.join(yield* makeTmpDir(), "repo\nwith-newline"); |
| 929 | yield* fs.makeDirectory(cwd); |
| 930 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 931 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 932 | const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "newline"); |
| 933 | yield* driver.createWorktree({ |
| 934 | cwd, |
| 935 | path: worktreePath, |
| 936 | refName: initialBranch, |
| 937 | newRefName: "feature/newline", |
| 938 | }); |
| 939 | const status = yield* driver.statusDetailsLocal(cwd); |
| 940 | assert.equal(status.branch, initialBranch); |
| 941 | const refs = yield* driver.listRefs({ cwd }); |
| 942 | assert.isTrue(refs.refs.find((ref) => ref.name === initialBranch)?.current); |
| 943 | assert.isTrue(refs.refs.some((ref) => ref.name === "feature/newline")); |
| 944 | }), |
| 945 | ).pipe(Effect.provide(layerTest)), |
| 946 | ); |
| 947 | |
| 948 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 949 | "preserves a trailing carriage return in the repository root after creation through an alias", |
| 950 | () => |
| 951 | Effect.scoped( |
| 952 | Effect.gen(function* () { |
| 953 | const path = yield* Path.Path; |
| 954 | const fs = yield* FileSystem.FileSystem; |
| 955 | const sandbox = yield* makeTmpDir(); |
| 956 | const repository = path.join(sandbox, "repo\r"); |
| 957 | const cwd = path.join(sandbox, "alias"); |
| 958 | yield* fs.makeDirectory(repository); |
| 959 | const { initialBranch } = yield* initRepoWithCommit(repository); |
| 960 | NodeFS.symlinkSync(repository, cwd, "junction"); |
| 961 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 962 | yield* driver.createWorktree({ |
| 963 | cwd, |
| 964 | path: path.join(yield* makeTmpDir("git-worktrees-"), "created"), |
| 965 | refName: initialBranch, |
| 966 | newRefName: "feature/carriage-return", |
| 967 | }); |
| 968 | const status = yield* driver.statusDetailsLocal(cwd); |
| 969 | assert.equal(status.workingTree.rootPath, NodeFS.realpathSync.native(repository)); |
| 970 | assert.equal(status.branch, initialBranch); |
| 971 | const refs = yield* driver.listRefs({ cwd }); |
| 972 | assert.isTrue(refs.isAtRepositoryRoot); |
| 973 | assert.isTrue(refs.refs.some((ref) => ref.name === "feature/carriage-return")); |
| 974 | }), |
| 975 | ).pipe(Effect.provide(layerTest)), |
| 976 | ); |
| 977 | |
| 978 | it.effect( |
| 979 | "reads fresh metadata when another mutation completes during common-directory discovery", |
| 980 | () => |
| 981 | Effect.scoped( |
| 982 | Effect.gen(function* () { |
| 983 | const cwd = yield* makeTmpDir(); |
| 984 | yield* initRepoWithCommit(cwd); |
| 985 | const commit = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 986 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 987 | const discoveryComplete = yield* Deferred.make<void>(); |
| 988 | const releaseDiscovery = yield* Deferred.make<void>(); |
| 989 | let holdDiscovery = false; |
| 990 | const spawner = ChildProcessSpawner.make((command) => |
| 991 | Effect.gen(function* () { |
| 992 | const handle = yield* delegate.spawn(command); |
| 993 | if ( |
| 994 | !holdDiscovery || |
| 995 | !ChildProcess.isStandardCommand(command) || |
| 996 | !command.args.includes("--git-common-dir") |
| 997 | ) |
| 998 | return handle; |
| 999 | holdDiscovery = false; |
| 1000 | const output = yield* Stream.runCollect(handle.stdout); |
| 1001 | yield* handle.exitCode; |
| 1002 | yield* Deferred.succeed(discoveryComplete, undefined); |
| 1003 | yield* Deferred.await(releaseDiscovery); |
| 1004 | return ChildProcessSpawner.makeHandle({ |
| 1005 | ...handle, |
| 1006 | stdout: Stream.fromIterable(output), |
| 1007 | }); |
| 1008 | }), |
| 1009 | ); |
| 1010 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1011 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1012 | ); |
| 1013 | yield* driver.listRefs({ cwd, refresh: true }); |
| 1014 | const path = yield* Path.Path; |
| 1015 | const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "concurrent"); |
| 1016 | holdDiscovery = true; |
| 1017 | const creation = yield* driver |
| 1018 | .createWorktree({ |
| 1019 | cwd, |
| 1020 | path: worktreePath, |
| 1021 | refName: "HEAD", |
| 1022 | newRefName: "feature/concurrent", |
| 1023 | }) |
| 1024 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1025 | yield* Effect.gen(function* () { |
| 1026 | yield* Deferred.await(discoveryComplete); |
| 1027 | yield* driver.switchRef({ cwd, refName: commit }); |
| 1028 | }).pipe(Effect.ensuring(Deferred.succeed(releaseDiscovery, undefined))); |
| 1029 | const created = yield* Fiber.join(creation); |
| 1030 | assert.equal(created.worktree.path, worktreePath); |
| 1031 | const refs = yield* driver.listRefs({ cwd }); |
| 1032 | assert.isEmpty(refs.refs.filter((ref) => ref.current)); |
| 1033 | assert.isTrue(refs.refs.some((ref) => ref.name === "feature/concurrent")); |
| 1034 | assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, null); |
| 1035 | }), |
| 1036 | ).pipe(Effect.provide(layerTest)), |
| 1037 | ); |
| 1038 | |
| 1039 | it.effect("invalidates cached metadata after interrupted worktree creation", () => |
| 1040 | Effect.scoped( |
| 1041 | Effect.gen(function* () { |
| 1042 | const cwd = yield* makeTmpDir(); |
| 1043 | yield* initRepoWithCommit(cwd); |
| 1044 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1045 | const discoveryComplete = yield* Deferred.make<void>(); |
| 1046 | const releaseDiscovery = yield* Deferred.make<void>(); |
| 1047 | let holdDiscovery = false; |
| 1048 | const spawner = ChildProcessSpawner.make((command) => |
| 1049 | Effect.gen(function* () { |
| 1050 | const handle = yield* delegate.spawn(command); |
| 1051 | if ( |
| 1052 | !holdDiscovery || |
| 1053 | !ChildProcess.isStandardCommand(command) || |
| 1054 | !command.args.includes("--git-common-dir") |
| 1055 | ) |
| 1056 | return handle; |
| 1057 | holdDiscovery = false; |
| 1058 | const output = yield* Stream.runCollect(handle.stdout); |
| 1059 | yield* handle.exitCode; |
| 1060 | yield* Deferred.succeed(discoveryComplete, undefined); |
| 1061 | yield* Deferred.await(releaseDiscovery); |
| 1062 | return ChildProcessSpawner.makeHandle({ ...handle, stdout: Stream.fromIterable(output) }); |
| 1063 | }), |
| 1064 | ); |
| 1065 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1066 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1067 | ); |
| 1068 | yield* driver.listRefs({ cwd, refresh: true }); |
| 1069 | yield* driver.statusDetailsLocal(cwd); |
| 1070 | yield* git(cwd, ["checkout", "-b", "creator-current"]); |
| 1071 | const path = yield* Path.Path; |
| 1072 | const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "interrupted"); |
| 1073 | holdDiscovery = true; |
| 1074 | const creation = yield* driver |
| 1075 | .createWorktree({ |
| 1076 | cwd, |
| 1077 | path: worktreePath, |
| 1078 | refName: "HEAD", |
| 1079 | newRefName: "feature/interrupted", |
| 1080 | }) |
| 1081 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1082 | const cancellation = yield* Effect.gen(function* () { |
| 1083 | yield* Deferred.await(discoveryComplete); |
| 1084 | return yield* Fiber.interrupt(creation).pipe(Effect.forkChild({ startImmediately: true })); |
| 1085 | }).pipe(Effect.ensuring(Deferred.succeed(releaseDiscovery, undefined))); |
| 1086 | yield* Fiber.join(cancellation); |
| 1087 | const exit = yield* Fiber.await(creation); |
| 1088 | assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)); |
| 1089 | const refs = yield* driver.listRefs({ cwd }); |
| 1090 | assert.isTrue(refs.refs.find((ref) => ref.name === "creator-current")?.current); |
| 1091 | const interruptedRef = refs.refs.find((ref) => ref.name === "feature/interrupted"); |
| 1092 | assert.isDefined(interruptedRef?.worktreePath); |
| 1093 | assert.equal( |
| 1094 | NodeFS.realpathSync.native(interruptedRef!.worktreePath!), |
| 1095 | NodeFS.realpathSync.native(worktreePath), |
| 1096 | ); |
| 1097 | assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, "creator-current"); |
| 1098 | const nextPath = path.join(yield* makeTmpDir("git-worktrees-"), "after-interruption"); |
| 1099 | yield* driver.createWorktree({ |
| 1100 | cwd, |
| 1101 | path: nextPath, |
| 1102 | refName: "HEAD", |
| 1103 | newRefName: "feature/after", |
| 1104 | }); |
| 1105 | assert.isTrue( |
| 1106 | (yield* driver.listRefs({ cwd })).refs.some((ref) => ref.name === "feature/after"), |
| 1107 | ); |
| 1108 | }), |
| 1109 | ).pipe(Effect.provide(layerTest)), |
| 1110 | ); |
| 1111 | |
| 1112 | describe("pullCurrentBranch", () => { |
| 1113 | // A fast-forward that prints over 1 MB takes thousands of files, so the real pull's output is |
| 1114 | // padded past the cap instead. |
| 1115 | const withPaddedPull = ( |
| 1116 | stream: "stdout" | "stderr", |
| 1117 | onPull?: (args: ReadonlyArray<string>) => void, |
| 1118 | ) => |
| 1119 | Effect.gen(function* () { |
| 1120 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1121 | const padding = new Uint8Array(1_000_001).fill(0x20); |
| 1122 | const paddingSpawner = ChildProcessSpawner.make((command) => |
| 1123 | Effect.gen(function* () { |
| 1124 | const handle = yield* delegate.spawn(command); |
| 1125 | const isPull = |
| 1126 | ChildProcess.isStandardCommand(command) && |
| 1127 | command.args.includes("pull") && |
| 1128 | command.args.includes("--ff-only"); |
| 1129 | if (isPull) onPull?.(command.args.map(String)); |
| 1130 | return isPull |
| 1131 | ? ChildProcessSpawner.makeHandle({ |
| 1132 | ...handle, |
| 1133 | [stream]: Stream.concat(handle[stream], Stream.make(padding)), |
| 1134 | }) |
| 1135 | : handle; |
| 1136 | }), |
| 1137 | ); |
| 1138 | return yield* makeGitVcsDriverCore().pipe( |
| 1139 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, paddingSpawner), |
| 1140 | ); |
| 1141 | }); |
| 1142 | |
| 1143 | const cloneBehindRemote = Effect.gen(function* () { |
| 1144 | const cwd = yield* makeTmpDir(); |
| 1145 | const remote = yield* makeTmpDir("git-vcs-driver-remote-"); |
| 1146 | const updater = yield* makeTmpDir("git-vcs-driver-updater-"); |
| 1147 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 1148 | yield* git(remote, ["init", "--bare"]); |
| 1149 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 1150 | yield* git(cwd, ["push", "-u", "origin", initialBranch]); |
| 1151 | yield* git(updater, ["clone", remote, "."]); |
| 1152 | yield* git(updater, ["config", "user.email", "test@test.com"]); |
| 1153 | yield* git(updater, ["config", "user.name", "Test"]); |
| 1154 | yield* writeTextFile(updater, "remote.txt", "remote\n"); |
| 1155 | yield* git(updater, ["add", "remote.txt"]); |
| 1156 | yield* git(updater, ["commit", "-m", "remote commit"]); |
| 1157 | yield* git(updater, ["push", "origin", initialBranch]); |
| 1158 | return { |
| 1159 | cwd, |
| 1160 | remote, |
| 1161 | updater, |
| 1162 | initialBranch, |
| 1163 | remoteHead: yield* git(updater, ["rev-parse", "HEAD"]), |
| 1164 | }; |
| 1165 | }); |
| 1166 | |
| 1167 | it.effect("resolves a status waiter when Pull claims its queued fetch", () => |
| 1168 | Effect.scoped( |
| 1169 | Effect.gen(function* () { |
| 1170 | const { cwd, remoteHead } = yield* cloneBehindRemote; |
| 1171 | const blockers: string[] = []; |
| 1172 | for (let index = 0; index < 4; index++) { |
| 1173 | const blocker = yield* cloneBehindRemote; |
| 1174 | blockers.push(NodeFS.realpathSync.native(blocker.cwd)); |
| 1175 | } |
| 1176 | const targetPath = NodeFS.realpathSync.native(cwd); |
| 1177 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1178 | const release = yield* Deferred.make<void>(); |
| 1179 | const blockersStarted = yield* Deferred.make<void>(); |
| 1180 | const targetEntered = yield* Deferred.make<void>(); |
| 1181 | let running = 0; |
| 1182 | let targetFetches = 0; |
| 1183 | let waiterSucceeded = false; |
| 1184 | const spawner = ChildProcessSpawner.make((command) => |
| 1185 | Effect.gen(function* () { |
| 1186 | const handle = yield* delegate.spawn(command); |
| 1187 | if (!ChildProcess.isStandardCommand(command) || !command.args.includes("fetch")) |
| 1188 | return handle; |
| 1189 | const commandCwd = String(command.options.cwd); |
| 1190 | if (commandCwd === targetPath) targetFetches++; |
| 1191 | if (blockers.includes(commandCwd)) { |
| 1192 | running++; |
| 1193 | if (running === 4) yield* Deferred.succeed(blockersStarted, undefined); |
| 1194 | yield* Deferred.await(release); |
| 1195 | } |
| 1196 | return handle; |
| 1197 | }), |
| 1198 | ); |
| 1199 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1200 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1201 | ); |
| 1202 | const tracer = Tracer.make({ |
| 1203 | span(options) { |
| 1204 | const span = new Tracer.NativeSpan(options); |
| 1205 | if (options.name === "GitVcsDriver.fetchRemoteForStatus.wait") { |
| 1206 | const attribute = span.attribute.bind(span); |
| 1207 | span.attribute = (key, value) => { |
| 1208 | attribute(key, value); |
| 1209 | if (key === "statusFetch.joining") Deferred.doneUnsafe(targetEntered, Effect.void); |
| 1210 | }; |
| 1211 | const end = span.end.bind(span); |
| 1212 | span.end = (endTime, exit) => { |
| 1213 | waiterSucceeded = Exit.isSuccess(exit); |
| 1214 | end(endTime, exit); |
| 1215 | }; |
| 1216 | } |
| 1217 | return span; |
| 1218 | }, |
| 1219 | }); |
| 1220 | yield* Effect.gen(function* () { |
| 1221 | for (const blocker of blockers) { |
| 1222 | yield* driver.statusDetailsRemote(blocker).pipe(Effect.forkChild); |
| 1223 | } |
| 1224 | yield* Deferred.await(blockersStarted); |
| 1225 | const status = yield* driver |
| 1226 | .statusDetailsRemote(cwd) |
| 1227 | .pipe(Effect.withTracer(tracer), Effect.forkChild({ startImmediately: true })); |
| 1228 | yield* Deferred.await(targetEntered); |
| 1229 | const pull = yield* driver.pullCurrentBranch(cwd); |
| 1230 | const refreshed = yield* Fiber.join(status); |
| 1231 | assert.equal(pull.status, "pulled"); |
| 1232 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); |
| 1233 | assert.isTrue(waiterSucceeded); |
| 1234 | assert.equal(refreshed.behindCount, 0); |
| 1235 | assert.equal(targetFetches, 0); |
| 1236 | }).pipe(Effect.ensuring(Deferred.succeed(release, undefined))); |
| 1237 | }), |
| 1238 | ).pipe(Effect.provide(layerTest)), |
| 1239 | ); |
| 1240 | |
| 1241 | it.effect("the startup pull waits for a status fetch that runs past five seconds", () => |
| 1242 | Effect.scoped( |
| 1243 | Effect.gen(function* () { |
| 1244 | const { cwd, remoteHead } = yield* cloneBehindRemote; |
| 1245 | const targetPath = NodeFS.realpathSync.native(cwd); |
| 1246 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1247 | const fetchHeld = yield* Deferred.make<void>(); |
| 1248 | const release = yield* Deferred.make<void>(); |
| 1249 | let held = false; |
| 1250 | const spawner = ChildProcessSpawner.make((command) => |
| 1251 | Effect.gen(function* () { |
| 1252 | if ( |
| 1253 | !held && |
| 1254 | ChildProcess.isStandardCommand(command) && |
| 1255 | command.args.includes("fetch") && |
| 1256 | String(command.options.cwd) === targetPath |
| 1257 | ) { |
| 1258 | held = true; |
| 1259 | yield* Deferred.succeed(fetchHeld, undefined); |
| 1260 | yield* Deferred.await(release); |
| 1261 | } |
| 1262 | return yield* delegate.spawn(command); |
| 1263 | }), |
| 1264 | ); |
| 1265 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1266 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1267 | ); |
| 1268 | const startup = yield* autoPullProjects( |
| 1269 | [{ id: ProjectId.make("behind"), workspaceRoot: cwd, autoPull: true }], |
| 1270 | { ...DEFAULT_SERVER_SETTINGS, defaultAutoPull: true }, |
| 1271 | ).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver), Effect.forkChild); |
| 1272 | yield* Deferred.await(fetchHeld); |
| 1273 | yield* TestClock.adjust("6 seconds"); |
| 1274 | yield* Deferred.succeed(release, undefined); |
| 1275 | yield* Fiber.join(startup); |
| 1276 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); |
| 1277 | }), |
| 1278 | ).pipe(Effect.provide(layerTest)), |
| 1279 | ); |
| 1280 | |
| 1281 | const claimedFetchFallbacks = ["diverged", "interrupted", "upstream-only"] as const; |
| 1282 | |
| 1283 | it.effect.each(claimedFetchFallbacks)( |
| 1284 | "falls back to the claimed status fetch when Pull is %s", |
| 1285 | (failure) => |
| 1286 | Effect.scoped( |
| 1287 | Effect.gen(function* () { |
| 1288 | const { cwd, updater, remoteHead } = yield* cloneBehindRemote; |
| 1289 | if (failure === "upstream-only") { |
| 1290 | yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); |
| 1291 | yield* writeTextFile(cwd, ".git/refs/remotes/origin/other.lock", ""); |
| 1292 | } |
| 1293 | if (failure === "diverged") { |
| 1294 | yield* writeTextFile(cwd, "local.txt", "local\n"); |
| 1295 | yield* git(cwd, ["add", "local.txt"]); |
| 1296 | yield* git(cwd, ["commit", "-m", "local commit"]); |
| 1297 | } |
| 1298 | const blockers: string[] = []; |
| 1299 | for (let index = 0; index < 4; index++) { |
| 1300 | const blocker = yield* cloneBehindRemote; |
| 1301 | blockers.push(NodeFS.realpathSync.native(blocker.cwd)); |
| 1302 | } |
| 1303 | const targetPath = NodeFS.realpathSync.native(cwd); |
| 1304 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1305 | const release = yield* Deferred.make<void>(); |
| 1306 | const blockersStarted = yield* Deferred.make<void>(); |
| 1307 | const targetEntered = yield* Deferred.make<void>(); |
| 1308 | const targetFetchStarted = yield* Deferred.make<void>(); |
| 1309 | const pullBeforeFetch = yield* Deferred.make<void>(); |
| 1310 | const releasePull = yield* Deferred.make<void>(); |
| 1311 | let running = 0; |
| 1312 | let targetFetches = 0; |
| 1313 | let waiterSucceeded = false; |
| 1314 | let targetFetchExitCode: number | undefined; |
| 1315 | const spawner = ChildProcessSpawner.make((command) => |
| 1316 | Effect.gen(function* () { |
| 1317 | if (ChildProcess.isStandardCommand(command)) { |
| 1318 | const commandCwd = NodeFS.realpathSync.native(String(command.options.cwd)); |
| 1319 | if ( |
| 1320 | commandCwd === targetPath && |
| 1321 | failure === "interrupted" && |
| 1322 | command.args[0] === "rev-parse" && |
| 1323 | command.args[1] === "HEAD" && |
| 1324 | command.args.length === 2 |
| 1325 | ) { |
| 1326 | yield* Deferred.succeed(pullBeforeFetch, undefined); |
| 1327 | yield* Deferred.await(releasePull); |
| 1328 | } |
| 1329 | } |
| 1330 | const handle = yield* delegate.spawn(command); |
| 1331 | // A status fetch downloads once, then fetches again only to move refs. |
| 1332 | if (!ChildProcess.isStandardCommand(command) || !command.args.includes("--dry-run")) |
| 1333 | return handle; |
| 1334 | const commandCwd = String(command.options.cwd); |
| 1335 | if (commandCwd === targetPath) { |
| 1336 | targetFetches++; |
| 1337 | yield* Deferred.succeed(targetFetchStarted, undefined); |
| 1338 | return ChildProcessSpawner.makeHandle({ |
| 1339 | ...handle, |
| 1340 | exitCode: handle.exitCode.pipe( |
| 1341 | Effect.tap((exitCode) => |
| 1342 | Effect.sync(() => { |
| 1343 | targetFetchExitCode = exitCode; |
| 1344 | }), |
| 1345 | ), |
| 1346 | ), |
| 1347 | }); |
| 1348 | } |
| 1349 | if (blockers.includes(commandCwd)) { |
| 1350 | running++; |
| 1351 | if (running === 4) yield* Deferred.succeed(blockersStarted, undefined); |
| 1352 | yield* Deferred.await(release); |
| 1353 | } |
| 1354 | return handle; |
| 1355 | }), |
| 1356 | ); |
| 1357 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1358 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1359 | ); |
| 1360 | const tracer = Tracer.make({ |
| 1361 | span(options) { |
| 1362 | const span = new Tracer.NativeSpan(options); |
| 1363 | if (options.name === "GitVcsDriver.fetchRemoteForStatus.wait") { |
| 1364 | const attribute = span.attribute.bind(span); |
| 1365 | span.attribute = (key, value) => { |
| 1366 | attribute(key, value); |
| 1367 | if (key === "statusFetch.joining") |
| 1368 | Deferred.doneUnsafe(targetEntered, Effect.void); |
| 1369 | }; |
| 1370 | const end = span.end.bind(span); |
| 1371 | span.end = (endTime, exit) => { |
| 1372 | waiterSucceeded = Exit.isSuccess(exit); |
| 1373 | end(endTime, exit); |
| 1374 | }; |
| 1375 | } |
| 1376 | return span; |
| 1377 | }, |
| 1378 | }); |
| 1379 | yield* Effect.gen(function* () { |
| 1380 | for (const blocker of blockers) { |
| 1381 | yield* driver.statusDetailsRemote(blocker).pipe(Effect.forkChild); |
| 1382 | } |
| 1383 | yield* Deferred.await(blockersStarted); |
| 1384 | const status = yield* driver |
| 1385 | .statusDetailsRemote(cwd) |
| 1386 | .pipe(Effect.withTracer(tracer), Effect.forkChild({ startImmediately: true })); |
| 1387 | yield* Deferred.await(targetEntered); |
| 1388 | if (failure === "interrupted") { |
| 1389 | const pull = yield* driver.pullCurrentBranch(cwd).pipe(Effect.forkChild); |
| 1390 | yield* Deferred.await(pullBeforeFetch); |
| 1391 | yield* Fiber.interrupt(pull); |
| 1392 | const exit = yield* Fiber.await(pull); |
| 1393 | assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)); |
| 1394 | } else if (failure === "upstream-only") { |
| 1395 | assert.equal((yield* driver.pullCurrentBranch(cwd)).status, "pulled"); |
| 1396 | yield* (yield* FileSystem.FileSystem).remove( |
| 1397 | `${cwd}/.git/refs/remotes/origin/other.lock`, |
| 1398 | ); |
| 1399 | } else { |
| 1400 | const error = yield* Effect.flip(driver.pullCurrentBranch(cwd)); |
| 1401 | assert.equal(error.operation, "GitVcsDriver.pullCurrentBranch.pull"); |
| 1402 | } |
| 1403 | assert.equal(targetFetches, 0); |
| 1404 | yield* Deferred.succeed(release, undefined); |
| 1405 | yield* Deferred.await(targetFetchStarted); |
| 1406 | assert.isTrue((yield* Fiber.join(status)).isRepo); |
| 1407 | assert.isTrue(waiterSucceeded); |
| 1408 | assert.equal(targetFetches, 1); |
| 1409 | assert.equal(targetFetchExitCode, 0); |
| 1410 | if (failure === "upstream-only") { |
| 1411 | assert.equal(yield* git(cwd, ["rev-parse", "refs/remotes/origin/other"]), remoteHead); |
| 1412 | } |
| 1413 | }).pipe( |
| 1414 | Effect.ensuring( |
| 1415 | Effect.all([ |
| 1416 | Deferred.succeed(release, undefined), |
| 1417 | Deferred.succeed(releasePull, undefined), |
| 1418 | ]), |
| 1419 | ), |
| 1420 | ); |
| 1421 | }), |
| 1422 | ).pipe(Effect.provide(layerTest)), |
| 1423 | ); |
| 1424 | |
| 1425 | it.effect("waits for a running status fetch before starting Pull", () => |
| 1426 | Effect.scoped( |
| 1427 | Effect.gen(function* () { |
| 1428 | const { cwd, remoteHead } = yield* cloneBehindRemote; |
| 1429 | const targetPath = NodeFS.realpathSync.native(cwd); |
| 1430 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1431 | const fetchStarted = yield* Deferred.make<void>(); |
| 1432 | const releaseFetch = yield* Deferred.make<void>(); |
| 1433 | const pullResolvedCommonDir = yield* Deferred.make<void>(); |
| 1434 | const pullStarted = yield* Deferred.make<void>(); |
| 1435 | const events: string[] = []; |
| 1436 | const spawner = ChildProcessSpawner.make((command) => |
| 1437 | Effect.gen(function* () { |
| 1438 | if (!ChildProcess.isStandardCommand(command)) return yield* delegate.spawn(command); |
| 1439 | const target = NodeFS.realpathSync.native(String(command.options.cwd)) === targetPath; |
| 1440 | if (target && command.args.includes("pull")) { |
| 1441 | events.push("pull-spawn"); |
| 1442 | yield* Deferred.succeed(pullStarted, undefined); |
| 1443 | } |
| 1444 | const handle = yield* delegate.spawn(command); |
| 1445 | if (target && command.args.includes("fetch")) { |
| 1446 | yield* Deferred.succeed(fetchStarted, undefined); |
| 1447 | yield* Deferred.await(releaseFetch); |
| 1448 | yield* handle.exitCode; |
| 1449 | events.push("fetch-exit"); |
| 1450 | } |
| 1451 | return handle; |
| 1452 | }), |
| 1453 | ); |
| 1454 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1455 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1456 | ); |
| 1457 | const tracer = Tracer.make({ |
| 1458 | span(options) { |
| 1459 | const span = new Tracer.NativeSpan(options); |
| 1460 | if (options.name === "resolveGitCommonDir") { |
| 1461 | const end = span.end.bind(span); |
| 1462 | span.end = (endTime, exit) => { |
| 1463 | end(endTime, exit); |
| 1464 | Deferred.doneUnsafe(pullResolvedCommonDir, Effect.void); |
| 1465 | }; |
| 1466 | } |
| 1467 | return span; |
| 1468 | }, |
| 1469 | }); |
| 1470 | yield* Effect.gen(function* () { |
| 1471 | yield* driver.statusDetailsRemote(cwd).pipe(Effect.forkChild); |
| 1472 | yield* Deferred.await(fetchStarted); |
| 1473 | const pull = yield* driver |
| 1474 | .pullCurrentBranch(cwd) |
| 1475 | .pipe(Effect.withTracer(tracer), Effect.forkChild({ startImmediately: true })); |
| 1476 | yield* Deferred.await(pullResolvedCommonDir); |
| 1477 | assert.isFalse(yield* Deferred.isDone(pullStarted)); |
| 1478 | assert.isUndefined(pull.pollUnsafe()); |
| 1479 | yield* Deferred.succeed(releaseFetch, undefined); |
| 1480 | const result = yield* Fiber.join(pull); |
| 1481 | assert.equal(result.status, "pulled"); |
| 1482 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); |
| 1483 | // The status fetch downloads, then fetches again to move the refs it found. |
| 1484 | assert.deepEqual(events, ["fetch-exit", "fetch-exit", "pull-spawn"]); |
| 1485 | }).pipe(Effect.ensuring(Deferred.succeed(releaseFetch, undefined))); |
| 1486 | }), |
| 1487 | ).pipe(Effect.provide(layerTest)), |
| 1488 | ); |
| 1489 | |
| 1490 | it.effect("still fetches other branches on the first pull", () => |
| 1491 | Effect.gen(function* () { |
| 1492 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 1493 | const { cwd, updater, remoteHead } = yield* cloneBehindRemote; |
| 1494 | yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); |
| 1495 | |
| 1496 | const result = yield* driver.pullCurrentBranch(cwd); |
| 1497 | |
| 1498 | assert.equal(result.status, "pulled"); |
| 1499 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); |
| 1500 | assert.equal(yield* git(cwd, ["rev-parse", "refs/remotes/origin/other"]), remoteHead); |
| 1501 | }).pipe(Effect.provide(layerTest)), |
| 1502 | ); |
| 1503 | |
| 1504 | it.effect.each([false, true])( |
| 1505 | "pulls past an unrelated lock with custom fetch mapping=%s", |
| 1506 | (customMapping) => |
| 1507 | Effect.gen(function* () { |
| 1508 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 1509 | const fs = yield* FileSystem.FileSystem; |
| 1510 | const { cwd, updater, initialBranch, remoteHead } = yield* cloneBehindRemote; |
| 1511 | yield* git(cwd, ["tag", initialBranch]); |
| 1512 | yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); |
| 1513 | const remoteName = customMapping ? "team/upstream" : "origin"; |
| 1514 | const refPrefix = customMapping |
| 1515 | ? `refs/remotes/${remoteName}/mapped` |
| 1516 | : "refs/remotes/origin"; |
| 1517 | if (customMapping) { |
| 1518 | yield* git(cwd, ["remote", "rename", "origin", remoteName]); |
| 1519 | yield* git(cwd, ["config", `remote.${remoteName}.fetch`, `+refs/heads/*:${refPrefix}/*`]); |
| 1520 | yield* git(cwd, ["update-ref", `${refPrefix}/${initialBranch}`, "HEAD"]); |
| 1521 | } |
| 1522 | const lock = `.git/${refPrefix}/other.lock`; |
| 1523 | yield* writeTextFile(cwd, lock, ""); |
| 1524 | |
| 1525 | const result = yield* driver.pullCurrentBranch(cwd); |
| 1526 | |
| 1527 | assert.equal(result.status, "pulled"); |
| 1528 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); |
| 1529 | assert.equal(yield* git(cwd, ["rev-parse", `${refPrefix}/${initialBranch}`]), remoteHead); |
| 1530 | assert.isTrue(yield* fs.exists(`${cwd}/${lock}`)); |
| 1531 | assert.equal(yield* fs.readFileString(`${cwd}/${lock}`), ""); |
| 1532 | }).pipe(Effect.provide(layerTest)), |
| 1533 | ); |
| 1534 | |
| 1535 | it.effect("reports an upstream lock after the fallback without removing it", () => |
| 1536 | Effect.gen(function* () { |
| 1537 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 1538 | const fs = yield* FileSystem.FileSystem; |
| 1539 | const { cwd, initialBranch } = yield* cloneBehindRemote; |
| 1540 | const before = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 1541 | const lock = `.git/refs/remotes/origin/${initialBranch}.lock`; |
| 1542 | yield* writeTextFile(cwd, lock, ""); |
| 1543 | |
| 1544 | const error = yield* Effect.flip(driver.pullCurrentBranch(cwd)); |
| 1545 | |
| 1546 | assert.include(error.detail, "could not update a local reference"); |
| 1547 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), before); |
| 1548 | assert.isTrue(yield* fs.exists(`${cwd}/${lock}`)); |
| 1549 | }).pipe(Effect.provide(layerTest)), |
| 1550 | ); |
| 1551 | |
| 1552 | it.effect.each(["branch", "HEAD"] as const)( |
| 1553 | "does not retry a failed fetch if another operation moved %s", |
| 1554 | (moved) => |
| 1555 | Effect.gen(function* () { |
| 1556 | const fixtureDriver = yield* GitVcsDriver.GitVcsDriver; |
| 1557 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1558 | const { cwd, updater } = yield* cloneBehindRemote; |
| 1559 | yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); |
| 1560 | yield* writeTextFile(cwd, ".git/refs/remotes/origin/other.lock", ""); |
| 1561 | let pulls = 0; |
| 1562 | const spawner = ChildProcessSpawner.make((command) => |
| 1563 | Effect.gen(function* () { |
| 1564 | const handle = yield* delegate.spawn(command); |
| 1565 | if (!ChildProcess.isStandardCommand(command) || !command.args.includes("pull")) { |
| 1566 | return handle; |
| 1567 | } |
| 1568 | pulls += 1; |
| 1569 | return ChildProcessSpawner.makeHandle({ |
| 1570 | ...handle, |
| 1571 | exitCode: handle.exitCode.pipe( |
| 1572 | Effect.tap(() => |
| 1573 | git( |
| 1574 | cwd, |
| 1575 | moved === "branch" |
| 1576 | ? ["checkout", "-b", "moved"] |
| 1577 | : ["commit", "--allow-empty", "-m", "concurrent commit"], |
| 1578 | ).pipe( |
| 1579 | Effect.provideService(GitVcsDriver.GitVcsDriver, fixtureDriver), |
| 1580 | Effect.orDie, |
| 1581 | ), |
| 1582 | ), |
| 1583 | ), |
| 1584 | }); |
| 1585 | }), |
| 1586 | ); |
| 1587 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1588 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1589 | ); |
| 1590 | |
| 1591 | const error = yield* Effect.flip(driver.pullCurrentBranch(cwd)); |
| 1592 | |
| 1593 | assert.include(error.detail, "could not update a local reference"); |
| 1594 | assert.equal(pulls, 1); |
| 1595 | }).pipe(Effect.scoped, Effect.provide(layerServerConfig.pipe(Layer.provideMerge(layerTest)))), |
| 1596 | ); |
| 1597 | |
| 1598 | it.effect.each(["stdout", "stderr"] as const)( |
| 1599 | "reports a fast-forward whose %s passes the cap as pulled", |
| 1600 | (stream) => |
| 1601 | Effect.scoped( |
| 1602 | Effect.gen(function* () { |
| 1603 | const driver = yield* withPaddedPull(stream); |
| 1604 | yield* Effect.gen(function* () { |
| 1605 | const { cwd, remoteHead } = yield* cloneBehindRemote; |
| 1606 | |
| 1607 | const result = yield* driver.pullCurrentBranch(cwd); |
| 1608 | |
| 1609 | assert.equal(result.status, "pulled"); |
| 1610 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); |
| 1611 | }).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); |
| 1612 | }), |
| 1613 | ).pipe( |
| 1614 | Effect.provide( |
| 1615 | layerServerConfig.pipe( |
| 1616 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1617 | ), |
| 1618 | ), |
| 1619 | ), |
| 1620 | ); |
| 1621 | |
| 1622 | it.effect("still fails a pull that Git rejects, whatever its output size", () => |
| 1623 | Effect.scoped( |
| 1624 | Effect.gen(function* () { |
| 1625 | const pulls: ReadonlyArray<string>[] = []; |
| 1626 | const driver = yield* withPaddedPull("stderr", (args) => pulls.push(args)); |
| 1627 | yield* Effect.gen(function* () { |
| 1628 | const { cwd } = yield* cloneBehindRemote; |
| 1629 | yield* writeTextFile(cwd, "local.txt", "local\n"); |
| 1630 | yield* git(cwd, ["add", "local.txt"]); |
| 1631 | yield* git(cwd, ["commit", "-m", "local commit"]); |
| 1632 | |
| 1633 | const error = yield* Effect.flip(driver.pullCurrentBranch(cwd)); |
| 1634 | |
| 1635 | assert.equal(error.operation, "GitVcsDriver.pullCurrentBranch.pull"); |
| 1636 | assert.equal(error.exitCode, 128); |
| 1637 | assert.notInclude(error.detail, "exceeded"); |
| 1638 | assert.lengthOf(pulls, 1); |
| 1639 | }).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); |
| 1640 | }), |
| 1641 | ).pipe( |
| 1642 | Effect.provide( |
| 1643 | layerServerConfig.pipe( |
| 1644 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1645 | ), |
| 1646 | ), |
| 1647 | ), |
| 1648 | ); |
| 1649 | |
| 1650 | // A slow smudge filter (LFS) can hold the checkout past 30 seconds; killing it there leaves a |
| 1651 | // half-updated working tree. The automatic pulls and pull request refresh use these defaults. |
| 1652 | it.effect.each(["pull", "merge"] as const)( |
| 1653 | "lets a slow %s checkout finish instead of killing it at 30 seconds", |
| 1654 | (subcommand) => |
| 1655 | Effect.gen(function* () { |
| 1656 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1657 | const { cwd, remoteHead } = yield* cloneBehindRemote; |
| 1658 | yield* git(cwd, ["fetch", "origin"]); |
| 1659 | const checkoutStarted = yield* Deferred.make<void>(); |
| 1660 | const releaseCheckout = yield* Deferred.make<void>(); |
| 1661 | const spawner = ChildProcessSpawner.make((command) => |
| 1662 | Effect.gen(function* () { |
| 1663 | const handle = yield* delegate.spawn(command); |
| 1664 | if (!ChildProcess.isStandardCommand(command) || command.args[0] !== subcommand) { |
| 1665 | return handle; |
| 1666 | } |
| 1667 | yield* Deferred.succeed(checkoutStarted, undefined); |
| 1668 | return ChildProcessSpawner.makeHandle({ |
| 1669 | ...handle, |
| 1670 | exitCode: Deferred.await(releaseCheckout).pipe(Effect.andThen(handle.exitCode)), |
| 1671 | }); |
| 1672 | }), |
| 1673 | ); |
| 1674 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1675 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1676 | ); |
| 1677 | |
| 1678 | const move = |
| 1679 | subcommand === "pull" |
| 1680 | ? Effect.asVoid(driver.pullCurrentBranch(cwd)) |
| 1681 | : Effect.asVoid(driver.refreshCheckedOutBranch({ cwd, targetCommit: remoteHead })); |
| 1682 | const moving = yield* move.pipe(Effect.forkChild({ startImmediately: true })); |
| 1683 | yield* Deferred.await(checkoutStarted); |
| 1684 | yield* TestClock.adjust("60 seconds"); |
| 1685 | yield* Deferred.succeed(releaseCheckout, undefined); |
| 1686 | |
| 1687 | yield* Fiber.join(moving); |
| 1688 | assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); |
| 1689 | }).pipe(Effect.provide(layerTest)), |
| 1690 | ); |
| 1691 | }); |
| 1692 | |
| 1693 | it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => |
| 1694 | Effect.scoped( |
| 1695 | Effect.gen(function* () { |
| 1696 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1697 | const firstWorktreeScanStarted = yield* Deferred.make<void>(); |
| 1698 | const firstRefScanCompleted = yield* Deferred.make<void>(); |
| 1699 | const releaseFirstWorktreeScan = yield* Deferred.make<void>(); |
| 1700 | const delayFirstWorktreeScan = yield* Ref.make(true); |
| 1701 | const refScans = yield* Ref.make(0); |
| 1702 | const coordinatingSpawner = ChildProcessSpawner.make((command) => |
| 1703 | Effect.gen(function* () { |
| 1704 | if (!ChildProcess.isStandardCommand(command)) { |
| 1705 | return yield* Effect.die("expected a standard Git command"); |
| 1706 | } |
| 1707 | const isWorktreeScan = |
| 1708 | command.args.includes("worktree") && command.args.includes("--porcelain"); |
| 1709 | if (isWorktreeScan && (yield* Ref.getAndSet(delayFirstWorktreeScan, false))) { |
| 1710 | yield* Deferred.succeed(firstWorktreeScanStarted, undefined); |
| 1711 | yield* Deferred.await(releaseFirstWorktreeScan); |
| 1712 | } |
| 1713 | const handle = yield* delegate.spawn(command); |
| 1714 | const isRefScan = |
| 1715 | command.args.includes("for-each-ref") && |
| 1716 | command.args.includes("refs/heads") && |
| 1717 | command.args.includes("refs/remotes"); |
| 1718 | if (!isRefScan) return handle; |
| 1719 | const scan = yield* Ref.updateAndGet(refScans, (count) => count + 1); |
| 1720 | return scan === 1 |
| 1721 | ? ChildProcessSpawner.makeHandle({ |
| 1722 | ...handle, |
| 1723 | exitCode: handle.exitCode.pipe( |
| 1724 | Effect.tap(() => Deferred.succeed(firstRefScanCompleted, undefined)), |
| 1725 | ), |
| 1726 | }) |
| 1727 | : handle; |
| 1728 | }), |
| 1729 | ); |
| 1730 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1731 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner), |
| 1732 | ); |
| 1733 | const cwd = yield* makeTmpDir(); |
| 1734 | yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); |
| 1735 | |
| 1736 | const inFlight = yield* driver |
| 1737 | .listRefs({ cwd, refresh: true, limit: 100 }) |
| 1738 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1739 | yield* Deferred.await(firstWorktreeScanStarted); |
| 1740 | yield* Deferred.await(firstRefScanCompleted); |
| 1741 | |
| 1742 | yield* driver.createRef({ cwd, refName: "feature/during-refresh" }); |
| 1743 | yield* Deferred.succeed(releaseFirstWorktreeScan, undefined); |
| 1744 | |
| 1745 | const refs = yield* Fiber.join(inFlight); |
| 1746 | assert.isTrue(refs.refs.some((ref) => ref.name === "feature/during-refresh")); |
| 1747 | assert.equal(yield* Ref.get(refScans), 2); |
| 1748 | }), |
| 1749 | ).pipe( |
| 1750 | Effect.provide( |
| 1751 | layerServerConfig.pipe( |
| 1752 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1753 | ), |
| 1754 | ), |
| 1755 | ), |
| 1756 | ); |
| 1757 | |
| 1758 | it.effect("superseded ref snapshots of one repository do not evict another's", () => |
| 1759 | Effect.scoped( |
| 1760 | Effect.gen(function* () { |
| 1761 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1762 | const quietRepo = yield* makeTmpDir(); |
| 1763 | const quietRepoRealPath = NodeFS.realpathSync.native(quietRepo); |
| 1764 | const quietRepoScans = yield* Ref.make(0); |
| 1765 | const countingSpawner = ChildProcessSpawner.make((command) => |
| 1766 | Effect.gen(function* () { |
| 1767 | if ( |
| 1768 | ChildProcess.isStandardCommand(command) && |
| 1769 | command.args.includes("for-each-ref") && |
| 1770 | command.args.includes("refs/remotes") && |
| 1771 | NodeFS.realpathSync.native(String(command.options.cwd)).startsWith(quietRepoRealPath) |
| 1772 | ) { |
| 1773 | yield* Ref.update(quietRepoScans, (count) => count + 1); |
| 1774 | } |
| 1775 | return yield* delegate.spawn(command); |
| 1776 | }), |
| 1777 | ); |
| 1778 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1779 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, countingSpawner), |
| 1780 | ); |
| 1781 | const busyRepo = yield* makeTmpDir(); |
| 1782 | yield* initRepoWithCommit(quietRepo).pipe( |
| 1783 | Effect.provideService(GitVcsDriver.GitVcsDriver, driver), |
| 1784 | ); |
| 1785 | yield* initRepoWithCommit(busyRepo).pipe( |
| 1786 | Effect.provideService(GitVcsDriver.GitVcsDriver, driver), |
| 1787 | ); |
| 1788 | |
| 1789 | yield* driver.listRefs({ cwd: quietRepo }); |
| 1790 | // More epochs than the snapshot cache holds. |
| 1791 | for (let index = 0; index < 70; index++) { |
| 1792 | yield* driver.invalidateRefs(busyRepo); |
| 1793 | yield* driver.listRefs({ cwd: busyRepo }); |
| 1794 | } |
| 1795 | yield* driver.listRefs({ cwd: quietRepo }); |
| 1796 | |
| 1797 | assert.equal(yield* Ref.get(quietRepoScans), 1); |
| 1798 | }), |
| 1799 | ).pipe( |
| 1800 | Effect.provide( |
| 1801 | layerServerConfig.pipe( |
| 1802 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1803 | ), |
| 1804 | ), |
| 1805 | ), |
| 1806 | ); |
| 1807 | |
| 1808 | it.effect("invalidates a ref snapshot when a mutation fails after changing Git", () => |
| 1809 | Effect.scoped( |
| 1810 | Effect.gen(function* () { |
| 1811 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1812 | const partiallyFailingSpawner = ChildProcessSpawner.make((command) => |
| 1813 | Effect.gen(function* () { |
| 1814 | if (!ChildProcess.isStandardCommand(command)) { |
| 1815 | return yield* Effect.die("expected a standard Git command"); |
| 1816 | } |
| 1817 | if (command.args[0] === "branch" && command.args.at(-1) === "feature/partial-failure") { |
| 1818 | const handle = yield* delegate.spawn(command); |
| 1819 | yield* handle.exitCode; |
| 1820 | return makeNonRepositoryHandle(); |
| 1821 | } |
| 1822 | return yield* delegate.spawn(command); |
| 1823 | }), |
| 1824 | ); |
| 1825 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1826 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, partiallyFailingSpawner), |
| 1827 | ); |
| 1828 | const cwd = yield* makeTmpDir(); |
| 1829 | yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); |
| 1830 | yield* driver.listRefs({ cwd, refresh: true }); |
| 1831 | |
| 1832 | yield* driver.createRef({ cwd, refName: "feature/partial-failure" }).pipe(Effect.flip); |
| 1833 | |
| 1834 | const refs = yield* driver.listRefs({ cwd }); |
| 1835 | assert.isTrue(refs.refs.some((ref) => ref.name === "feature/partial-failure")); |
| 1836 | }), |
| 1837 | ).pipe( |
| 1838 | Effect.provide( |
| 1839 | layerServerConfig.pipe( |
| 1840 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1841 | ), |
| 1842 | ), |
| 1843 | ), |
| 1844 | ); |
| 1845 | |
| 1846 | it.effect("marks the current branch when worktree metadata is unavailable", () => |
| 1847 | Effect.scoped( |
| 1848 | Effect.gen(function* () { |
| 1849 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1850 | const incompleteMetadataSpawner = ChildProcessSpawner.make((command) => |
| 1851 | Effect.gen(function* () { |
| 1852 | if (!ChildProcess.isStandardCommand(command)) { |
| 1853 | return yield* Effect.die("expected a standard Git command"); |
| 1854 | } |
| 1855 | const isWorktreeRoot = |
| 1856 | command.args.includes("rev-parse") && command.args.includes("--show-toplevel"); |
| 1857 | const isWorktreeList = |
| 1858 | command.args.includes("worktree") && command.args.includes("--porcelain"); |
| 1859 | if (isWorktreeRoot || isWorktreeList) { |
| 1860 | return makeNonRepositoryHandle(); |
| 1861 | } |
| 1862 | return yield* delegate.spawn(command); |
| 1863 | }), |
| 1864 | ); |
| 1865 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1866 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, incompleteMetadataSpawner), |
| 1867 | ); |
| 1868 | const cwd = yield* makeTmpDir(); |
| 1869 | const { initialBranch } = yield* initRepoWithCommit(cwd).pipe( |
| 1870 | Effect.provideService(GitVcsDriver.GitVcsDriver, driver), |
| 1871 | ); |
| 1872 | |
| 1873 | const refs = yield* driver.listRefs({ cwd, refresh: true }); |
| 1874 | |
| 1875 | assert.isTrue(refs.isRepo); |
| 1876 | assert.isTrue(refs.refs.find((ref) => ref.name === initialBranch)?.current); |
| 1877 | }), |
| 1878 | ).pipe( |
| 1879 | Effect.provide( |
| 1880 | layerServerConfig.pipe( |
| 1881 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1882 | ), |
| 1883 | ), |
| 1884 | ), |
| 1885 | ); |
| 1886 | |
| 1887 | it.effect("ignores worktree metadata for directories that no longer exist", () => |
| 1888 | Effect.scoped( |
| 1889 | Effect.gen(function* () { |
| 1890 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1891 | const missingWorktreePath = "/missing/deleted-worktree"; |
| 1892 | const staleWorktreeSpawner = ChildProcessSpawner.make((command) => |
| 1893 | Effect.gen(function* () { |
| 1894 | if (!ChildProcess.isStandardCommand(command)) { |
| 1895 | return yield* Effect.die("expected a standard Git command"); |
| 1896 | } |
| 1897 | const isWorktreeList = |
| 1898 | command.args.includes("worktree") && command.args.includes("--porcelain"); |
| 1899 | if (isWorktreeList) { |
| 1900 | return makeSuccessfulHandle( |
| 1901 | `worktree ${missingWorktreePath}\0HEAD deadbeef\0branch refs/heads/stale-worktree\0\0`, |
| 1902 | ); |
| 1903 | } |
| 1904 | return yield* delegate.spawn(command); |
| 1905 | }), |
| 1906 | ); |
| 1907 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1908 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, staleWorktreeSpawner), |
| 1909 | ); |
| 1910 | const cwd = yield* makeTmpDir(); |
| 1911 | yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); |
| 1912 | yield* git(cwd, ["branch", "stale-worktree"]).pipe( |
| 1913 | Effect.provideService(GitVcsDriver.GitVcsDriver, driver), |
| 1914 | ); |
| 1915 | |
| 1916 | const refs = yield* driver.listRefs({ cwd, refresh: true }); |
| 1917 | |
| 1918 | assert.equal(refs.refs.find((ref) => ref.name === "stale-worktree")?.worktreePath, null); |
| 1919 | }), |
| 1920 | ).pipe( |
| 1921 | Effect.provide( |
| 1922 | layerServerConfig.pipe( |
| 1923 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1924 | ), |
| 1925 | ), |
| 1926 | ), |
| 1927 | ); |
| 1928 | |
| 1929 | it.effect("reads worktrees from git that rejects worktree list -z", () => |
| 1930 | Effect.scoped( |
| 1931 | Effect.gen(function* () { |
| 1932 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1933 | // Git before 2.36 has no `worktree list -z` and exits with a usage error. |
| 1934 | const oldGitSpawner = ChildProcessSpawner.make((command) => |
| 1935 | Effect.gen(function* () { |
| 1936 | if (!ChildProcess.isStandardCommand(command)) { |
| 1937 | return yield* Effect.die("expected a standard Git command"); |
| 1938 | } |
| 1939 | if (command.args.includes("worktree") && command.args.includes("-z")) { |
| 1940 | return ChildProcessSpawner.makeHandle({ |
| 1941 | pid: ChildProcessSpawner.ProcessId(1), |
| 1942 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(129)), |
| 1943 | isRunning: Effect.succeed(false), |
| 1944 | kill: () => Effect.void, |
| 1945 | unref: Effect.succeed(Effect.void), |
| 1946 | stdin: Sink.drain, |
| 1947 | stdout: Stream.empty, |
| 1948 | stderr: Stream.encodeText(Stream.make("error: unknown switch `z'")), |
| 1949 | all: Stream.empty, |
| 1950 | getInputFd: () => Sink.drain, |
| 1951 | getOutputFd: () => Stream.empty, |
| 1952 | }); |
| 1953 | } |
| 1954 | return yield* delegate.spawn(command); |
| 1955 | }), |
| 1956 | ); |
| 1957 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 1958 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, oldGitSpawner), |
| 1959 | ); |
| 1960 | const cwd = yield* makeTmpDir(); |
| 1961 | yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); |
| 1962 | const worktreePath = NodeFS.realpathSync.native(yield* makeTmpDir()); |
| 1963 | yield* git(cwd, ["worktree", "add", "-b", "feature/old-git", worktreePath]).pipe( |
| 1964 | Effect.provideService(GitVcsDriver.GitVcsDriver, driver), |
| 1965 | ); |
| 1966 | |
| 1967 | const refs = yield* driver.listRefs({ cwd, refresh: true }); |
| 1968 | const listedPath = refs.refs.find((ref) => ref.name === "feature/old-git")?.worktreePath; |
| 1969 | assert.equal(listedPath && NodeFS.realpathSync.native(listedPath), worktreePath); |
| 1970 | |
| 1971 | const paths = yield* driver.listWorktreePaths(cwd); |
| 1972 | assert.include( |
| 1973 | paths.map((listed) => NodeFS.realpathSync.native(listed)), |
| 1974 | worktreePath, |
| 1975 | ); |
| 1976 | }), |
| 1977 | ).pipe( |
| 1978 | Effect.provide( |
| 1979 | layerServerConfig.pipe( |
| 1980 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1981 | ), |
| 1982 | ), |
| 1983 | ), |
| 1984 | ); |
| 1985 | |
| 1986 | it.effect("commits selected files with git that rejects --pathspec-from-file", () => |
| 1987 | Effect.scoped( |
| 1988 | Effect.gen(function* () { |
| 1989 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1990 | // Git before 2.25 has no `add --pathspec-from-file` and exits with a usage error. |
| 1991 | const oldGitSpawner = ChildProcessSpawner.make((command) => { |
| 1992 | if (!ChildProcess.isStandardCommand(command)) { |
| 1993 | return Effect.die("expected a standard Git command"); |
| 1994 | } |
| 1995 | if (command.args.at(-1) === "version") { |
| 1996 | return Effect.succeed(makeSuccessfulHandle("git version 2.24.4\n")); |
| 1997 | } |
| 1998 | if (command.args.some((arg) => String(arg).startsWith("--pathspec-from-file"))) { |
| 1999 | return Effect.succeed(makeFailedHandle("error: unknown option `pathspec-from-file=-'")); |
| 2000 | } |
| 2001 | return delegate.spawn(command); |
| 2002 | }); |
| 2003 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2004 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, oldGitSpawner), |
| 2005 | ); |
| 2006 | yield* Effect.gen(function* () { |
| 2007 | const cwd = yield* makeTmpDir(); |
| 2008 | yield* initRepoWithCommit(cwd); |
| 2009 | const selected = ["selected[1].txt", "-dash.txt", "with space.txt"]; |
| 2010 | for (const file of selected) yield* writeTextFile(cwd, file, "selected\n"); |
| 2011 | yield* writeTextFile(cwd, "left.txt", "left\n"); |
| 2012 | |
| 2013 | yield* driver.commit(cwd, "Selected", "", { stage: { filePaths: selected } }); |
| 2014 | |
| 2015 | assert.sameMembers( |
| 2016 | (yield* git(cwd, ["show", "--pretty=", "--name-only", "-z", "HEAD"])) |
| 2017 | .split("\0") |
| 2018 | .filter(Boolean), |
| 2019 | selected, |
| 2020 | ); |
| 2021 | assert.equal(yield* git(cwd, ["status", "--porcelain"]), "?? left.txt"); |
| 2022 | }).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); |
| 2023 | }), |
| 2024 | ).pipe( |
| 2025 | Effect.provide( |
| 2026 | layerServerConfig.pipe( |
| 2027 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 2028 | ), |
| 2029 | ), |
| 2030 | ), |
| 2031 | ); |
| 2032 | |
| 2033 | it.effect("does not report a separate git dir as the worktree of its branch", () => |
| 2034 | Effect.scoped( |
| 2035 | Effect.gen(function* () { |
| 2036 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2037 | const cwd = yield* makeTmpDir(); |
| 2038 | const gitDir = yield* makeTmpDir(); |
| 2039 | yield* git(cwd, ["init", `--separate-git-dir=${gitDir}`]); |
| 2040 | yield* git(cwd, ["config", "user.email", "test@test.com"]); |
| 2041 | yield* git(cwd, ["config", "user.name", "Test"]); |
| 2042 | yield* git(cwd, ["commit", "--allow-empty", "-m", "init"]); |
| 2043 | |
| 2044 | const refs = yield* driver.listRefs({ cwd, refresh: true }); |
| 2045 | const worktreePath = refs.refs.find((ref) => ref.current)?.worktreePath; |
| 2046 | |
| 2047 | assert.equal( |
| 2048 | worktreePath && NodeFS.realpathSync.native(worktreePath), |
| 2049 | NodeFS.realpathSync.native(cwd), |
| 2050 | ); |
| 2051 | }), |
| 2052 | ).pipe(Effect.provide(layerTest)), |
| 2053 | ); |
| 2054 | |
| 2055 | it.effect.each([ |
| 2056 | { |
| 2057 | name: "HTTPS credentials", |
| 2058 | stderr: "fatal: Authentication failed for", |
| 2059 | expected: "could not authenticate", |
| 2060 | }, |
| 2061 | { |
| 2062 | name: "SSH credentials", |
| 2063 | stderr: "git@example.com: Permission denied (publickey).", |
| 2064 | expected: "could not authenticate", |
| 2065 | }, |
| 2066 | { |
| 2067 | name: "disabled prompts", |
| 2068 | stderr: "fatal: could not read Username: terminal prompts disabled", |
| 2069 | expected: "could not authenticate", |
| 2070 | }, |
| 2071 | { |
| 2072 | name: "DNS failure", |
| 2073 | stderr: "fatal: Could not resolve host: example.com", |
| 2074 | expected: "could not reach the remote", |
| 2075 | }, |
| 2076 | { |
| 2077 | name: "connection failure", |
| 2078 | stderr: "ssh: connect to host example.com port 22: Connection refused", |
| 2079 | expected: "could not reach the remote", |
| 2080 | }, |
| 2081 | { |
| 2082 | name: "missing remote", |
| 2083 | stderr: "remote: Repository not found.", |
| 2084 | expected: "could not access the remote repository", |
| 2085 | }, |
| 2086 | { |
| 2087 | name: "invalid remote", |
| 2088 | stderr: "fatal: remote does not appear to be a git repository", |
| 2089 | expected: "could not access the remote repository", |
| 2090 | }, |
| 2091 | { |
| 2092 | name: "reference lock", |
| 2093 | stderr: "error: cannot lock ref 'refs/remotes/origin/main': is at abc but expected def", |
| 2094 | expected: "could not update a local reference", |
| 2095 | attempts: 2, |
| 2096 | }, |
| 2097 | { |
| 2098 | name: "lock file", |
| 2099 | stderr: "fatal: Unable to create '/repo/.git/FETCH_HEAD.lock': File exists.", |
| 2100 | expected: "could not update a local reference", |
| 2101 | attempts: 2, |
| 2102 | }, |
| 2103 | { |
| 2104 | name: "reference race on Git 2.53", |
| 2105 | stderr: "error: fetching ref refs/remotes/origin/main failed: incorrect old value provided", |
| 2106 | expected: "could not update a local reference", |
| 2107 | attempts: 2, |
| 2108 | }, |
| 2109 | { |
| 2110 | name: "held reference lock on Git 2.53", |
| 2111 | stderr: "error: fetching ref refs/remotes/origin/main failed: reference already exists", |
| 2112 | expected: "could not update a local reference", |
| 2113 | attempts: 2, |
| 2114 | }, |
| 2115 | { |
| 2116 | name: "broken local ref", |
| 2117 | stderr: "fatal: bad object refs/remotes/origin/dev 2", |
| 2118 | expected: "broken local ref", |
| 2119 | }, |
| 2120 | { |
| 2121 | name: "unrelated remote chatter", |
| 2122 | stderr: |
| 2123 | "remote: Help: authentication failed, connection refused, cannot lock ref\nremote: unrelated service error", |
| 2124 | expected: "git fetch origin failed", |
| 2125 | }, |
| 2126 | { |
| 2127 | name: "HTTPS DNS failure", |
| 2128 | stderr: |
| 2129 | "fatal: unable to access 'https://example.com/repo.git/': Could not resolve host: example.com", |
| 2130 | expected: "could not reach the remote", |
| 2131 | }, |
| 2132 | { |
| 2133 | name: "unknown failure", |
| 2134 | stderr: "fatal: unexpected remote failure", |
| 2135 | expected: "git fetch origin failed", |
| 2136 | }, |
| 2137 | ] as const)("reports $name during fetch without retaining remote output", (scenario) => |
| 2138 | Effect.gen(function* () { |
| 2139 | const secret = "secret-fetch-token"; |
| 2140 | const stderr = `${scenario.stderr}\nhttps://user:${secret}@example.com/private?token=${secret}`; |
| 2141 | const attempts = yield* Ref.make(0); |
| 2142 | const spawner = ChildProcessSpawner.make((command) => |
| 2143 | Effect.gen(function* () { |
| 2144 | if (!ChildProcess.isStandardCommand(command)) |
| 2145 | return yield* Effect.die("expected Git command"); |
| 2146 | if (command.args[0] !== "fetch") return makeNonRepositoryHandle(); |
| 2147 | assert.deepEqual(command.args, ["fetch", "--quiet", "--", "origin"]); |
| 2148 | assert.equal(command.options.env?.LANGUAGE, "C"); |
| 2149 | assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0"); |
| 2150 | yield* Ref.update(attempts, (count) => count + 1); |
| 2151 | return ChildProcessSpawner.makeHandle({ |
| 2152 | pid: ChildProcessSpawner.ProcessId(1), |
| 2153 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)), |
| 2154 | isRunning: Effect.succeed(false), |
| 2155 | kill: () => Effect.void, |
| 2156 | unref: Effect.succeed(Effect.void), |
| 2157 | stdin: Sink.drain, |
| 2158 | stdout: Stream.encodeText(Stream.make(secret)), |
| 2159 | stderr: Stream.encodeText(Stream.make(stderr)), |
| 2160 | all: Stream.empty, |
| 2161 | getInputFd: () => Sink.drain, |
| 2162 | getOutputFd: () => Stream.empty, |
| 2163 | }); |
| 2164 | }), |
| 2165 | ); |
| 2166 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2167 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2168 | ); |
| 2169 | const cwd = yield* makeTmpDir(); |
| 2170 | const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip); |
| 2171 | assert.include(error.detail, scenario.expected); |
| 2172 | assert.equal(error.exitCode, 128); |
| 2173 | assert.equal(error.stderrLength, stderr.length); |
| 2174 | assert.equal(error.stdoutLength, secret.length); |
| 2175 | assert.notInclude(error.message, secret); |
| 2176 | assert.notInclude(yield* encodeGitCommandError(error), secret); |
| 2177 | assert.notProperty(error, "stderr"); |
| 2178 | assert.notProperty(error, "args"); |
| 2179 | assert.equal(yield* Ref.get(attempts), "attempts" in scenario ? scenario.attempts : 1); |
| 2180 | }).pipe( |
| 2181 | Effect.provide( |
| 2182 | layerServerConfig.pipe( |
| 2183 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 2184 | ), |
| 2185 | ), |
| 2186 | ), |
| 2187 | ); |
| 2188 | |
| 2189 | it.effect("retries a fetch that lost a ref update to another Git process", () => |
| 2190 | Effect.gen(function* () { |
| 2191 | const attempts = yield* Ref.make(0); |
| 2192 | const spawner = ChildProcessSpawner.make((command) => |
| 2193 | Effect.gen(function* () { |
| 2194 | if (!ChildProcess.isStandardCommand(command)) |
| 2195 | return yield* Effect.die("expected Git command"); |
| 2196 | if (command.args[0] !== "fetch") return makeNonRepositoryHandle(); |
| 2197 | const attempt = yield* Ref.updateAndGet(attempts, (count) => count + 1); |
| 2198 | if (attempt > 1) return makeSuccessfulHandle(""); |
| 2199 | return ChildProcessSpawner.makeHandle({ |
| 2200 | ...makeNonRepositoryHandle(), |
| 2201 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), |
| 2202 | stderr: Stream.encodeText( |
| 2203 | Stream.make( |
| 2204 | "error: fetching ref refs/remotes/origin/main failed: incorrect old value provided", |
| 2205 | ), |
| 2206 | ), |
| 2207 | }); |
| 2208 | }), |
| 2209 | ); |
| 2210 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2211 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2212 | ); |
| 2213 | const cwd = yield* makeTmpDir(); |
| 2214 | yield* driver.fetchRemote({ cwd, remoteName: "origin", refName: "main" }); |
| 2215 | assert.equal(yield* Ref.get(attempts), 2); |
| 2216 | }).pipe( |
| 2217 | Effect.provide( |
| 2218 | layerServerConfig.pipe( |
| 2219 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 2220 | ), |
| 2221 | ), |
| 2222 | ), |
| 2223 | ); |
| 2224 | |
| 2225 | it.effect("does not fetch for status when the branch tracks a local branch", () => |
| 2226 | Effect.scoped( |
| 2227 | Effect.gen(function* () { |
| 2228 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 2229 | const fetches: Array<ReadonlyArray<string>> = []; |
| 2230 | const spawner = ChildProcessSpawner.make((command) => { |
| 2231 | if (ChildProcess.isStandardCommand(command) && command.args.includes("fetch")) { |
| 2232 | fetches.push(command.args.map(String)); |
| 2233 | } |
| 2234 | return delegate.spawn(command); |
| 2235 | }); |
| 2236 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2237 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2238 | ); |
| 2239 | const cwd = yield* makeTmpDir(); |
| 2240 | const remote = yield* makeTmpDir("git-vcs-driver-remote-"); |
| 2241 | yield* initRepoWithCommit(cwd); |
| 2242 | yield* git(remote, ["init", "--bare"]); |
| 2243 | yield* git(cwd, ["remote", "add", "feature", remote]); |
| 2244 | yield* git(cwd, ["branch", "feature/base"]); |
| 2245 | yield* git(cwd, ["checkout", "-b", "stacked", "--track", "feature/base"]); |
| 2246 | |
| 2247 | const status = yield* driver.statusDetailsRemote(cwd); |
| 2248 | |
| 2249 | assert.equal(status.upstreamRef, "feature/base"); |
| 2250 | assert.deepStrictEqual(fetches, []); |
| 2251 | }), |
| 2252 | ).pipe(Effect.provide(layerTest)), |
| 2253 | ); |
| 2254 | |
| 2255 | it.effect("does not fetch for status when the automatic fetch interval is zero", () => |
| 2256 | Effect.scoped( |
| 2257 | Effect.gen(function* () { |
| 2258 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 2259 | const fetches: Array<ReadonlyArray<string>> = []; |
| 2260 | const spawner = ChildProcessSpawner.make((command) => { |
| 2261 | if (ChildProcess.isStandardCommand(command) && command.args.includes("fetch")) { |
| 2262 | fetches.push(command.args.map(String)); |
| 2263 | } |
| 2264 | return delegate.spawn(command); |
| 2265 | }); |
| 2266 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2267 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2268 | Effect.provideService(VcsAutomaticFetchInterval, Effect.succeed(Duration.zero)), |
| 2269 | ); |
| 2270 | const cwd = yield* makeTmpDir(); |
| 2271 | const remote = yield* makeTmpDir("git-vcs-driver-remote-"); |
| 2272 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 2273 | yield* git(remote, ["init", "--bare"]); |
| 2274 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 2275 | yield* git(cwd, ["push", "--set-upstream", "origin", initialBranch]); |
| 2276 | |
| 2277 | yield* driver.statusDetails(cwd); |
| 2278 | const status = yield* driver.statusDetailsRemote(cwd); |
| 2279 | |
| 2280 | assert.equal(status.upstreamRef, `origin/${initialBranch}`); |
| 2281 | assert.deepStrictEqual(fetches, []); |
| 2282 | }), |
| 2283 | ).pipe(Effect.provide(layerTest)), |
| 2284 | ); |
| 2285 | |
| 2286 | it.effect("lets a worktree checkout that is still working run past five minutes", () => |
| 2287 | Effect.gen(function* () { |
| 2288 | const checkoutStarted = yield* Deferred.make<void>(); |
| 2289 | const checkoutFinished = yield* Deferred.make<void>(); |
| 2290 | const spawner = ChildProcessSpawner.make((command) => |
| 2291 | Effect.gen(function* () { |
| 2292 | if (!ChildProcess.isStandardCommand(command)) |
| 2293 | return yield* Effect.die("expected Git command"); |
| 2294 | if (!command.args.includes("worktree") || command.args.includes("-h")) |
| 2295 | return makeSuccessfulHandle(""); |
| 2296 | yield* Deferred.succeed(checkoutStarted, undefined); |
| 2297 | return ChildProcessSpawner.makeHandle({ |
| 2298 | ...makeSuccessfulHandle(""), |
| 2299 | exitCode: Deferred.await(checkoutFinished).pipe( |
| 2300 | Effect.as(ChildProcessSpawner.ExitCode(0)), |
| 2301 | ), |
| 2302 | stderr: Stream.encodeText( |
| 2303 | Stream.concat( |
| 2304 | Stream.make("Updating files: 40% (49052/122629)\n"), |
| 2305 | Stream.fromEffect( |
| 2306 | Deferred.await(checkoutFinished).pipe( |
| 2307 | Effect.as("Updating files: 100% (122629/122629), done.\n"), |
| 2308 | ), |
| 2309 | ), |
| 2310 | ), |
| 2311 | ), |
| 2312 | }); |
| 2313 | }), |
| 2314 | ); |
| 2315 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2316 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2317 | ); |
| 2318 | const path = yield* Path.Path; |
| 2319 | const cwd = yield* makeTmpDir(); |
| 2320 | const worktreePath = path.join(cwd, "worktree"); |
| 2321 | |
| 2322 | const creation = yield* driver |
| 2323 | .createWorktree({ cwd, refName: "main", newRefName: "t3/slow-checkout", path: worktreePath }) |
| 2324 | .pipe(Effect.forkChild); |
| 2325 | yield* Deferred.await(checkoutStarted); |
| 2326 | yield* TestClock.adjust("6 minutes"); |
| 2327 | yield* Deferred.succeed(checkoutFinished, undefined); |
| 2328 | |
| 2329 | const result = yield* Fiber.join(creation); |
| 2330 | assert.equal(result.worktree.path, worktreePath); |
| 2331 | assert.equal(result.worktree.refName, "t3/slow-checkout"); |
| 2332 | }).pipe( |
| 2333 | Effect.provide( |
| 2334 | layerServerConfig.pipe( |
| 2335 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 2336 | ), |
| 2337 | ), |
| 2338 | ), |
| 2339 | ); |
| 2340 | |
| 2341 | it.effect("cancels a slow submodule checkout without reporting best-effort success", () => |
| 2342 | Effect.gen(function* () { |
| 2343 | const updateStarted = yield* Deferred.make<void>(); |
| 2344 | const updateStopped = yield* Deferred.make<void>(); |
| 2345 | const finished = yield* Ref.make<ReadonlyArray<{ ok: boolean; detail: string | null }>>([]); |
| 2346 | const claimed = yield* Ref.make<string | null>(null); |
| 2347 | const spawner = ChildProcessSpawner.make((command) => { |
| 2348 | if ( |
| 2349 | ChildProcess.isStandardCommand(command) && |
| 2350 | command.args[0] === "submodule" && |
| 2351 | command.args[1] === "update" |
| 2352 | ) { |
| 2353 | return Effect.acquireRelease( |
| 2354 | Effect.succeed( |
| 2355 | ChildProcessSpawner.makeHandle({ |
| 2356 | ...makeSuccessfulHandle(""), |
| 2357 | exitCode: Deferred.succeed(updateStarted, undefined).pipe( |
| 2358 | Effect.andThen(Effect.never), |
| 2359 | ), |
| 2360 | }), |
| 2361 | ), |
| 2362 | () => Deferred.succeed(updateStopped, undefined), |
| 2363 | ); |
| 2364 | } |
| 2365 | return Effect.succeed(makeSuccessfulHandle("")); |
| 2366 | }); |
| 2367 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2368 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2369 | ); |
| 2370 | const cwd = yield* makeTmpDir(); |
| 2371 | const path = yield* Path.Path; |
| 2372 | const worktreePath = path.join(cwd, "worktree"); |
| 2373 | yield* writeTextFile(worktreePath, ".gitmodules", ""); |
| 2374 | const creation = yield* driver |
| 2375 | .createWorktree( |
| 2376 | { cwd, refName: "main", newRefName: "bugfix/cancel-submodules", path: worktreePath }, |
| 2377 | { |
| 2378 | progress: { |
| 2379 | onWorktreeClaimed: (value) => Ref.set(claimed, value), |
| 2380 | onSubmodulesFinished: (result) => Ref.update(finished, (items) => [...items, result]), |
| 2381 | }, |
| 2382 | }, |
| 2383 | ) |
| 2384 | .pipe(Effect.forkChild); |
| 2385 | yield* Deferred.await(updateStarted); |
| 2386 | yield* TestClock.adjust("6 minutes"); |
| 2387 | yield* Fiber.interrupt(creation); |
| 2388 | const exit = yield* Fiber.await(creation); |
| 2389 | assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)); |
| 2390 | assert.isTrue(yield* Deferred.isDone(updateStopped)); |
| 2391 | assert.equal(yield* Ref.get(claimed), worktreePath); |
| 2392 | assert.isEmpty(yield* Ref.get(finished)); |
| 2393 | }).pipe( |
| 2394 | Effect.provide( |
| 2395 | layerServerConfig.pipe( |
| 2396 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 2397 | ), |
| 2398 | ), |
| 2399 | ), |
| 2400 | ); |
| 2401 | |
| 2402 | // regression: #18537 the fetch before creating a worktree outgrew the 30s default |
| 2403 | it.effect.each(["healthy", "hung"] as const)("bounds a %s remote fetch at five minutes", (fetch) => |
| 2404 | Effect.gen(function* () { |
| 2405 | const started = yield* Deferred.make<void>(); |
| 2406 | const finished = yield* Deferred.make<void>(); |
| 2407 | const spawner = ChildProcessSpawner.make((command) => |
| 2408 | Effect.succeed( |
| 2409 | ChildProcess.isStandardCommand(command) && command.args[0] === "fetch" |
| 2410 | ? ChildProcessSpawner.makeHandle({ |
| 2411 | ...makeSuccessfulHandle(""), |
| 2412 | exitCode: Deferred.succeed(started, undefined).pipe( |
| 2413 | Effect.andThen(Deferred.await(finished)), |
| 2414 | Effect.as(ChildProcessSpawner.ExitCode(0)), |
| 2415 | ), |
| 2416 | }) |
| 2417 | : makeNonRepositoryHandle(), |
| 2418 | ), |
| 2419 | ); |
| 2420 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2421 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2422 | ); |
| 2423 | const fetching = yield* driver |
| 2424 | .fetchRemote({ cwd: yield* makeTmpDir(), remoteName: "origin" }) |
| 2425 | .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); |
| 2426 | yield* Deferred.await(started); |
| 2427 | yield* TestClock.adjust("31 seconds"); |
| 2428 | if (fetch === "healthy") yield* Deferred.succeed(finished, undefined); |
| 2429 | else { |
| 2430 | yield* TestClock.adjust("268 seconds"); |
| 2431 | assert.isUndefined(fetching.pollUnsafe()); |
| 2432 | yield* TestClock.adjust("1 second"); |
| 2433 | } |
| 2434 | |
| 2435 | const result = yield* Fiber.join(fetching); |
| 2436 | assert.equal( |
| 2437 | Result.isFailure(result) ? result.failure.detail : "fetched", |
| 2438 | fetch === "healthy" ? "fetched" : "Git command timed out.", |
| 2439 | ); |
| 2440 | }).pipe( |
| 2441 | Effect.provide( |
| 2442 | layerServerConfig.pipe( |
| 2443 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 2444 | ), |
| 2445 | ), |
| 2446 | ), |
| 2447 | ); |
| 2448 | |
| 2449 | describe("rejected git refs", () => { |
| 2450 | const remoteUrl = "https://user:token-123@git.example.invalid/org/secret-repo.git"; |
| 2451 | const failedPush = `error: failed to push some refs to '${remoteUrl}'`; |
| 2452 | const leakedText = [ |
| 2453 | "token-123", |
| 2454 | "secret-repo", |
| 2455 | "git.example.invalid", |
| 2456 | "private-branch", |
| 2457 | "workflow scope", |
| 2458 | ]; |
| 2459 | |
| 2460 | const failWith = (stderr: string) => { |
| 2461 | const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeFailedHandle(stderr))); |
| 2462 | const layer = GitVcsDriver.layer.pipe( |
| 2463 | Layer.provide(layerServerConfig), |
| 2464 | Layer.provideMerge( |
| 2465 | Layer.merge( |
| 2466 | Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), |
| 2467 | Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2468 | ), |
| 2469 | ), |
| 2470 | ); |
| 2471 | return Effect.gen(function* () { |
| 2472 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2473 | return yield* driver |
| 2474 | .execute({ |
| 2475 | operation: "GitVcsDriver.test.rejectedRef", |
| 2476 | cwd: "/repo", |
| 2477 | args: ["push", "origin", "HEAD"], |
| 2478 | }) |
| 2479 | .pipe(Effect.flip); |
| 2480 | }).pipe(Effect.provide(layer)); |
| 2481 | }; |
| 2482 | |
| 2483 | it.effect.each([ |
| 2484 | { |
| 2485 | label: "a ref the remote refused", |
| 2486 | stderr: [ |
| 2487 | "remote: Unable to determine if workflow can be created; workflow scope may be required.", |
| 2488 | `To ${remoteUrl}`, |
| 2489 | " ! [remote rejected] private-branch -> private-branch (workflow scope may be required.)", |
| 2490 | failedPush, |
| 2491 | ], |
| 2492 | reason: "push_rejected_by_remote" as const, |
| 2493 | detail: "The remote rejected the push.", |
| 2494 | }, |
| 2495 | { |
| 2496 | label: "a non-fast-forward push", |
| 2497 | stderr: [ |
| 2498 | `To ${remoteUrl}`, |
| 2499 | " ! [rejected] private-branch -> private-branch (non-fast-forward)", |
| 2500 | failedPush, |
| 2501 | ], |
| 2502 | reason: "push_rejected_non_fast_forward" as const, |
| 2503 | detail: "Pull or rebase", |
| 2504 | }, |
| 2505 | ])("names $label without quoting stderr", ({ stderr, reason, detail }) => |
| 2506 | Effect.gen(function* () { |
| 2507 | const error = yield* failWith(stderr.join("\n")); |
| 2508 | |
| 2509 | assert.deepInclude(error, { reason }); |
| 2510 | assert.include(error.detail, detail); |
| 2511 | for (const text of leakedText) assert.notInclude(error.message, text); |
| 2512 | }), |
| 2513 | ); |
| 2514 | |
| 2515 | // A fetch into a diverged local branch prints the same rejected line, but |
| 2516 | // never "failed to push some refs". |
| 2517 | it.effect("leaves a rejected fetch unclassified", () => |
| 2518 | Effect.gen(function* () { |
| 2519 | const error = yield* failWith( |
| 2520 | [`From ${remoteUrl}`, " ! [rejected] main -> side (non-fast-forward)"].join( |
| 2521 | "\n", |
| 2522 | ), |
| 2523 | ); |
| 2524 | |
| 2525 | assert.equal(error.reason, undefined); |
| 2526 | assert.equal(error.detail, "Git command exited with a non-zero status."); |
| 2527 | }), |
| 2528 | ); |
| 2529 | }); |
| 2530 | |
| 2531 | it.layer(layerTest)("GitVcsDriver core integration", (it) => { |
| 2532 | // regression: #26577 a timed-out git that outlives its timeout holds a process permit |
| 2533 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 2534 | "kills a timed-out git command that ignores SIGTERM", |
| 2535 | () => |
| 2536 | Effect.gen(function* () { |
| 2537 | const cwd = yield* makeTmpDir(); |
| 2538 | yield* initRepoWithCommit(cwd); |
| 2539 | const pathService = yield* Path.Path; |
| 2540 | const fileSystem = yield* FileSystem.FileSystem; |
| 2541 | const markerPath = pathService.join(yield* makeTmpDir(), "outlived-timeout"); |
| 2542 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2543 | const trapped = yield* Deferred.make<void>(); |
| 2544 | |
| 2545 | const command = yield* driver |
| 2546 | .execute({ |
| 2547 | operation: "GitVcsDriver.test.ignoresSigterm", |
| 2548 | cwd, |
| 2549 | args: [ |
| 2550 | "-c", |
| 2551 | `alias.hang=!trap '' TERM; echo trapped; sleep 3; touch '${markerPath}'`, |
| 2552 | "hang", |
| 2553 | ], |
| 2554 | progress: { |
| 2555 | onStdoutLine: (line) => |
| 2556 | line === "trapped" ? Deferred.succeed(trapped, undefined) : Effect.void, |
| 2557 | }, |
| 2558 | }) |
| 2559 | .pipe(Effect.forkChild); |
| 2560 | yield* Deferred.await(trapped); |
| 2561 | // The driver's timeout ends a command the same way: by interrupting it. |
| 2562 | yield* Fiber.interrupt(command); |
| 2563 | |
| 2564 | assert.isFalse( |
| 2565 | yield* fileSystem.exists(markerPath), |
| 2566 | "the timed-out git command kept running until it finished on its own", |
| 2567 | ); |
| 2568 | }), |
| 2569 | ); |
| 2570 | |
| 2571 | it.effect("keeps large change sets available for status and commit preparation", () => |
| 2572 | Effect.gen(function* () { |
| 2573 | const cwd = yield* makeTmpDir(); |
| 2574 | const fs = yield* FileSystem.FileSystem; |
| 2575 | const path = yield* Path.Path; |
| 2576 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2577 | yield* git(cwd, ["init"]); |
| 2578 | yield* git(cwd, ["config", "user.email", "test@test.com"]); |
| 2579 | yield* git(cwd, ["config", "user.name", "Test"]); |
| 2580 | // Selected paths add up to more than Linux's default 2 MiB argument limit. |
| 2581 | const dir = "d".repeat(200); |
| 2582 | yield* fs.makeDirectory(path.join(cwd, dir)); |
| 2583 | const files = Array.from( |
| 2584 | { length: 6_000 }, |
| 2585 | (_, index) => `${dir}/file-${String(index).padStart(5, "0")}-${"x".repeat(160)}.txt`, |
| 2586 | ); |
| 2587 | yield* Effect.forEach(files, (file) => fs.writeFileString(path.join(cwd, file), "before\n"), { |
| 2588 | concurrency: 16, |
| 2589 | discard: true, |
| 2590 | }); |
| 2591 | yield* git(cwd, ["add", "."]); |
| 2592 | const unborn = yield* driver.statusDetailsLocal(cwd); |
| 2593 | assert.lengthOf(unborn.workingTree.files, files.length); |
| 2594 | assert.equal(unborn.workingTree.insertions, files.length); |
| 2595 | const initial = yield* driver.commit(cwd, "initial", ""); |
| 2596 | assert.match(initial.commitSha, /^[a-f0-9]{40}$/); |
| 2597 | assert.isFalse((yield* driver.statusDetailsLocal(cwd)).hasWorkingTreeChanges); |
| 2598 | yield* Effect.forEach(files, (file) => fs.writeFileString(path.join(cwd, file), "after\n"), { |
| 2599 | concurrency: 16, |
| 2600 | discard: true, |
| 2601 | }); |
| 2602 | const status = yield* driver.statusDetailsLocal(cwd); |
| 2603 | assert.isTrue(status.hasWorkingTreeChanges); |
| 2604 | assert.lengthOf(status.workingTree.files, files.length); |
| 2605 | assert.equal(status.workingTree.insertions, files.length); |
| 2606 | assert.equal(status.workingTree.deletions, files.length); |
| 2607 | const context = yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false }); |
| 2608 | assert.isNotNull(context); |
| 2609 | assert.isAbove(context!.stagedSummary.length, 1_000_000); |
| 2610 | assert.lengthOf(context!.stagedSummary.split("\n"), files.length); |
| 2611 | const selected = files.slice(1); |
| 2612 | yield* driver.commit(cwd, "selected", "", { stage: { filePaths: selected } }); |
| 2613 | assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "selected"); |
| 2614 | assert.equal(yield* git(cwd, ["status", "--porcelain"]), `M ${files[0]}`); |
| 2615 | }), |
| 2616 | ); |
| 2617 | describe("structured errors", () => { |
| 2618 | it.effect("does not retain git arguments or stderr in command failures", () => |
| 2619 | Effect.gen(function* () { |
| 2620 | const cwd = yield* makeTmpDir(); |
| 2621 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2622 | yield* driver.initRepo({ cwd }); |
| 2623 | |
| 2624 | const secret = "secret-token-value"; |
| 2625 | const error = yield* driver |
| 2626 | .execute({ |
| 2627 | operation: "GitVcsDriver.test.redactedFailure", |
| 2628 | cwd, |
| 2629 | args: ["status", `--unknown-option=${secret}`], |
| 2630 | }) |
| 2631 | .pipe(Effect.flip); |
| 2632 | |
| 2633 | assert.deepInclude(error, { |
| 2634 | _tag: "GitCommandError", |
| 2635 | operation: "GitVcsDriver.test.redactedFailure", |
| 2636 | command: "git", |
| 2637 | argumentCount: 2, |
| 2638 | cwd, |
| 2639 | }); |
| 2640 | assert.isNumber(error.exitCode); |
| 2641 | assert.isAbove(error.stderrLength ?? 0, 0); |
| 2642 | assert.notInclude(error.detail, secret); |
| 2643 | assert.notInclude(error.message, secret); |
| 2644 | assert.notProperty(error, "args"); |
| 2645 | assert.notProperty(error, "stderr"); |
| 2646 | assert.notProperty(error, "reason"); |
| 2647 | }), |
| 2648 | ); |
| 2649 | |
| 2650 | it.effect("fails with a GitCommandError when spawn throws", () => |
| 2651 | Effect.gen(function* () { |
| 2652 | const cwd = yield* makeTmpDir(); |
| 2653 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2654 | |
| 2655 | // Over the OS argument limit, Node's spawn throws E2BIG synchronously. |
| 2656 | const error = yield* driver |
| 2657 | .execute({ |
| 2658 | operation: "GitVcsDriver.test.spawnThrow", |
| 2659 | cwd, |
| 2660 | args: ["status", "x".repeat(4 * 1024 * 1024)], |
| 2661 | }) |
| 2662 | .pipe(Effect.flip); |
| 2663 | |
| 2664 | assert.deepInclude(error, { |
| 2665 | _tag: "GitCommandError", |
| 2666 | operation: "GitVcsDriver.test.spawnThrow", |
| 2667 | detail: "Failed to spawn Git process.", |
| 2668 | }); |
| 2669 | }), |
| 2670 | ); |
| 2671 | |
| 2672 | // regression: #8645 name the cause of a failed git command |
| 2673 | it.effect("names the branch conflict behind a failed worktree add", () => |
| 2674 | Effect.gen(function* () { |
| 2675 | const parent = yield* makeTmpDir(); |
| 2676 | const pathService = yield* Path.Path; |
| 2677 | const cwd = pathService.join(parent, "repo"); |
| 2678 | const fileSystem = yield* FileSystem.FileSystem; |
| 2679 | yield* fileSystem.makeDirectory(cwd); |
| 2680 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2681 | yield* initRepoWithCommit(cwd); |
| 2682 | const firstWorktree = pathService.join(parent, "first"); |
| 2683 | yield* git(cwd, ["worktree", "add", firstWorktree, "-b", "shared-branch"]); |
| 2684 | |
| 2685 | const error = yield* driver |
| 2686 | .execute({ |
| 2687 | operation: "GitVcsDriver.test.worktreeAddConflict", |
| 2688 | cwd, |
| 2689 | args: ["worktree", "add", pathService.join(parent, "second"), "shared-branch"], |
| 2690 | env: { LC_ALL: "C" }, |
| 2691 | }) |
| 2692 | .pipe(Effect.flip); |
| 2693 | |
| 2694 | assert.deepInclude(error, { |
| 2695 | _tag: "GitCommandError", |
| 2696 | operation: "GitVcsDriver.test.worktreeAddConflict", |
| 2697 | reason: "branch_checked_out_in_worktree", |
| 2698 | }); |
| 2699 | assert.include(error.message, "(branch_checked_out_in_worktree)"); |
| 2700 | assert.notInclude(error.message, firstWorktree); |
| 2701 | }), |
| 2702 | ); |
| 2703 | |
| 2704 | // regression: #8645 name the cause of a failed git command |
| 2705 | it.effect("names a missing repository behind a failed command", () => |
| 2706 | Effect.gen(function* () { |
| 2707 | const cwd = yield* makeTmpDir(); |
| 2708 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2709 | |
| 2710 | const error = yield* driver |
| 2711 | .execute({ |
| 2712 | operation: "GitVcsDriver.test.notARepository", |
| 2713 | cwd, |
| 2714 | args: ["rev-parse", "--abbrev-ref", "HEAD"], |
| 2715 | env: { LC_ALL: "C" }, |
| 2716 | }) |
| 2717 | .pipe(Effect.flip); |
| 2718 | |
| 2719 | assert.deepInclude(error, { |
| 2720 | _tag: "GitCommandError", |
| 2721 | operation: "GitVcsDriver.test.notARepository", |
| 2722 | reason: "not_a_repository", |
| 2723 | }); |
| 2724 | assert.include(error.message, "(not_a_repository)"); |
| 2725 | }), |
| 2726 | ); |
| 2727 | |
| 2728 | it.effect.each([ |
| 2729 | { action: "worktree add", detail: "git worktree add failed" }, |
| 2730 | { action: "worktree add -b", detail: "git branch failed" }, |
| 2731 | { action: "switch", detail: "git checkout failed" }, |
| 2732 | ])( |
| 2733 | "reports a missing ref during $action with stable, redacted diagnostics", |
| 2734 | ({ action, detail }) => |
| 2735 | Effect.gen(function* () { |
| 2736 | const cwd = yield* makeTmpDir(); |
| 2737 | yield* initRepoWithCommit(cwd); |
| 2738 | const path = yield* Path.Path; |
| 2739 | const refName = "private/deleted-base"; |
| 2740 | const locales: Array<CommandLine.Word | undefined> = []; |
| 2741 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 2742 | const spawner = ChildProcessSpawner.make((command) => { |
| 2743 | if ( |
| 2744 | ChildProcess.isStandardCommand(command) && |
| 2745 | !command.args.includes("-h") && |
| 2746 | (command.args.includes("worktree") || |
| 2747 | command.args[0] === "branch" || |
| 2748 | command.args[0] === "checkout") |
| 2749 | ) { |
| 2750 | locales.push(command.options.env?.LANGUAGE); |
| 2751 | } |
| 2752 | return delegate.spawn(command); |
| 2753 | }); |
| 2754 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2755 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2756 | Effect.provide(layerServerConfig), |
| 2757 | ); |
| 2758 | const error = |
| 2759 | action === "switch" |
| 2760 | ? yield* driver.switchRef({ cwd, refName }).pipe(Effect.flip) |
| 2761 | : yield* driver |
| 2762 | .createWorktree({ |
| 2763 | cwd, |
| 2764 | refName, |
| 2765 | ...(action === "worktree add -b" ? { newRefName: "t3/new-thread" } : {}), |
| 2766 | path: path.join(cwd, "worktree"), |
| 2767 | }) |
| 2768 | .pipe(Effect.flip); |
| 2769 | |
| 2770 | assert.deepInclude(error, { _tag: "GitCommandError", detail, reason: "ref_not_found" }); |
| 2771 | assert.include(error.message, `${detail} (ref_not_found)`); |
| 2772 | assert.notInclude(error.message, refName); |
| 2773 | assert.notInclude(yield* encodeGitCommandError(error), refName); |
| 2774 | assert.deepEqual(locales, ["C"]); |
| 2775 | assert.notProperty(error, "stderr"); |
| 2776 | assert.notProperty(error, "args"); |
| 2777 | }), |
| 2778 | ); |
| 2779 | |
| 2780 | it.effect("explains a non-fast-forward push from a host with a translated Git", () => |
| 2781 | Effect.gen(function* () { |
| 2782 | const cwd = yield* makeTmpDir(); |
| 2783 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 2784 | const remote = yield* makeTmpDir("git-remote-"); |
| 2785 | const other = yield* makeTmpDir("git-other-"); |
| 2786 | yield* git(remote, ["init", "--bare"]); |
| 2787 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 2788 | yield* git(cwd, ["push", "--set-upstream", "origin", initialBranch]); |
| 2789 | yield* git(other, ["clone", "--branch", initialBranch, remote, "."]); |
| 2790 | yield* git(other, [ |
| 2791 | "-c", |
| 2792 | "user.email=t@t", |
| 2793 | "-c", |
| 2794 | "user.name=T", |
| 2795 | "commit", |
| 2796 | "--allow-empty", |
| 2797 | "-m", |
| 2798 | "remote", |
| 2799 | ]); |
| 2800 | yield* git(other, ["push", "origin", initialBranch]); |
| 2801 | yield* git(cwd, ["commit", "--allow-empty", "-m", "local"]); |
| 2802 | const locales: Array<CommandLine.Word | undefined> = []; |
| 2803 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 2804 | const spawner = ChildProcessSpawner.make((command) => { |
| 2805 | if (ChildProcess.isStandardCommand(command) && command.args.includes("push")) { |
| 2806 | locales.push(command.options.env?.LANGUAGE); |
| 2807 | } |
| 2808 | return delegate.spawn(command); |
| 2809 | }); |
| 2810 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2811 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2812 | Effect.provide(layerServerConfig), |
| 2813 | ); |
| 2814 | const hostEnv = yield* HostProcess.Environment; |
| 2815 | |
| 2816 | const error = yield* driver |
| 2817 | .pushCurrentBranch(cwd, null) |
| 2818 | .pipe( |
| 2819 | Effect.provideService(HostProcess.Environment, { ...hostEnv, LANGUAGE: "de" }), |
| 2820 | Effect.flip, |
| 2821 | ); |
| 2822 | |
| 2823 | assert.equal(error.reason, "push_rejected_non_fast_forward"); |
| 2824 | assert.isNotEmpty(locales); |
| 2825 | for (const locale of locales) assert.equal(locale, "C"); |
| 2826 | }), |
| 2827 | ); |
| 2828 | |
| 2829 | it.effect("lets a slow remote branch checkout finish without blocking config writes", () => |
| 2830 | Effect.gen(function* () { |
| 2831 | const cwd = yield* makeTmpDir(); |
| 2832 | yield* initRepoWithCommit(cwd); |
| 2833 | const remote = yield* makeTmpDir("git-remote-"); |
| 2834 | yield* git(remote, ["init", "--bare"]); |
| 2835 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 2836 | yield* git(cwd, ["push", "origin", "HEAD:refs/heads/feature"]); |
| 2837 | yield* git(cwd, ["fetch", "origin"]); |
| 2838 | const checkoutStarted = yield* Deferred.make<void>(); |
| 2839 | const releaseCheckout = yield* Deferred.make<void>(); |
| 2840 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 2841 | // Holds the real checkout open like a slow LFS smudge filter would. |
| 2842 | const spawner = ChildProcessSpawner.make((command) => |
| 2843 | Effect.gen(function* () { |
| 2844 | const handle = yield* delegate.spawn(command); |
| 2845 | if (!ChildProcess.isStandardCommand(command) || command.args[0] !== "checkout") { |
| 2846 | return handle; |
| 2847 | } |
| 2848 | yield* Deferred.succeed(checkoutStarted, undefined); |
| 2849 | return ChildProcessSpawner.makeHandle({ |
| 2850 | ...handle, |
| 2851 | exitCode: Deferred.await(releaseCheckout).pipe(Effect.andThen(handle.exitCode)), |
| 2852 | }); |
| 2853 | }), |
| 2854 | ); |
| 2855 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 2856 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 2857 | Effect.provide(layerServerConfig), |
| 2858 | ); |
| 2859 | |
| 2860 | const switching = yield* driver |
| 2861 | .switchRef({ cwd, refName: "origin/feature" }) |
| 2862 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 2863 | yield* Deferred.await(checkoutStarted); |
| 2864 | yield* TestClock.adjust("60 seconds"); |
| 2865 | yield* driver.createRef({ cwd, refName: "other" }); |
| 2866 | yield* Deferred.succeed(releaseCheckout, undefined); |
| 2867 | |
| 2868 | const result = yield* Fiber.join(switching); |
| 2869 | assert.equal(result.refName, "feature"); |
| 2870 | assert.equal( |
| 2871 | yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature@{upstream}"]), |
| 2872 | "origin/feature", |
| 2873 | ); |
| 2874 | }), |
| 2875 | ); |
| 2876 | |
| 2877 | it.effect( |
| 2878 | "switches a remote ref to its tracking branch when a tag shares the branch name", |
| 2879 | () => |
| 2880 | Effect.gen(function* () { |
| 2881 | const cwd = yield* makeTmpDir(); |
| 2882 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 2883 | const remote = yield* makeTmpDir("git-remote-"); |
| 2884 | yield* git(remote, ["init", "--bare"]); |
| 2885 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 2886 | yield* git(cwd, ["push", "origin", "HEAD:refs/heads/v1.2"]); |
| 2887 | yield* git(cwd, ["fetch", "origin"]); |
| 2888 | yield* git(cwd, ["branch", "--track", "v1.2", "origin/v1.2"]); |
| 2889 | yield* git(cwd, ["tag", "v1.2"]); |
| 2890 | assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); |
| 2891 | |
| 2892 | const result = yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({ |
| 2893 | cwd, |
| 2894 | refName: "origin/v1.2", |
| 2895 | }); |
| 2896 | |
| 2897 | assert.equal(result.refName, "v1.2"); |
| 2898 | assert.equal(yield* git(cwd, ["symbolic-ref", "HEAD"]), "refs/heads/v1.2"); |
| 2899 | }), |
| 2900 | ); |
| 2901 | |
| 2902 | it.effect.each([ |
| 2903 | // Git cannot tell a missing revision from a missing file in these. |
| 2904 | { label: "an argument that may be a path", args: ["log", "-1", "missing"] }, |
| 2905 | { |
| 2906 | label: "a pathspec worded like a diagnostic", |
| 2907 | args: ["checkout", "HEAD", "--", "fatal: invalid reference: missing"], |
| 2908 | }, |
| 2909 | // The tag exists; it names a tree, which git reports in the same words. |
| 2910 | { |
| 2911 | label: "a worktree from a non-commit", |
| 2912 | args: ["worktree", "add", "tree-worktree", "tree-tag"], |
| 2913 | }, |
| 2914 | ])("leaves $label unclassified rather than calling it a missing ref", ({ args }) => |
| 2915 | Effect.gen(function* () { |
| 2916 | const cwd = yield* makeTmpDir(); |
| 2917 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2918 | yield* initRepoWithCommit(cwd); |
| 2919 | if (args.includes("tree-tag")) { |
| 2920 | yield* git(cwd, ["tag", "tree-tag", "HEAD^{tree}"]); |
| 2921 | } |
| 2922 | |
| 2923 | const error = yield* driver |
| 2924 | .execute({ |
| 2925 | operation: "GitVcsDriver.test.ambiguousMissingName", |
| 2926 | cwd, |
| 2927 | args, |
| 2928 | env: { LC_ALL: "C" }, |
| 2929 | }) |
| 2930 | .pipe(Effect.flip); |
| 2931 | |
| 2932 | assert.notProperty(error, "reason"); |
| 2933 | }), |
| 2934 | ); |
| 2935 | |
| 2936 | it.effect.each([ |
| 2937 | { |
| 2938 | label: "a refused key", |
| 2939 | sshMessage: "git@example.invalid: Permission denied (publickey).", |
| 2940 | expectedReason: "authentication_failed" as const, |
| 2941 | expectedText: "(authentication_failed)", |
| 2942 | }, |
| 2943 | { |
| 2944 | label: "a refused key among several methods", |
| 2945 | sshMessage: "git@example.invalid: Permission denied (publickey,password).", |
| 2946 | expectedReason: "authentication_failed" as const, |
| 2947 | expectedText: "(authentication_failed)", |
| 2948 | }, |
| 2949 | { |
| 2950 | label: "a refused keyboard-interactive attempt", |
| 2951 | sshMessage: "git@example.invalid: Permission denied (keyboard-interactive).", |
| 2952 | expectedReason: "authentication_failed" as const, |
| 2953 | expectedText: "(authentication_failed)", |
| 2954 | }, |
| 2955 | { |
| 2956 | label: "a rejected password", |
| 2957 | sshMessage: "Permission denied, please try again.", |
| 2958 | expectedReason: "authentication_failed" as const, |
| 2959 | expectedText: "(authentication_failed)", |
| 2960 | }, |
| 2961 | { |
| 2962 | label: "an untrusted host key", |
| 2963 | sshMessage: "Host key verification failed.", |
| 2964 | expectedReason: "host_key_unverified" as const, |
| 2965 | expectedText: "(host_key_unverified)", |
| 2966 | }, |
| 2967 | ])( |
| 2968 | "names $label rather than an unreachable remote", |
| 2969 | ({ sshMessage, expectedReason, expectedText }) => |
| 2970 | Effect.gen(function* () { |
| 2971 | const parent = yield* makeTmpDir(); |
| 2972 | const pathService = yield* Path.Path; |
| 2973 | const cwd = pathService.join(parent, "repo"); |
| 2974 | const fileSystem = yield* FileSystem.FileSystem; |
| 2975 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 2976 | yield* fileSystem.makeDirectory(cwd); |
| 2977 | yield* initRepoWithCommit(cwd); |
| 2978 | yield* git(cwd, ["remote", "add", "origin", "git@example.invalid:owner/repo.git"]); |
| 2979 | const fakeSsh = pathService.join(parent, "fake-ssh"); |
| 2980 | yield* writeTextFile( |
| 2981 | parent, |
| 2982 | "fake-ssh", |
| 2983 | `#!/bin/sh\necho "${sshMessage}" >&2\nexit 255\n`, |
| 2984 | ); |
| 2985 | yield* fileSystem.chmod(fakeSsh, 0o755); |
| 2986 | |
| 2987 | const error = yield* driver |
| 2988 | .execute({ |
| 2989 | operation: "GitVcsDriver.test.sshRefusal", |
| 2990 | cwd, |
| 2991 | args: ["fetch", "origin"], |
| 2992 | env: { LC_ALL: "C", GIT_SSH_COMMAND: fakeSsh }, |
| 2993 | }) |
| 2994 | .pipe(Effect.flip); |
| 2995 | |
| 2996 | assert.deepInclude(error, { reason: expectedReason }); |
| 2997 | assert.include(error.message, expectedText); |
| 2998 | }), |
| 2999 | ); |
| 3000 | |
| 3001 | it.effect("does not read a filesystem permission error as an ssh refusal", () => |
| 3002 | Effect.gen(function* () { |
| 3003 | const parent = yield* makeTmpDir(); |
| 3004 | const pathService = yield* Path.Path; |
| 3005 | const cwd = pathService.join(parent, "repo"); |
| 3006 | const fileSystem = yield* FileSystem.FileSystem; |
| 3007 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3008 | yield* fileSystem.makeDirectory(cwd); |
| 3009 | yield* initRepoWithCommit(cwd); |
| 3010 | yield* git(cwd, ["remote", "add", "origin", "git@example.invalid:owner/repo.git"]); |
| 3011 | const fakeSsh = pathService.join(parent, "fake-ssh"); |
| 3012 | yield* writeTextFile( |
| 3013 | parent, |
| 3014 | "fake-ssh", |
| 3015 | '#!/bin/sh\necho "fatal: cannot open backup file: Permission denied (os error 13)" >&2\nexit 255\n', |
| 3016 | ); |
| 3017 | yield* fileSystem.chmod(fakeSsh, 0o755); |
| 3018 | |
| 3019 | const error = yield* driver |
| 3020 | .execute({ |
| 3021 | operation: "GitVcsDriver.test.osPermission", |
| 3022 | cwd, |
| 3023 | args: ["fetch", "origin"], |
| 3024 | env: { LC_ALL: "C", GIT_SSH_COMMAND: fakeSsh }, |
| 3025 | }) |
| 3026 | .pipe(Effect.flip); |
| 3027 | |
| 3028 | assert.notInclude(error.message, "(authentication_failed)"); |
| 3029 | }), |
| 3030 | ); |
| 3031 | |
| 3032 | it.effect("reads a hook-declined push from git's rejection line, not the hook's output", () => |
| 3033 | Effect.gen(function* () { |
| 3034 | const parent = yield* makeTmpDir(); |
| 3035 | const pathService = yield* Path.Path; |
| 3036 | const remote = pathService.join(parent, "origin.git"); |
| 3037 | const cwd = pathService.join(parent, "work"); |
| 3038 | const fileSystem = yield* FileSystem.FileSystem; |
| 3039 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3040 | yield* fileSystem.makeDirectory(cwd); |
| 3041 | yield* initRepoWithCommit(cwd); |
| 3042 | yield* git(cwd, ["init", "--bare", remote]); |
| 3043 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 3044 | const preReceive = pathService.join(remote, "hooks", "pre-receive"); |
| 3045 | yield* writeTextFile( |
| 3046 | remote, |
| 3047 | "hooks/pre-receive", |
| 3048 | '#!/bin/sh\necho "authentication failed" >&2\necho "Permission denied (publickey)." >&2\necho "Host key verification failed." >&2\nexit 1\n', |
| 3049 | ); |
| 3050 | yield* fileSystem.chmod(preReceive, 0o755); |
| 3051 | |
| 3052 | const error = yield* driver |
| 3053 | .execute({ |
| 3054 | operation: "GitVcsDriver.test.remoteHookOutput", |
| 3055 | cwd, |
| 3056 | args: ["push", "origin", "HEAD"], |
| 3057 | env: { LC_ALL: "C" }, |
| 3058 | }) |
| 3059 | .pipe(Effect.flip); |
| 3060 | |
| 3061 | assert.deepInclude(error, { reason: "push_rejected_by_remote" }); |
| 3062 | assert.notInclude(error.message, "(authentication_failed)"); |
| 3063 | }), |
| 3064 | ); |
| 3065 | |
| 3066 | it.effect("leaves a tag collision unclassified rather than calling it a path", () => |
| 3067 | Effect.gen(function* () { |
| 3068 | const cwd = yield* makeTmpDir(); |
| 3069 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3070 | yield* initRepoWithCommit(cwd); |
| 3071 | yield* git(cwd, ["tag", "v1"]); |
| 3072 | |
| 3073 | const error = yield* driver |
| 3074 | .execute({ |
| 3075 | operation: "GitVcsDriver.test.tagCollision", |
| 3076 | cwd, |
| 3077 | args: ["tag", "v1"], |
| 3078 | env: { LC_ALL: "C" }, |
| 3079 | }) |
| 3080 | .pipe(Effect.flip); |
| 3081 | |
| 3082 | assert.notProperty(error, "reason"); |
| 3083 | assert.notInclude(error.message, "(path_already_exists)"); |
| 3084 | }), |
| 3085 | ); |
| 3086 | |
| 3087 | it.effect("keeps line callbacks flowing past the output cap when asked", () => |
| 3088 | Effect.gen(function* () { |
| 3089 | const cwd = yield* makeTmpDir(); |
| 3090 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3091 | const lines: Array<string> = []; |
| 3092 | const result = yield* driver.execute({ |
| 3093 | operation: "GitVcsDriver.test.callbacksPastCap", |
| 3094 | cwd, |
| 3095 | args: [ |
| 3096 | "-c", |
| 3097 | 'alias.spew=!for i in $(seq 1 128); do printf "é%03d\\n" $i >&2; done; echo fatal: last line >&2', |
| 3098 | "spew", |
| 3099 | ], |
| 3100 | maxOutputBytes: 512, |
| 3101 | appendTruncationMarker: true, |
| 3102 | keepLineCallbacksAfterTruncation: true, |
| 3103 | progress: { onStderrLine: (line) => Effect.sync(() => void lines.push(line)) }, |
| 3104 | }); |
| 3105 | |
| 3106 | assert.isTrue(result.stderrTruncated); |
| 3107 | assert.isAtMost(result.stderr.length, 600); |
| 3108 | assert.equal(lines.length, 129); |
| 3109 | assert.equal(lines[0], "é001"); |
| 3110 | assert.equal(lines[127], "é128"); |
| 3111 | assert.equal(lines.at(-1), "fatal: last line"); |
| 3112 | assert.isFalse(lines.some((line) => line.includes("\uFFFD"))); |
| 3113 | }), |
| 3114 | ); |
| 3115 | |
| 3116 | it.effect("recovers a structurally identified missing cwd as a non-repository", () => |
| 3117 | Effect.gen(function* () { |
| 3118 | const parent = yield* makeTmpDir(); |
| 3119 | const pathService = yield* Path.Path; |
| 3120 | const cwd = pathService.join(parent, "missing"); |
| 3121 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3122 | |
| 3123 | const [localStatus, remoteStatus, refs] = yield* Effect.all([ |
| 3124 | driver.statusDetails(cwd), |
| 3125 | driver.statusDetailsRemote(cwd, { refreshUpstream: false }), |
| 3126 | driver.listRefs({ cwd }), |
| 3127 | ]); |
| 3128 | |
| 3129 | assert.equal(localStatus.isRepo, false); |
| 3130 | assert.equal(remoteStatus.isRepo, false); |
| 3131 | assert.equal(refs.isRepo, false); |
| 3132 | assert.deepStrictEqual(refs.refs, []); |
| 3133 | }), |
| 3134 | ); |
| 3135 | }); |
| 3136 | |
| 3137 | describe("review diff previews", () => { |
| 3138 | it.effect("diffs a root commit against the empty tree but rejects a shallow boundary", () => |
| 3139 | Effect.gen(function* () { |
| 3140 | const upstream = yield* makeTmpDir(); |
| 3141 | yield* initRepoWithCommit(upstream); |
| 3142 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3143 | // Git for Windows rejects the null device as a path, so use an empty file. |
| 3144 | const emptyDir = yield* makeTmpDir("git-vcs-driver-empty-"); |
| 3145 | yield* writeTextFile(emptyDir, "empty", ""); |
| 3146 | const emptyFile = NodePath.join(emptyDir, "empty"); |
| 3147 | const emptyTree = yield* git(upstream, ["hash-object", "-t", "tree", emptyFile]); |
| 3148 | const root = yield* git(upstream, ["rev-parse", "HEAD"]); |
| 3149 | const rootSource = (yield* driver.getReviewDiffPreview({ cwd: upstream, commitSha: root })) |
| 3150 | .sources[0]!; |
| 3151 | assert.equal(rootSource.baseRef, emptyTree); |
| 3152 | assert.include(rootSource.diff, "+# test"); |
| 3153 | const rootMetadata = (yield* driver.getReviewDiffPreview({ |
| 3154 | cwd: upstream, |
| 3155 | commitSha: root, |
| 3156 | metadataOnly: true, |
| 3157 | })).sources[0]!; |
| 3158 | assert.deepStrictEqual(rootMetadata.files, rootSource.files); |
| 3159 | assert.isTrue(rootMetadata.patchesDeferred); |
| 3160 | assert.isEmpty(rootMetadata.diff); |
| 3161 | |
| 3162 | yield* writeTextFile(upstream, "README.md", "# boundary\n"); |
| 3163 | yield* git(upstream, ["commit", "-am", "boundary"]); |
| 3164 | const sha = yield* git(upstream, ["rev-parse", "HEAD"]); |
| 3165 | const cwd = yield* makeTmpDir(); |
| 3166 | yield* git(upstream, ["clone", "--depth=1", NodeURL.pathToFileURL(upstream).href, cwd], { |
| 3167 | GIT_CONFIG_GLOBAL: emptyFile, |
| 3168 | GIT_CONFIG_NOSYSTEM: "1", |
| 3169 | }); |
| 3170 | assert.equal(yield* git(cwd, ["rev-parse", "--is-shallow-repository"]), "true"); |
| 3171 | for (const request of [ |
| 3172 | driver.getReviewDiffPreview({ cwd, commitSha: sha }), |
| 3173 | driver.getReviewDiffFileContents( |
| 3174 | makeReviewDiffFileContentsInput(cwd, { |
| 3175 | sourceKind: "commit", |
| 3176 | changeType: "new", |
| 3177 | headRef: sha, |
| 3178 | baseRef: emptyTree, |
| 3179 | }), |
| 3180 | ), |
| 3181 | ]) { |
| 3182 | const error = yield* Effect.asVoid<unknown, GitCommandError, never>(request).pipe( |
| 3183 | Effect.flip, |
| 3184 | ); |
| 3185 | assert.include(error.detail, "parent"); |
| 3186 | } |
| 3187 | }), |
| 3188 | ); |
| 3189 | |
| 3190 | it.effect("lists the branch's commits newest first, at most 100, and flags the rest", () => |
| 3191 | Effect.gen(function* () { |
| 3192 | const cwd = yield* makeTmpDir(); |
| 3193 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 3194 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3195 | yield* git(cwd, ["checkout", "-b", "feature/commits"]); |
| 3196 | const parent = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 3197 | yield* gitWithStdin( |
| 3198 | cwd, |
| 3199 | ["fast-import", "--quiet"], |
| 3200 | Array.from({ length: 102 }, (_, index) => { |
| 3201 | const message = `feature ${index}`; |
| 3202 | return [ |
| 3203 | "commit refs/heads/feature/commits", |
| 3204 | `committer Test <test@test.com> ${1_700_000_000 + index} +0000`, |
| 3205 | `data ${Buffer.byteLength(message)}`, |
| 3206 | message, |
| 3207 | ...(index === 0 ? [`from ${parent}`] : []), |
| 3208 | "", |
| 3209 | ].join("\n"); |
| 3210 | }).join(""), |
| 3211 | ); |
| 3212 | |
| 3213 | const result = yield* driver.getReviewBranchCommits({ cwd, baseRef: initialBranch }); |
| 3214 | assert.strictEqual(result.truncated, true); |
| 3215 | assert.strictEqual(result.commits.length, 100); |
| 3216 | assert.strictEqual(result.commits[0]?.sha, yield* git(cwd, ["rev-parse", "HEAD"])); |
| 3217 | assert.deepStrictEqual( |
| 3218 | [result.commits[0]?.subject, result.commits[99]?.subject], |
| 3219 | ["feature 101", "feature 2"], |
| 3220 | ); |
| 3221 | }), |
| 3222 | ); |
| 3223 | |
| 3224 | it.effect("previews one selected commit, a merge against its first parent", () => |
| 3225 | Effect.gen(function* () { |
| 3226 | const cwd = yield* makeTmpDir(); |
| 3227 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 3228 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3229 | yield* git(cwd, ["checkout", "-b", "feature/merge-preview"]); |
| 3230 | yield* git(cwd, ["checkout", "-b", "feature/side"]); |
| 3231 | yield* writeTextFile(cwd, "README.md", "# side commit\n"); |
| 3232 | yield* git(cwd, ["add", "README.md"]); |
| 3233 | yield* git(cwd, ["commit", "-m", "side change"]); |
| 3234 | yield* git(cwd, ["checkout", "feature/merge-preview"]); |
| 3235 | yield* writeTextFile(cwd, "feature.txt", "feature commit\n"); |
| 3236 | yield* git(cwd, ["add", "feature.txt"]); |
| 3237 | yield* git(cwd, ["commit", "-m", "feature change"]); |
| 3238 | const firstParent = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 3239 | yield* git(cwd, ["merge", "--no-ff", "--no-edit", "feature/side"]); |
| 3240 | const mergeSha = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 3241 | yield* git(cwd, ["checkout", "-b", "feature/elsewhere", initialBranch]); |
| 3242 | yield* writeTextFile(cwd, "elsewhere.txt", "elsewhere\n"); |
| 3243 | yield* git(cwd, ["add", "elsewhere.txt"]); |
| 3244 | yield* git(cwd, ["commit", "-m", "elsewhere change"]); |
| 3245 | const elsewhereSha = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 3246 | yield* git(cwd, ["checkout", "feature/merge-preview"]); |
| 3247 | yield* writeTextFile(cwd, "README.md", "# dirty tree\n"); |
| 3248 | |
| 3249 | const elsewhere = yield* driver.getReviewDiffPreview({ cwd, commitSha: elsewhereSha }); |
| 3250 | assert.deepStrictEqual( |
| 3251 | elsewhere.sources |
| 3252 | .find((candidate) => candidate.kind === "commit") |
| 3253 | ?.files?.map((file) => file.path), |
| 3254 | ["elsewhere.txt"], |
| 3255 | ); |
| 3256 | |
| 3257 | const preview = yield* driver.getReviewDiffPreview({ |
| 3258 | cwd, |
| 3259 | baseRef: initialBranch, |
| 3260 | commitSha: mergeSha, |
| 3261 | }); |
| 3262 | const source = preview.sources.find((candidate) => candidate.kind === "commit")!; |
| 3263 | assert.strictEqual(source.baseRef, firstParent); |
| 3264 | assert.strictEqual(source.headRef, mergeSha); |
| 3265 | assert.deepStrictEqual( |
| 3266 | source.files?.map((file) => file.path), |
| 3267 | ["README.md"], |
| 3268 | ); |
| 3269 | assert.include(source.diff, "+# side commit"); |
| 3270 | assert.notInclude(source.diff, "dirty tree"); |
| 3271 | assert.notInclude(source.diff, "feature.txt"); |
| 3272 | |
| 3273 | const patch = yield* driver.getReviewDiffPreview({ |
| 3274 | cwd, |
| 3275 | baseRef: initialBranch, |
| 3276 | commitSha: mergeSha, |
| 3277 | file: { path: "README.md", previousPath: null, sourceKind: "commit" }, |
| 3278 | }); |
| 3279 | assert.include( |
| 3280 | patch.sources.find((candidate) => candidate.kind === "commit")!.diff, |
| 3281 | "+# side commit", |
| 3282 | ); |
| 3283 | const contents = yield* driver.getReviewDiffFileContents( |
| 3284 | makeReviewDiffFileContentsInput(cwd, { |
| 3285 | sourceKind: "commit", |
| 3286 | baseRef: source.baseRef, |
| 3287 | headRef: source.headRef, |
| 3288 | }), |
| 3289 | ); |
| 3290 | assert.deepStrictEqual(contents, { |
| 3291 | oldContents: "# test\n", |
| 3292 | newContents: "# side commit\n", |
| 3293 | }); |
| 3294 | }), |
| 3295 | ); |
| 3296 | |
| 3297 | it.effect("loads repository-relative files from nested directories and aliases", () => |
| 3298 | Effect.gen(function* () { |
| 3299 | const directory = yield* makeTmpDir(); |
| 3300 | const path = yield* Path.Path; |
| 3301 | const fileSystem = yield* FileSystem.FileSystem; |
| 3302 | const platform = yield* HostProcess.Platform; |
| 3303 | const cwd = path.join(directory, platform === "win32" ? "repository" : "repository\n "); |
| 3304 | yield* fileSystem.makeDirectory(cwd); |
| 3305 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 3306 | yield* git(cwd, ["checkout", "-b", "feature/nested"]); |
| 3307 | yield* writeTextFile(cwd, "nested/tracked.txt", "committed\n"); |
| 3308 | yield* git(cwd, ["add", "."]); |
| 3309 | yield* git(cwd, ["commit", "-m", "nested file"]); |
| 3310 | yield* writeTextFile(cwd, "nested/tracked.txt", "changed\n"); |
| 3311 | yield* writeTextFile(cwd, "untracked.txt", "new\n"); |
| 3312 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3313 | const nestedCwd = path.join(cwd, "nested"); |
| 3314 | const clone = path.join(nestedCwd, "clone"); |
| 3315 | yield* fileSystem.makeDirectory(clone); |
| 3316 | yield* initRepoWithCommit(clone); |
| 3317 | const projectDirectories = [nestedCwd]; |
| 3318 | if (symlinksSupported) { |
| 3319 | const alias = path.join(directory, "alias"); |
| 3320 | yield* fileSystem.symlink(nestedCwd, alias); |
| 3321 | projectDirectories.push(alias); |
| 3322 | } |
| 3323 | for (const projectDirectory of projectDirectories) { |
| 3324 | const preview = yield* driver.getReviewDiffPreview({ |
| 3325 | cwd: projectDirectory, |
| 3326 | baseRef: initialBranch, |
| 3327 | }); |
| 3328 | assert.equal( |
| 3329 | preview.sources.find((source) => source.kind === "working-tree")!.files!.length, |
| 3330 | 3, |
| 3331 | ); |
| 3332 | for (const source of preview.sources) { |
| 3333 | for (const file of source.files ?? []) { |
| 3334 | const scoped = yield* driver.getReviewDiffPreview({ |
| 3335 | cwd: projectDirectory, |
| 3336 | baseRef: initialBranch, |
| 3337 | file: { path: file.path, previousPath: file.previousPath, sourceKind: source.kind }, |
| 3338 | }); |
| 3339 | const patch = scoped.sources.find((item) => item.kind === source.kind)!; |
| 3340 | assert.deepStrictEqual(patch.files, [file]); |
| 3341 | assert.include(patch.diff, `b/${file.path}`); |
| 3342 | } |
| 3343 | } |
| 3344 | } |
| 3345 | }), |
| 3346 | ); |
| 3347 | |
| 3348 | it.effect("reads complete tracked and untracked manifests beyond 1 MB", () => |
| 3349 | Effect.gen(function* () { |
| 3350 | const cwd = yield* makeTmpDir(); |
| 3351 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 3352 | const mergeBase = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 3353 | yield* writeTextFile(cwd, "untracked.txt", "untracked content\n"); |
| 3354 | const paths = Array.from({ length: 5000 }, (_, index) => `${"a".repeat(220)}-${index}.txt`); |
| 3355 | const stats = paths.map((path) => `1\t0\t${path}\0`).join(""); |
| 3356 | const untracked = [...paths, "untracked.txt"].join("\0") + "\0"; |
| 3357 | assert.isAbove(stats.length, 1024 * 1024); |
| 3358 | assert.isAbove(untracked.length, 1024 * 1024); |
| 3359 | let readLargeUntracked = false; |
| 3360 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 3361 | const spawner = ChildProcessSpawner.make((command) => { |
| 3362 | if (ChildProcess.isStandardCommand(command)) { |
| 3363 | if (command.args.includes("--numstat") && command.args.includes(mergeBase)) { |
| 3364 | return Effect.succeed(makeSuccessfulHandle(stats)); |
| 3365 | } |
| 3366 | if (command.args.includes("ls-files") && command.args.includes("--others")) { |
| 3367 | return Effect.succeed(makeSuccessfulHandle(readLargeUntracked ? untracked : "")); |
| 3368 | } |
| 3369 | } |
| 3370 | return delegate.spawn(command); |
| 3371 | }); |
| 3372 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 3373 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 3374 | Effect.provide(layerServerConfig), |
| 3375 | ); |
| 3376 | const branch = yield* driver.getReviewDiffPreview({ |
| 3377 | cwd, |
| 3378 | baseRef: initialBranch, |
| 3379 | }); |
| 3380 | const files = branch.sources.find((source) => source.kind === "branch-range")!.files!; |
| 3381 | assert.equal(files.length, paths.length); |
| 3382 | assert.equal(files.at(-1)?.path, paths.at(-1)); |
| 3383 | assert.equal( |
| 3384 | files.reduce((total, file) => total + file.additions, 0), |
| 3385 | paths.length, |
| 3386 | ); |
| 3387 | readLargeUntracked = true; |
| 3388 | const dirty = yield* driver.getReviewDiffPreview({ |
| 3389 | cwd, |
| 3390 | file: { path: "untracked.txt", previousPath: null, sourceKind: "working-tree" }, |
| 3391 | }); |
| 3392 | const source = dirty.sources.find((source) => source.kind === "working-tree")!; |
| 3393 | assert.deepStrictEqual(source.files, [ |
| 3394 | { |
| 3395 | path: "untracked.txt", |
| 3396 | previousPath: null, |
| 3397 | changeType: "new", |
| 3398 | additions: 1, |
| 3399 | deletions: 0, |
| 3400 | }, |
| 3401 | ]); |
| 3402 | assert.include(source.diff, "+untracked content"); |
| 3403 | }), |
| 3404 | ); |
| 3405 | |
| 3406 | it.effect( |
| 3407 | "returns an incomplete selected tracked preview while untracked discovery is held", |
| 3408 | () => |
| 3409 | Effect.gen(function* () { |
| 3410 | const cwd = yield* makeTmpDir(); |
| 3411 | yield* initRepoWithCommit(cwd); |
| 3412 | yield* writeTextFile(cwd, "README.md", "changed\n"); |
| 3413 | yield* writeTextFile(cwd, "new.txt", "untracked\n"); |
| 3414 | const started = yield* Deferred.make<void>(); |
| 3415 | const release = yield* Deferred.make<void>(); |
| 3416 | let untrackedReads = 0; |
| 3417 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 3418 | const spawner = ChildProcessSpawner.make((command) => |
| 3419 | Effect.gen(function* () { |
| 3420 | if (ChildProcess.isStandardCommand(command) && command.args.includes("--others")) { |
| 3421 | assert.equal( |
| 3422 | ++untrackedReads, |
| 3423 | 1, |
| 3424 | "tracked preview must not enumerate untracked files", |
| 3425 | ); |
| 3426 | yield* Deferred.succeed(started, undefined); |
| 3427 | yield* Deferred.await(release); |
| 3428 | } |
| 3429 | return yield* delegate.spawn(command); |
| 3430 | }), |
| 3431 | ); |
| 3432 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 3433 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 3434 | Effect.provide(layerServerConfig), |
| 3435 | ); |
| 3436 | const full = yield* driver |
| 3437 | .getReviewDiffPreview({ cwd, sourceKind: "working-tree" }) |
| 3438 | .pipe(Effect.forkChild); |
| 3439 | yield* Deferred.await(started); |
| 3440 | yield* Effect.gen(function* () { |
| 3441 | const preview = yield* driver.getReviewDiffPreview({ |
| 3442 | cwd, |
| 3443 | sourceKind: "working-tree", |
| 3444 | trackedOnly: true, |
| 3445 | }); |
| 3446 | assert.isTrue(preview.incomplete); |
| 3447 | assert.deepStrictEqual( |
| 3448 | preview.sources.map((source) => source.kind), |
| 3449 | ["working-tree"], |
| 3450 | ); |
| 3451 | assert.include(preview.sources[0]!.diff, "+changed"); |
| 3452 | assert.notInclude(preview.sources[0]!.diff, "untracked"); |
| 3453 | const metadata = yield* driver.getReviewDiffPreview({ |
| 3454 | cwd, |
| 3455 | sourceKind: "working-tree", |
| 3456 | trackedOnly: true, |
| 3457 | metadataOnly: true, |
| 3458 | }); |
| 3459 | assert.isTrue(metadata.incomplete); |
| 3460 | assert.deepStrictEqual(metadata.sources[0]!.files, preview.sources[0]!.files); |
| 3461 | assert.isTrue(metadata.sources[0]!.patchesDeferred); |
| 3462 | assert.isEmpty(metadata.sources[0]!.diff); |
| 3463 | }).pipe(Effect.ensuring(Deferred.succeed(release, undefined))); |
| 3464 | const complete = yield* Fiber.join(full); |
| 3465 | assert.isUndefined(complete.incomplete); |
| 3466 | assert.include(complete.sources[0]!.diff, "+untracked"); |
| 3467 | yield* writeTextFile(cwd, "README.md", "edited again\n"); |
| 3468 | const refreshed = yield* driver.getReviewDiffPreview({ |
| 3469 | cwd, |
| 3470 | baseRef: "missing-base", |
| 3471 | sourceKind: "working-tree", |
| 3472 | trackedOnly: true, |
| 3473 | }); |
| 3474 | assert.include(refreshed.sources[0]!.diff, "+edited again"); |
| 3475 | }), |
| 3476 | ); |
| 3477 | |
| 3478 | it.effect("propagates patch failures instead of reporting an empty complete diff", () => |
| 3479 | Effect.gen(function* () { |
| 3480 | const cwd = yield* makeTmpDir(); |
| 3481 | yield* initRepoWithCommit(cwd); |
| 3482 | yield* writeTextFile(cwd, "README.md", "changed\n"); |
| 3483 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 3484 | const spawner = ChildProcessSpawner.make((command) => |
| 3485 | ChildProcess.isStandardCommand(command) && command.args.includes("--patch") |
| 3486 | ? Effect.succeed(makeNonRepositoryHandle()) |
| 3487 | : delegate.spawn(command), |
| 3488 | ); |
| 3489 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 3490 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 3491 | Effect.provide(layerServerConfig), |
| 3492 | ); |
| 3493 | const result = yield* driver.getReviewDiffPreview({ cwd }).pipe(Effect.result); |
| 3494 | assert.isTrue(Result.isFailure(result)); |
| 3495 | if (Result.isFailure(result)) { |
| 3496 | assert.equal(result.failure.operation, "GitVcsDriver.getReviewDiffPreview.patch"); |
| 3497 | } |
| 3498 | const metadata = yield* driver.getReviewDiffPreview({ |
| 3499 | cwd, |
| 3500 | sourceKind: "working-tree", |
| 3501 | metadataOnly: true, |
| 3502 | }); |
| 3503 | assert.isTrue(metadata.sources[0]!.patchesDeferred); |
| 3504 | assert.isEmpty(metadata.sources[0]!.diff); |
| 3505 | assert.deepStrictEqual(metadata.sources[0]!.files, [ |
| 3506 | { |
| 3507 | path: "README.md", |
| 3508 | previousPath: null, |
| 3509 | changeType: "change", |
| 3510 | additions: 1, |
| 3511 | deletions: 1, |
| 3512 | }, |
| 3513 | ]); |
| 3514 | }), |
| 3515 | ); |
| 3516 | |
| 3517 | it.effect("drops an unterminated path from truncated NUL-separated git output", () => |
| 3518 | Effect.sync(() => { |
| 3519 | const paths = splitNullSeparatedGitStdoutPaths({ |
| 3520 | stdout: "complete.txt\0partial", |
| 3521 | stdoutTruncated: true, |
| 3522 | }); |
| 3523 | |
| 3524 | assert.deepStrictEqual(paths, ["complete.txt"]); |
| 3525 | }), |
| 3526 | ); |
| 3527 | |
| 3528 | it.effect("keeps the patch format clients parse when the repository changes it", () => |
| 3529 | Effect.gen(function* () { |
| 3530 | const cwd = yield* makeTmpDir(); |
| 3531 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 3532 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3533 | yield* git(cwd, ["config", "diff.noprefix", "true"]); |
| 3534 | yield* git(cwd, ["config", "diff.mnemonicPrefix", "true"]); |
| 3535 | yield* git(cwd, ["config", "diff.suppressBlankEmpty", "true"]); |
| 3536 | yield* git(cwd, ["checkout", "-b", "feature/noprefix"]); |
| 3537 | yield* writeTextFile(cwd, "README.md", "# test\n\ncommitted change\n"); |
| 3538 | yield* git(cwd, ["add", "README.md"]); |
| 3539 | yield* git(cwd, ["commit", "-m", "committed change"]); |
| 3540 | yield* writeTextFile(cwd, "README.md", "# test\n\ndirty change\n"); |
| 3541 | yield* writeTextFile(cwd, "untracked.txt", "untracked\n"); |
| 3542 | |
| 3543 | const preview = yield* driver.getReviewDiffPreview({ |
| 3544 | cwd, |
| 3545 | baseRef: initialBranch, |
| 3546 | ignoreWhitespace: false, |
| 3547 | }); |
| 3548 | |
| 3549 | const workingTree = preview.sources.find((source) => source.kind === "working-tree")?.diff; |
| 3550 | const branchRange = preview.sources.find((source) => source.kind === "branch-range")?.diff; |
| 3551 | assert.include(workingTree, "diff --git a/README.md b/README.md"); |
| 3552 | assert.include(workingTree, " # test\n \n-committed change\n+dirty change\n"); |
| 3553 | assert.include(workingTree, "+++ b/untracked.txt"); |
| 3554 | assert.include(branchRange, "diff --git a/README.md b/README.md"); |
| 3555 | }), |
| 3556 | ); |
| 3557 | |
| 3558 | it.effect("keeps the review working beside a nested repository with no commits", () => |
| 3559 | Effect.gen(function* () { |
| 3560 | const cwd = yield* makeTmpDir(); |
| 3561 | yield* initRepoWithCommit(cwd); |
| 3562 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3563 | yield* git(cwd, ["init", "scaffold"]); |
| 3564 | const committed = `${cwd}/committed`; |
| 3565 | yield* (yield* FileSystem.FileSystem).makeDirectory(committed); |
| 3566 | yield* initRepoWithCommit(committed); |
| 3567 | yield* writeTextFile(cwd, "README.md", "# tracked change\n"); |
| 3568 | yield* writeTextFile(cwd, "untracked.txt", "untracked contents\n"); |
| 3569 | |
| 3570 | const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); |
| 3571 | const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; |
| 3572 | |
| 3573 | assert.include(diff, "+# tracked change"); |
| 3574 | assert.include(diff, "+untracked contents"); |
| 3575 | assert.notInclude(diff, "scaffold"); |
| 3576 | assert.include(diff, "diff --git a/committed b/committed"); |
| 3577 | |
| 3578 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 3579 | assert.deepStrictEqual(status.branchChanges, { |
| 3580 | baseRef: null, |
| 3581 | insertions: 3, |
| 3582 | deletions: 1, |
| 3583 | }); |
| 3584 | }), |
| 3585 | ); |
| 3586 | |
| 3587 | it.effect("keeps untracked filenames with pathspec magic in the review", () => |
| 3588 | Effect.gen(function* () { |
| 3589 | const cwd = yield* makeTmpDir(); |
| 3590 | yield* initRepoWithCommit(cwd); |
| 3591 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3592 | yield* writeTextFile(cwd, ":(exclude)after.ts", "literal pathspec contents\n"); |
| 3593 | yield* writeTextFile(cwd, "ordinary.ts", "ordinary contents\n"); |
| 3594 | const indexBefore = yield* git(cwd, ["ls-files", "--stage"]); |
| 3595 | |
| 3596 | const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); |
| 3597 | const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; |
| 3598 | |
| 3599 | assert.include(diff, "+literal pathspec contents"); |
| 3600 | assert.include(diff, "+ordinary contents"); |
| 3601 | const scoped = yield* driver.getReviewDiffPreview({ |
| 3602 | cwd, |
| 3603 | file: { |
| 3604 | path: ":(exclude)after.ts", |
| 3605 | previousPath: null, |
| 3606 | sourceKind: "working-tree", |
| 3607 | }, |
| 3608 | }); |
| 3609 | const scopedSource = scoped.sources.find((source) => source.kind === "working-tree")!; |
| 3610 | assert.deepStrictEqual(scopedSource.files, [ |
| 3611 | { |
| 3612 | path: ":(exclude)after.ts", |
| 3613 | previousPath: null, |
| 3614 | changeType: "new", |
| 3615 | additions: 1, |
| 3616 | deletions: 0, |
| 3617 | }, |
| 3618 | ]); |
| 3619 | assert.include(scopedSource.diff, "+literal pathspec contents"); |
| 3620 | assert.notInclude(scopedSource.diff, "ordinary.ts"); |
| 3621 | assert.strictEqual(yield* git(cwd, ["ls-files", "--stage"]), indexBefore); |
| 3622 | }), |
| 3623 | ); |
| 3624 | |
| 3625 | it.effect("reviews untracked files outside the sparse-checkout cone", () => |
| 3626 | Effect.gen(function* () { |
| 3627 | const cwd = yield* makeTmpDir(); |
| 3628 | yield* initRepoWithCommit(cwd); |
| 3629 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3630 | yield* writeTextFile(cwd, "excluded/tracked.ts", "tracked\n"); |
| 3631 | yield* git(cwd, ["add", "excluded/tracked.ts"]); |
| 3632 | yield* git(cwd, ["commit", "-m", "add excluded directory"]); |
| 3633 | yield* git(cwd, ["sparse-checkout", "set", "--cone", "included"]); |
| 3634 | yield* writeTextFile(cwd, "excluded/new.ts", "outside the cone\n"); |
| 3635 | |
| 3636 | const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); |
| 3637 | |
| 3638 | const source = preview.sources.find((candidate) => candidate.kind === "working-tree")!; |
| 3639 | assert.deepStrictEqual(source.files, [ |
| 3640 | { |
| 3641 | path: "excluded/new.ts", |
| 3642 | previousPath: null, |
| 3643 | changeType: "new", |
| 3644 | additions: 1, |
| 3645 | deletions: 0, |
| 3646 | }, |
| 3647 | ]); |
| 3648 | assert.include(source.diff, "+outside the cone"); |
| 3649 | }), |
| 3650 | ); |
| 3651 | |
| 3652 | it.effect("detects an unstaged rename with edits without mutating a split index", () => |
| 3653 | Effect.gen(function* () { |
| 3654 | const cwd = yield* makeTmpDir(); |
| 3655 | yield* initRepoWithCommit(cwd); |
| 3656 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3657 | const fileSystem = yield* FileSystem.FileSystem; |
| 3658 | const pathService = yield* Path.Path; |
| 3659 | yield* writeTextFile(cwd, "before.ts", "one\ntwo\nthree\nfour\nfive\n"); |
| 3660 | yield* git(cwd, ["add", "before.ts"]); |
| 3661 | yield* git(cwd, ["commit", "-m", "add source file"]); |
| 3662 | yield* git(cwd, ["config", "core.splitIndex", "true"]); |
| 3663 | yield* git(cwd, ["config", "splitIndex.sharedIndexExpire", "now"]); |
| 3664 | yield* git(cwd, ["update-index", "--split-index"]); |
| 3665 | const indexPath = yield* git(cwd, ["rev-parse", "--git-path", "index"]); |
| 3666 | const indexHashBefore = yield* git(cwd, ["hash-object", indexPath]); |
| 3667 | const gitDirValue = yield* git(cwd, ["rev-parse", "--git-dir"]); |
| 3668 | const gitDir = pathService.isAbsolute(gitDirValue) |
| 3669 | ? gitDirValue |
| 3670 | : pathService.resolve(cwd, gitDirValue); |
| 3671 | const sharedIndexesBefore = (yield* fileSystem.readDirectory(gitDir)) |
| 3672 | .filter((entry) => entry.startsWith("sharedindex.")) |
| 3673 | .sort(); |
| 3674 | yield* fileSystem.rename( |
| 3675 | pathService.join(cwd, "before.ts"), |
| 3676 | pathService.join(cwd, "after.ts"), |
| 3677 | ); |
| 3678 | yield* writeTextFile(cwd, "after.ts", "one\ntwo\nTHREE\nfour\nfive\n"); |
| 3679 | |
| 3680 | const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); |
| 3681 | const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; |
| 3682 | const indexHashAfter = yield* git(cwd, ["hash-object", indexPath]); |
| 3683 | const sharedIndexesAfter = (yield* fileSystem.readDirectory(gitDir)) |
| 3684 | .filter((entry) => entry.startsWith("sharedindex.")) |
| 3685 | .sort(); |
| 3686 | |
| 3687 | const source = preview.sources.find((candidate) => candidate.kind === "working-tree")!; |
| 3688 | assert.deepStrictEqual(source.files, [ |
| 3689 | { |
| 3690 | path: "after.ts", |
| 3691 | previousPath: "before.ts", |
| 3692 | changeType: "rename-changed", |
| 3693 | additions: 1, |
| 3694 | deletions: 1, |
| 3695 | }, |
| 3696 | ]); |
| 3697 | const scoped = yield* driver.getReviewDiffPreview({ |
| 3698 | cwd, |
| 3699 | file: { path: "after.ts", previousPath: "before.ts", sourceKind: "working-tree" }, |
| 3700 | }); |
| 3701 | const scopedSource = scoped.sources.find((candidate) => candidate.kind === "working-tree")!; |
| 3702 | assert.deepStrictEqual(scopedSource.files, source.files); |
| 3703 | assert.equal(scopedSource.diff, diff); |
| 3704 | assert.include(diff, "rename from before.ts"); |
| 3705 | assert.include(diff, "rename to after.ts"); |
| 3706 | assert.include(diff, "-three"); |
| 3707 | assert.include(diff, "+THREE"); |
| 3708 | assert.strictEqual(diff.match(/^diff --git /gm)?.length, 1); |
| 3709 | assert.strictEqual(indexHashAfter, indexHashBefore); |
| 3710 | assert.deepStrictEqual(sharedIndexesAfter, sharedIndexesBefore); |
| 3711 | }), |
| 3712 | ); |
| 3713 | |
| 3714 | it.effect.each(["fails", "exceeds the output limit"] as const)( |
| 3715 | "keeps tracked changes visible when untracked discovery %s", |
| 3716 | (scenario) => |
| 3717 | Effect.gen(function* () { |
| 3718 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 3719 | const failingLsFilesSpawner = ChildProcessSpawner.make((command) => { |
| 3720 | if (!ChildProcess.isStandardCommand(command)) { |
| 3721 | return Effect.die("expected a standard Git command"); |
| 3722 | } |
| 3723 | if (command.args[0] !== "ls-files" || command.args[1] !== "--others") { |
| 3724 | return delegate.spawn(command); |
| 3725 | } |
| 3726 | return Effect.succeed( |
| 3727 | scenario === "fails" |
| 3728 | ? makeNonRepositoryHandle() |
| 3729 | : makeSuccessfulHandle("a".repeat(16 * 1024 * 1024 + 1)), |
| 3730 | ); |
| 3731 | }); |
| 3732 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 3733 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingLsFilesSpawner), |
| 3734 | Effect.provide(layerServerConfig), |
| 3735 | ); |
| 3736 | const cwd = yield* makeTmpDir(); |
| 3737 | yield* initRepoWithCommit(cwd).pipe( |
| 3738 | Effect.provideService(GitVcsDriver.GitVcsDriver, driver), |
| 3739 | ); |
| 3740 | yield* writeTextFile(cwd, "README.md", "# tracked change\n"); |
| 3741 | |
| 3742 | const preview = yield* driver.getReviewDiffPreview({ |
| 3743 | cwd, |
| 3744 | ignoreWhitespace: false, |
| 3745 | metadataOnly: true, |
| 3746 | }); |
| 3747 | const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; |
| 3748 | |
| 3749 | const source = preview.sources.find((source) => source.kind === "working-tree")!; |
| 3750 | assert.isUndefined(source.patchesDeferred); |
| 3751 | assert.isUndefined(source.files); |
| 3752 | assert.isTrue(source.truncated); |
| 3753 | assert.include(diff, "-# test"); |
| 3754 | assert.include(diff, "+# tracked change"); |
| 3755 | }), |
| 3756 | ); |
| 3757 | |
| 3758 | it.effect.each([ |
| 3759 | { stagedCopy: false, expected: ["deleted file mode", "-remove me"] }, |
| 3760 | { stagedCopy: true, expected: ["rename from removed.txt", "rename to copy.txt"] }, |
| 3761 | ])( |
| 3762 | "preserves a staged deletion when the removed path still exists (staged copy: $stagedCopy)", |
| 3763 | ({ stagedCopy, expected }) => |
| 3764 | Effect.gen(function* () { |
| 3765 | const cwd = yield* makeTmpDir(); |
| 3766 | yield* initRepoWithCommit(cwd); |
| 3767 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3768 | yield* writeTextFile(cwd, "removed.txt", "remove me\n"); |
| 3769 | yield* git(cwd, ["add", "removed.txt"]); |
| 3770 | yield* git(cwd, ["commit", "-m", "add removable file"]); |
| 3771 | yield* git(cwd, ["rm", "--cached", "removed.txt"]); |
| 3772 | if (stagedCopy) { |
| 3773 | yield* writeTextFile(cwd, "copy.txt", "remove me\n"); |
| 3774 | yield* git(cwd, ["add", "copy.txt"]); |
| 3775 | } |
| 3776 | |
| 3777 | const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); |
| 3778 | const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; |
| 3779 | |
| 3780 | for (const text of expected) assert.include(diff, text); |
| 3781 | assert.notInclude(diff, "new file mode"); |
| 3782 | }), |
| 3783 | ); |
| 3784 | |
| 3785 | it.effect.each([false, true])( |
| 3786 | "keeps the preceding second cached in review previews (split: %s)", |
| 3787 | (splitIndex) => |
| 3788 | Effect.gen(function* () { |
| 3789 | const cwd = yield* makeTmpDir(); |
| 3790 | yield* initRepoWithCommit(cwd); |
| 3791 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3792 | const fs = yield* FileSystem.FileSystem; |
| 3793 | const path = yield* Path.Path; |
| 3794 | yield* writeTextFile(cwd, ".gitattributes", "stable.txt filter=probe\n"); |
| 3795 | yield* writeTextFile(cwd, "stable.txt", "unchanged\n"); |
| 3796 | yield* writeTextFile( |
| 3797 | cwd, |
| 3798 | ".git/filter.cjs", |
| 3799 | 'require("node:fs").appendFileSync(".git/filter-runs", "read\\n"); process.stdin.pipe(process.stdout);', |
| 3800 | ); |
| 3801 | yield* git(cwd, ["config", "filter.probe.clean", "node .git/filter.cjs"]); |
| 3802 | yield* fs.utimes(path.join(cwd, "stable.txt"), 1_699_999_999.5, 1_699_999_999.5); |
| 3803 | yield* git(cwd, ["add", "."]); |
| 3804 | yield* git(cwd, ["commit", "-m", "cache stable file"]); |
| 3805 | if (splitIndex) yield* git(cwd, ["update-index", "--split-index"]); |
| 3806 | const indexPath = path.join(cwd, ".git", "index"); |
| 3807 | yield* fs.utimes(indexPath, 1_700_000_000, 1_700_000_000); |
| 3808 | const originalIndex = yield* fs.readFile(indexPath); |
| 3809 | const originalMtime = (yield* fs.stat(indexPath)).mtime; |
| 3810 | yield* writeTextFile(cwd, ".git/filter-runs", ""); |
| 3811 | yield* writeTextFile(cwd, "untracked.txt", "new\n"); |
| 3812 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 3813 | assert.deepStrictEqual( |
| 3814 | preview.sources.find((source) => source.kind === "working-tree")!.files, |
| 3815 | [ |
| 3816 | { |
| 3817 | path: "untracked.txt", |
| 3818 | previousPath: null, |
| 3819 | changeType: "new", |
| 3820 | additions: 1, |
| 3821 | deletions: 0, |
| 3822 | }, |
| 3823 | ], |
| 3824 | ); |
| 3825 | assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/filter-runs")), ""); |
| 3826 | assert.deepStrictEqual(yield* fs.readFile(indexPath), originalIndex); |
| 3827 | assert.deepStrictEqual((yield* fs.stat(indexPath)).mtime, originalMtime); |
| 3828 | }), |
| 3829 | ); |
| 3830 | |
| 3831 | it.effect.each([ |
| 3832 | [1_700_000_000, false], |
| 3833 | [1_700_000_000.9999, false], |
| 3834 | [1_700_000_000, true], |
| 3835 | [1_700_000_000.9999, true], |
| 3836 | ] as const)( |
| 3837 | "preserves same-size edits with a racy review index (%s, split: %s)", |
| 3838 | ([timestamp, splitIndex]) => |
| 3839 | Effect.gen(function* () { |
| 3840 | const cwd = yield* makeTmpDir(); |
| 3841 | yield* initRepoWithCommit(cwd); |
| 3842 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3843 | const fileSystem = yield* FileSystem.FileSystem; |
| 3844 | const path = yield* Path.Path; |
| 3845 | const filePath = path.join(cwd, "tracked.txt"); |
| 3846 | const indexPath = path.join(cwd, ".git", "index"); |
| 3847 | yield* git(cwd, ["config", "core.trustctime", "false"]); |
| 3848 | yield* writeTextFile(cwd, "tracked.txt", "before\n"); |
| 3849 | yield* fileSystem.utimes(filePath, timestamp, timestamp); |
| 3850 | yield* git(cwd, ["add", "tracked.txt"]); |
| 3851 | yield* git(cwd, ["commit", "-m", "record racy file"]); |
| 3852 | if (splitIndex) yield* git(cwd, ["update-index", "--split-index"]); |
| 3853 | yield* fileSystem.utimes(indexPath, timestamp, timestamp); |
| 3854 | const originalIndex = yield* fileSystem.readFile(indexPath); |
| 3855 | const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime; |
| 3856 | yield* writeTextFile(cwd, "tracked.txt", "after!\n"); |
| 3857 | yield* fileSystem.utimes(filePath, timestamp, timestamp); |
| 3858 | yield* writeTextFile(cwd, "untracked.txt", "new\n"); |
| 3859 | |
| 3860 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 3861 | const dirty = preview.sources.find((source) => source.kind === "working-tree")!; |
| 3862 | assert.deepStrictEqual(dirty.files, [ |
| 3863 | { |
| 3864 | path: "tracked.txt", |
| 3865 | previousPath: null, |
| 3866 | changeType: "change", |
| 3867 | additions: 1, |
| 3868 | deletions: 1, |
| 3869 | }, |
| 3870 | { |
| 3871 | path: "untracked.txt", |
| 3872 | previousPath: null, |
| 3873 | changeType: "new", |
| 3874 | additions: 1, |
| 3875 | deletions: 0, |
| 3876 | }, |
| 3877 | ]); |
| 3878 | assert.include(dirty.diff, "-before"); |
| 3879 | assert.include(dirty.diff, "+after!"); |
| 3880 | assert.deepStrictEqual(yield* fileSystem.readFile(indexPath), originalIndex); |
| 3881 | assert.deepStrictEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime); |
| 3882 | }), |
| 3883 | ); |
| 3884 | |
| 3885 | it.effect("keeps complete stats for files beyond the combined patch limit", () => |
| 3886 | Effect.gen(function* () { |
| 3887 | const cwd = yield* makeTmpDir(); |
| 3888 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 3889 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3890 | const largeContents = "a long line of changed content for the diff preview\n".repeat(4000); |
| 3891 | yield* git(cwd, ["checkout", "-b", "feature/large"]); |
| 3892 | yield* writeTextFile(cwd, "a-large.txt", largeContents); |
| 3893 | yield* writeTextFile(cwd, "z-last.txt", "last file\n"); |
| 3894 | yield* git(cwd, ["add", "."]); |
| 3895 | yield* git(cwd, ["commit", "-m", "large change"]); |
| 3896 | yield* writeTextFile(cwd, "a-large.txt", largeContents.replaceAll("changed", "updated")); |
| 3897 | yield* writeTextFile(cwd, "z-last.txt", "last file updated\n"); |
| 3898 | yield* writeTextFile(cwd, "untracked.txt", largeContents); |
| 3899 | |
| 3900 | const preview = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); |
| 3901 | const branch = preview.sources.find((source) => source.kind === "branch-range")!; |
| 3902 | const dirty = preview.sources.find((source) => source.kind === "working-tree")!; |
| 3903 | assert.isTrue(branch.truncated); |
| 3904 | assert.isTrue(dirty.truncated); |
| 3905 | assert.notInclude(branch.diff, "z-last.txt"); |
| 3906 | for (const source of [branch, dirty]) { |
| 3907 | const selected = yield* driver.getReviewDiffPreview({ |
| 3908 | cwd, |
| 3909 | baseRef: initialBranch, |
| 3910 | sourceKind: source.kind === "working-tree" ? "working-tree" : "branch-range", |
| 3911 | }); |
| 3912 | assert.deepStrictEqual(selected.sources, [source]); |
| 3913 | const metadata = (yield* driver.getReviewDiffPreview({ |
| 3914 | cwd, |
| 3915 | baseRef: initialBranch, |
| 3916 | sourceKind: source.kind === "working-tree" ? "working-tree" : "branch-range", |
| 3917 | metadataOnly: true, |
| 3918 | })).sources[0]!; |
| 3919 | assert.deepStrictEqual(metadata.files, source.files); |
| 3920 | assert.isTrue(metadata.patchesDeferred); |
| 3921 | assert.isFalse(metadata.truncated); |
| 3922 | assert.isEmpty(metadata.diff); |
| 3923 | for (const file of source.files ?? []) { |
| 3924 | const individual = yield* driver.getReviewDiffPreview({ |
| 3925 | cwd, |
| 3926 | baseRef: initialBranch, |
| 3927 | file: { path: file.path, previousPath: file.previousPath, sourceKind: source.kind }, |
| 3928 | }); |
| 3929 | const patch = individual.sources.find((candidate) => candidate.kind === source.kind)!; |
| 3930 | assert.isFalse(patch.truncated); |
| 3931 | assert.deepStrictEqual(patch.files, [file]); |
| 3932 | assert.include(patch.diff, `b/${file.path}`); |
| 3933 | assert.isEmpty( |
| 3934 | individual.sources.find((candidate) => candidate.kind !== source.kind)!.diff, |
| 3935 | ); |
| 3936 | } |
| 3937 | } |
| 3938 | |
| 3939 | assert.deepStrictEqual(branch.files, [ |
| 3940 | { |
| 3941 | path: "a-large.txt", |
| 3942 | previousPath: null, |
| 3943 | changeType: "new", |
| 3944 | additions: 4000, |
| 3945 | deletions: 0, |
| 3946 | }, |
| 3947 | { |
| 3948 | path: "untracked.txt", |
| 3949 | previousPath: null, |
| 3950 | changeType: "new", |
| 3951 | additions: 4000, |
| 3952 | deletions: 0, |
| 3953 | }, |
| 3954 | { path: "z-last.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, |
| 3955 | ]); |
| 3956 | assert.deepStrictEqual(dirty.files, [ |
| 3957 | { |
| 3958 | path: "a-large.txt", |
| 3959 | previousPath: null, |
| 3960 | changeType: "change", |
| 3961 | additions: 4000, |
| 3962 | deletions: 4000, |
| 3963 | }, |
| 3964 | { |
| 3965 | path: "untracked.txt", |
| 3966 | previousPath: null, |
| 3967 | changeType: "new", |
| 3968 | additions: 4000, |
| 3969 | deletions: 0, |
| 3970 | }, |
| 3971 | { |
| 3972 | path: "z-last.txt", |
| 3973 | previousPath: null, |
| 3974 | changeType: "change", |
| 3975 | additions: 1, |
| 3976 | deletions: 1, |
| 3977 | }, |
| 3978 | ]); |
| 3979 | }), |
| 3980 | ); |
| 3981 | |
| 3982 | it.effect("preserves renames, unusual paths, modes, and binary statistics", () => |
| 3983 | Effect.gen(function* () { |
| 3984 | const cwd = yield* makeTmpDir(); |
| 3985 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 3986 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 3987 | yield* writeTextFile(cwd, "mode-only.sh", "echo unchanged\n"); |
| 3988 | yield* writeTextFile(cwd, "removed.txt", "removed\n"); |
| 3989 | yield* git(cwd, ["add", "mode-only.sh", "removed.txt"]); |
| 3990 | yield* git(cwd, ["commit", "-m", "add executable candidate"]); |
| 3991 | yield* git(cwd, ["checkout", "-b", "feature/paths"]); |
| 3992 | yield* git(cwd, ["mv", "README.md", "renamed.md"]); |
| 3993 | yield* git(cwd, ["rm", "removed.txt"]); |
| 3994 | yield* writeTextFile(cwd, "[literal].txt", "literal\n"); |
| 3995 | yield* writeTextFile(cwd, " leading.txt", "whitespace path\n"); |
| 3996 | yield* writeTextFile(cwd, "l.txt", "other\n"); |
| 3997 | yield* writeTextFile(cwd, "binary.dat", "binary\0data"); |
| 3998 | if ((yield* HostProcess.Platform) !== "win32") { |
| 3999 | yield* writeTextFile(cwd, "tab\tand\nnewline.txt", "unusual path\n"); |
| 4000 | } |
| 4001 | yield* git(cwd, ["add", "."]); |
| 4002 | yield* git(cwd, ["update-index", "--chmod=+x", "mode-only.sh"]); |
| 4003 | yield* git(cwd, ["commit", "-m", "rename and add files"]); |
| 4004 | const preview = yield* driver.getReviewDiffPreview({ |
| 4005 | cwd, |
| 4006 | baseRef: initialBranch, |
| 4007 | }); |
| 4008 | const branch = preview.sources.find((source) => source.kind === "branch-range")!; |
| 4009 | const decodeReviewDiffPreviewInput = Schema.decodeEffect(ReviewDiffPreviewInput); |
| 4010 | |
| 4011 | for (const path of ["renamed.md", "[literal].txt", " leading.txt", "mode-only.sh"]) { |
| 4012 | const stat = branch.files!.find((file) => file.path === path)!; |
| 4013 | const request = yield* decodeReviewDiffPreviewInput({ |
| 4014 | cwd, |
| 4015 | baseRef: initialBranch, |
| 4016 | file: { path, previousPath: stat.previousPath, sourceKind: "branch-range" }, |
| 4017 | }); |
| 4018 | const result = yield* driver.getReviewDiffPreview(request); |
| 4019 | const scoped = result.sources.find((source) => source.kind === "branch-range")!; |
| 4020 | assert.deepStrictEqual(scoped.files, [stat]); |
| 4021 | assert.notInclude(scoped.diff, "b/l.txt"); |
| 4022 | if (path === "renamed.md") assert.include(scoped.diff, "rename from README.md"); |
| 4023 | if (path === "mode-only.sh") { |
| 4024 | assert.include(scoped.diff, "old mode 100644"); |
| 4025 | assert.include(scoped.diff, "new mode 100755"); |
| 4026 | } |
| 4027 | } |
| 4028 | assert.include(branch.diff, "rename from README.md"); |
| 4029 | assert.include(branch.diff, "rename to renamed.md"); |
| 4030 | assert.deepInclude(branch.files ?? [], { |
| 4031 | path: "renamed.md", |
| 4032 | previousPath: "README.md", |
| 4033 | changeType: "rename-pure", |
| 4034 | additions: 0, |
| 4035 | deletions: 0, |
| 4036 | }); |
| 4037 | assert.deepInclude(branch.files ?? [], { |
| 4038 | path: "removed.txt", |
| 4039 | previousPath: null, |
| 4040 | changeType: "deleted", |
| 4041 | additions: 0, |
| 4042 | deletions: 1, |
| 4043 | }); |
| 4044 | assert.deepInclude(branch.files ?? [], { |
| 4045 | path: "mode-only.sh", |
| 4046 | previousPath: null, |
| 4047 | changeType: "change", |
| 4048 | additions: 0, |
| 4049 | deletions: 0, |
| 4050 | }); |
| 4051 | assert.deepInclude(branch.files ?? [], { |
| 4052 | path: "binary.dat", |
| 4053 | previousPath: null, |
| 4054 | changeType: "new", |
| 4055 | additions: 0, |
| 4056 | deletions: 0, |
| 4057 | }); |
| 4058 | if ((yield* HostProcess.Platform) !== "win32") { |
| 4059 | assert.deepInclude(branch.files ?? [], { |
| 4060 | path: "tab\tand\nnewline.txt", |
| 4061 | previousPath: null, |
| 4062 | changeType: "new", |
| 4063 | additions: 1, |
| 4064 | deletions: 0, |
| 4065 | }); |
| 4066 | } |
| 4067 | }), |
| 4068 | ); |
| 4069 | |
| 4070 | it.effect("reports staged and untracked changes before the first commit", () => |
| 4071 | Effect.gen(function* () { |
| 4072 | const cwd = yield* makeTmpDir(); |
| 4073 | yield* git(cwd, ["init"]); |
| 4074 | yield* writeTextFile(cwd, "staged.txt", "staged\n"); |
| 4075 | yield* git(cwd, ["add", "staged.txt"]); |
| 4076 | yield* writeTextFile(cwd, "untracked.txt", "untracked\n"); |
| 4077 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4078 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4079 | const dirty = preview.sources.find((source) => source.kind === "working-tree")!; |
| 4080 | assert.deepStrictEqual(dirty.files, [ |
| 4081 | { path: "staged.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, |
| 4082 | { |
| 4083 | path: "untracked.txt", |
| 4084 | previousPath: null, |
| 4085 | changeType: "new", |
| 4086 | additions: 1, |
| 4087 | deletions: 0, |
| 4088 | }, |
| 4089 | ]); |
| 4090 | assert.include(dirty.diff, "b/staged.txt"); |
| 4091 | assert.include(dirty.diff, "b/untracked.txt"); |
| 4092 | }), |
| 4093 | ); |
| 4094 | |
| 4095 | it.effect("loads full file contents for working-tree diff expansion", () => |
| 4096 | Effect.gen(function* () { |
| 4097 | const cwd = yield* makeTmpDir(); |
| 4098 | yield* initRepoWithCommit(cwd); |
| 4099 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4100 | const pathService = yield* Path.Path; |
| 4101 | yield* writeTextFile(cwd, "nested/.keep", ""); |
| 4102 | yield* writeTextFile(cwd, "README.md", "# changed\nunchanged context\n"); |
| 4103 | |
| 4104 | const contents = yield* driver.getReviewDiffFileContents( |
| 4105 | makeReviewDiffFileContentsInput(pathService.join(cwd, "nested")), |
| 4106 | ); |
| 4107 | |
| 4108 | assert.strictEqual(contents.oldContents, "# test\n"); |
| 4109 | assert.strictEqual(contents.newContents, "# changed\nunchanged context\n"); |
| 4110 | }), |
| 4111 | ); |
| 4112 | |
| 4113 | it.effect.each([ |
| 4114 | { scenario: "kept", before: "\uFEFFold\n", after: "\uFEFFnew\n" }, |
| 4115 | { scenario: "added", before: "same\n", after: "\uFEFFsame\n" }, |
| 4116 | { scenario: "removed", before: "\uFEFFsame\n", after: "same\n" }, |
| 4117 | ])("preserves byte-order marks in diff expansion when $scenario", ({ before, after }) => |
| 4118 | Effect.gen(function* () { |
| 4119 | const cwd = yield* makeTmpDir(); |
| 4120 | yield* initRepoWithCommit(cwd); |
| 4121 | yield* writeTextFile(cwd, "README.md", before); |
| 4122 | yield* git(cwd, ["commit", "-am", "write original contents"]); |
| 4123 | yield* writeTextFile(cwd, "README.md", after); |
| 4124 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4125 | |
| 4126 | const contents = yield* driver.getReviewDiffFileContents( |
| 4127 | makeReviewDiffFileContentsInput(cwd), |
| 4128 | ); |
| 4129 | |
| 4130 | assert.deepStrictEqual(contents, { oldContents: before, newContents: after }); |
| 4131 | }), |
| 4132 | ); |
| 4133 | |
| 4134 | it.effect("reads a base ref that looks like an option as a revision", () => |
| 4135 | Effect.gen(function* () { |
| 4136 | const cwd = yield* makeTmpDir(); |
| 4137 | yield* initRepoWithCommit(cwd); |
| 4138 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4139 | const fileSystem = yield* FileSystem.FileSystem; |
| 4140 | const output = (yield* Path.Path).join(yield* makeTmpDir(), "out"); |
| 4141 | |
| 4142 | yield* driver |
| 4143 | .getReviewDiffFileContents( |
| 4144 | makeReviewDiffFileContentsInput(cwd, { baseRef: `--output=${output}` }), |
| 4145 | ) |
| 4146 | .pipe(Effect.flip); |
| 4147 | yield* driver.readRangeContext(cwd, `--output=${output}`).pipe(Effect.flip); |
| 4148 | |
| 4149 | assert.isFalse(yield* fileSystem.exists(`${output}:README.md`)); |
| 4150 | assert.isFalse(yield* fileSystem.exists(`${output}..HEAD`)); |
| 4151 | }), |
| 4152 | ); |
| 4153 | |
| 4154 | it.effect("reads raw range context regardless of Git display configuration", () => |
| 4155 | Effect.gen(function* () { |
| 4156 | const cwd = yield* makeTmpDir(); |
| 4157 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 4158 | yield* git(cwd, ["config", "diff.probe.textconv", "touch textconv-ran; echo converted"]); |
| 4159 | yield* git(cwd, ["config", "color.ui", "always"]); |
| 4160 | yield* git(cwd, ["config", "diff.relative", "true"]); |
| 4161 | yield* git(cwd, ["config", "log.decorate", "short"]); |
| 4162 | yield* git(cwd, ["checkout", "-b", "feature/range"]); |
| 4163 | yield* writeTextFile(cwd, ".gitattributes", "*.doc diff=probe\n"); |
| 4164 | yield* writeTextFile(cwd, "notes.doc", "source line\n"); |
| 4165 | yield* writeTextFile(cwd, "plain.txt", "plain line\n"); |
| 4166 | yield* writeTextFile(cwd, "binary.dat", "binary\0data"); |
| 4167 | yield* git(cwd, ["add", "."]); |
| 4168 | const signingKey = `${yield* makeTmpDir("git-vcs-driver-signing-key-")}/key`; |
| 4169 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 4170 | const keygen = ChildProcess.make("ssh-keygen", [ |
| 4171 | "-q", |
| 4172 | "-t", |
| 4173 | "ed25519", |
| 4174 | "-N", |
| 4175 | "", |
| 4176 | "-f", |
| 4177 | signingKey, |
| 4178 | ]); |
| 4179 | assert.equal(Number(yield* spawner.exitCode(keygen)), 0); |
| 4180 | yield* git(cwd, ["config", "gpg.format", "ssh"]); |
| 4181 | // A global signer such as 1Password's cannot use the fixture's generated key. |
| 4182 | yield* git(cwd, ["config", "gpg.ssh.program", "ssh-keygen"]); |
| 4183 | yield* git(cwd, ["config", "user.signingkey", `${signingKey}.pub`]); |
| 4184 | yield* git(cwd, ["config", "log.showSignature", "true"]); |
| 4185 | yield* git(cwd, ["commit", "-S", "-m", "range files"]); |
| 4186 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4187 | const fileSystem = yield* FileSystem.FileSystem; |
| 4188 | const projectCwd = `${cwd}/app`; |
| 4189 | yield* fileSystem.makeDirectory(projectCwd); |
| 4190 | |
| 4191 | const context = yield* driver.readRangeContext(projectCwd, initialBranch); |
| 4192 | |
| 4193 | assert.match(context.commitSummary.trim(), /^[a-f0-9]+ range files$/); |
| 4194 | assert.include(context.diffPatch, "+source line"); |
| 4195 | assert.notInclude(context.diffPatch, "converted"); |
| 4196 | assert.include(context.diffPatch, "+plain line"); |
| 4197 | assert.include(context.diffPatch, "Binary files /dev/null and b/binary.dat differ"); |
| 4198 | assert.include(context.diffSummary, "notes.doc"); |
| 4199 | for (const output of [context.commitSummary, context.diffSummary, context.diffPatch]) { |
| 4200 | assert.notInclude(output, "\u001b["); |
| 4201 | } |
| 4202 | assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); |
| 4203 | |
| 4204 | yield* writeTextFile(cwd, "notes.doc", "updated source line\n"); |
| 4205 | const staged = yield* driver.prepareCommitContext(projectCwd, ["notes.doc"]); |
| 4206 | assert.include(staged?.stagedPatch ?? "", "+updated source line"); |
| 4207 | assert.notInclude(staged?.stagedPatch ?? "", "converted"); |
| 4208 | assert.notInclude(staged?.stagedPatch ?? "", "\u001b["); |
| 4209 | assert.include(staged?.stagedSummary ?? "", "notes.doc"); |
| 4210 | assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); |
| 4211 | }), |
| 4212 | ); |
| 4213 | |
| 4214 | it.effect("loads new and deleted files without reading their missing side", () => |
| 4215 | Effect.gen(function* () { |
| 4216 | const cwd = yield* makeTmpDir(); |
| 4217 | yield* initRepoWithCommit(cwd); |
| 4218 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4219 | const fileSystem = yield* FileSystem.FileSystem; |
| 4220 | const pathService = yield* Path.Path; |
| 4221 | yield* writeTextFile(cwd, "added.ts", "export const added = true;\n"); |
| 4222 | yield* fileSystem.remove(pathService.join(cwd, "README.md")); |
| 4223 | |
| 4224 | const [added, deleted] = yield* Effect.all([ |
| 4225 | driver.getReviewDiffFileContents( |
| 4226 | makeReviewDiffFileContentsInput(cwd, { |
| 4227 | changeType: "new", |
| 4228 | oldPath: "added.ts", |
| 4229 | newPath: "added.ts", |
| 4230 | }), |
| 4231 | ), |
| 4232 | driver.getReviewDiffFileContents( |
| 4233 | makeReviewDiffFileContentsInput(cwd, { changeType: "deleted" }), |
| 4234 | ), |
| 4235 | ]); |
| 4236 | |
| 4237 | assert.deepStrictEqual(added, { |
| 4238 | oldContents: "", |
| 4239 | newContents: "export const added = true;\n", |
| 4240 | }); |
| 4241 | assert.deepStrictEqual(deleted, { |
| 4242 | oldContents: "# test\n", |
| 4243 | newContents: "", |
| 4244 | }); |
| 4245 | }), |
| 4246 | ); |
| 4247 | |
| 4248 | it.effect("loads merge-base and disk contents for Changes expansion", () => |
| 4249 | Effect.gen(function* () { |
| 4250 | const cwd = yield* makeTmpDir(); |
| 4251 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 4252 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4253 | yield* git(cwd, ["checkout", "-b", "feature/context"]); |
| 4254 | yield* writeTextFile(cwd, "README.md", "# branch change\nunchanged context\n"); |
| 4255 | yield* git(cwd, ["add", "README.md"]); |
| 4256 | yield* git(cwd, ["commit", "-m", "change readme"]); |
| 4257 | yield* writeTextFile(cwd, "README.md", "# dirty change\nunchanged context\n"); |
| 4258 | |
| 4259 | const contents = yield* driver.getReviewDiffFileContents( |
| 4260 | makeReviewDiffFileContentsInput(cwd, { |
| 4261 | sourceKind: "branch-range", |
| 4262 | baseRef: initialBranch, |
| 4263 | headRef: "feature/context", |
| 4264 | }), |
| 4265 | ); |
| 4266 | |
| 4267 | assert.strictEqual(contents.oldContents, "# test\n"); |
| 4268 | assert.strictEqual(contents.newContents, "# dirty change\nunchanged context\n"); |
| 4269 | }), |
| 4270 | ); |
| 4271 | |
| 4272 | it.effect("loads working-tree contents as Git diffs them under the ident attribute", () => |
| 4273 | Effect.gen(function* () { |
| 4274 | const cwd = yield* makeTmpDir(); |
| 4275 | yield* initRepoWithCommit(cwd); |
| 4276 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4277 | const fileSystem = yield* FileSystem.FileSystem; |
| 4278 | const filePath = (yield* Path.Path).join(cwd, "README.md"); |
| 4279 | const committed = "$Id$\nfirst\nsecond\n"; |
| 4280 | yield* writeTextFile(cwd, ".gitattributes", "README.md ident\n"); |
| 4281 | yield* writeTextFile(cwd, "README.md", committed); |
| 4282 | yield* writeTextFile(cwd, "PLAIN.md", "plain\n"); |
| 4283 | yield* git(cwd, ["add", "."]); |
| 4284 | yield* git(cwd, ["commit", "-m", "add ident keyword"]); |
| 4285 | // Checkout smudges the keyword to `$Id: <blob> $`. |
| 4286 | yield* fileSystem.remove(filePath); |
| 4287 | yield* git(cwd, ["checkout-index", "--force", "README.md"]); |
| 4288 | const smudged = yield* fileSystem.readFileString(filePath); |
| 4289 | assert.match(smudged, /^\$Id: [0-9a-f]{40} \$\n/); |
| 4290 | yield* writeTextFile(cwd, "README.md", smudged.replace("first", "edited")); |
| 4291 | yield* writeTextFile(cwd, "PLAIN.md", "$Id: literal $\n"); |
| 4292 | const disk = yield* fileSystem.readFile(filePath); |
| 4293 | |
| 4294 | const contents = yield* driver.getReviewDiffFileContents( |
| 4295 | makeReviewDiffFileContentsInput(cwd), |
| 4296 | ); |
| 4297 | const plain = yield* driver.getReviewDiffFileContents( |
| 4298 | makeReviewDiffFileContentsInput(cwd, { oldPath: "PLAIN.md", newPath: "PLAIN.md" }), |
| 4299 | ); |
| 4300 | |
| 4301 | assert.deepStrictEqual(contents, { |
| 4302 | oldContents: committed, |
| 4303 | newContents: "$Id$\nedited\nsecond\n", |
| 4304 | }); |
| 4305 | assert.strictEqual(plain.newContents, "$Id: literal $\n"); |
| 4306 | yield* writeTextFile(cwd, "README.md", "$Id: x $Id: y $\n"); |
| 4307 | const sharedDollar = yield* driver.getReviewDiffFileContents( |
| 4308 | makeReviewDiffFileContentsInput(cwd), |
| 4309 | ); |
| 4310 | assert.strictEqual(sharedDollar.newContents, "$Id$Id: y $\n"); |
| 4311 | yield* git(cwd, ["config", "filter.unrelated.clean", "touch filter-ran; cat"]); |
| 4312 | yield* writeTextFile(cwd, ".gitattributes", "README.md ident text eol=lf\n"); |
| 4313 | yield* writeTextFile( |
| 4314 | cwd, |
| 4315 | "README.md", |
| 4316 | smudged.replace("first", "edited").replaceAll("\n", "\r\n"), |
| 4317 | ); |
| 4318 | const crlf = yield* driver.getReviewDiffFileContents(makeReviewDiffFileContentsInput(cwd)); |
| 4319 | assert.strictEqual(crlf.newContents, "$Id$\r\nedited\r\nsecond\r\n"); |
| 4320 | yield* fileSystem.writeFile(filePath, disk); |
| 4321 | yield* writeTextFile(cwd, ".gitattributes", "README.md ident=set\n"); |
| 4322 | const literal = yield* driver.getReviewDiffFileContents( |
| 4323 | makeReviewDiffFileContentsInput(cwd), |
| 4324 | ); |
| 4325 | assert.strictEqual(literal.newContents, smudged.replace("first", "edited")); |
| 4326 | yield* writeTextFile(cwd, ".gitattributes", "README.md ident filter=probe\n"); |
| 4327 | yield* git(cwd, ["config", "filter.probe.clean", "touch filter-ran; cat"]); |
| 4328 | const filtered = yield* driver.getReviewDiffFileContents( |
| 4329 | makeReviewDiffFileContentsInput(cwd), |
| 4330 | ); |
| 4331 | assert.strictEqual(filtered.newContents, literal.newContents); |
| 4332 | yield* writeTextFile(cwd, ".gitattributes", "README.md ident filter=unspecified\n"); |
| 4333 | yield* git(cwd, ["config", "filter.unspecified.clean", "touch filter-ran; cat"]); |
| 4334 | const reservedFilter = yield* driver.getReviewDiffFileContents( |
| 4335 | makeReviewDiffFileContentsInput(cwd), |
| 4336 | ); |
| 4337 | assert.strictEqual(reservedFilter.newContents, literal.newContents); |
| 4338 | assert.isFalse(yield* fileSystem.exists((yield* Path.Path).join(cwd, "filter-ran"))); |
| 4339 | assert.deepStrictEqual(yield* fileSystem.readFile(filePath), disk); |
| 4340 | }), |
| 4341 | ); |
| 4342 | |
| 4343 | it.effect("Changes combines commits, uncommitted edits, and untracked files", () => |
| 4344 | Effect.gen(function* () { |
| 4345 | const cwd = yield* makeTmpDir(); |
| 4346 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 4347 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4348 | const sourceFiles = ( |
| 4349 | preview: ReviewDiffPreviewResult, |
| 4350 | kind: "working-tree" | "branch-range", |
| 4351 | ) => preview.sources.find((source) => source.kind === kind)!.files; |
| 4352 | yield* git(cwd, ["checkout", "-b", "feature/combined"]); |
| 4353 | yield* writeTextFile(cwd, "README.md", "# test\ncommitted\n"); |
| 4354 | yield* git(cwd, ["commit", "-am", "commit edit"]); |
| 4355 | |
| 4356 | const clean = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); |
| 4357 | assert.deepStrictEqual(sourceFiles(clean, "working-tree"), []); |
| 4358 | assert.deepStrictEqual(sourceFiles(clean, "branch-range"), [ |
| 4359 | { |
| 4360 | path: "README.md", |
| 4361 | previousPath: null, |
| 4362 | changeType: "change", |
| 4363 | additions: 1, |
| 4364 | deletions: 0, |
| 4365 | }, |
| 4366 | ]); |
| 4367 | |
| 4368 | yield* writeTextFile(cwd, "README.md", "# test\ncommitted\ndirty\n"); |
| 4369 | yield* writeTextFile(cwd, "new.txt", "new\n"); |
| 4370 | const dirty = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); |
| 4371 | const changes = dirty.sources.find((source) => source.kind === "branch-range")!; |
| 4372 | assert.deepStrictEqual(changes.files, [ |
| 4373 | { |
| 4374 | path: "README.md", |
| 4375 | previousPath: null, |
| 4376 | changeType: "change", |
| 4377 | additions: 2, |
| 4378 | deletions: 0, |
| 4379 | }, |
| 4380 | { path: "new.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, |
| 4381 | ]); |
| 4382 | assert.strictEqual(changes.diff.match(/^diff --git a\/README\.md /gm)?.length, 1); |
| 4383 | assert.include(changes.diff, "+dirty"); |
| 4384 | assert.deepStrictEqual(sourceFiles(dirty, "working-tree"), [ |
| 4385 | { |
| 4386 | path: "README.md", |
| 4387 | previousPath: null, |
| 4388 | changeType: "change", |
| 4389 | additions: 1, |
| 4390 | deletions: 0, |
| 4391 | }, |
| 4392 | { path: "new.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, |
| 4393 | ]); |
| 4394 | }), |
| 4395 | ); |
| 4396 | |
| 4397 | it.effect("Changes on the default branch compares with its remote copy", () => |
| 4398 | Effect.gen(function* () { |
| 4399 | const cwd = yield* makeTmpDir(); |
| 4400 | const remote = yield* makeTmpDir(); |
| 4401 | yield* initRepoWithCommit(cwd); |
| 4402 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4403 | yield* git(cwd, ["branch", "-M", "main"]); |
| 4404 | yield* writeTextFile(cwd, "unpushed.txt", "unpushed\n"); |
| 4405 | yield* git(cwd, ["add", "unpushed.txt"]); |
| 4406 | yield* git(cwd, ["commit", "-m", "unpushed"]); |
| 4407 | |
| 4408 | const local = yield* driver.getReviewDiffPreview({ cwd }); |
| 4409 | const localChanges = local.sources.find((source) => source.kind === "branch-range")!; |
| 4410 | assert.isNull(localChanges.baseRef); |
| 4411 | assert.deepStrictEqual(localChanges.files, []); |
| 4412 | |
| 4413 | yield* git(remote, ["init", "--bare"]); |
| 4414 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 4415 | yield* git(cwd, ["push", "origin", "HEAD~1:refs/heads/main"]); |
| 4416 | yield* git(cwd, ["fetch", "origin"]); |
| 4417 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4418 | const changes = preview.sources.find((source) => source.kind === "branch-range")!; |
| 4419 | assert.strictEqual(changes.baseRef, "origin/main"); |
| 4420 | assert.deepStrictEqual(changes.files, [ |
| 4421 | { |
| 4422 | path: "unpushed.txt", |
| 4423 | previousPath: null, |
| 4424 | changeType: "new", |
| 4425 | additions: 1, |
| 4426 | deletions: 0, |
| 4427 | }, |
| 4428 | ]); |
| 4429 | }), |
| 4430 | ); |
| 4431 | |
| 4432 | it.effect("honors configured remote-qualified bases for Changes and ahead counts", () => |
| 4433 | Effect.gen(function* () { |
| 4434 | const cwd = yield* makeTmpDir(); |
| 4435 | const fork = yield* makeTmpDir(); |
| 4436 | const upstream = yield* makeTmpDir(); |
| 4437 | yield* initRepoWithCommit(cwd); |
| 4438 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4439 | yield* git(cwd, ["branch", "-M", "main"]); |
| 4440 | yield* git(fork, ["init", "--bare"]); |
| 4441 | yield* git(upstream, ["init", "--bare"]); |
| 4442 | yield* git(cwd, ["remote", "add", "origin", fork]); |
| 4443 | yield* git(cwd, ["remote", "add", "upstream", upstream]); |
| 4444 | yield* git(cwd, ["remote", "add", "canonical/team", upstream]); |
| 4445 | yield* git(cwd, ["push", "origin", "main"]); |
| 4446 | yield* writeTextFile(cwd, "upstream.txt", "unrelated upstream work\n"); |
| 4447 | yield* git(cwd, ["add", "upstream.txt"]); |
| 4448 | yield* git(cwd, ["commit", "-m", "upstream work"]); |
| 4449 | yield* git(cwd, ["push", "upstream", "main"]); |
| 4450 | yield* git(cwd, ["fetch", "canonical/team"]); |
| 4451 | yield* git(cwd, ["branch", "release/v2"]); |
| 4452 | yield* git(cwd, ["checkout", "-b", "feature/configured-base"]); |
| 4453 | yield* writeTextFile(cwd, "feature.txt", "intended branch change\n"); |
| 4454 | yield* git(cwd, ["add", "feature.txt"]); |
| 4455 | yield* git(cwd, ["commit", "-m", "feature work"]); |
| 4456 | |
| 4457 | for (const baseRef of ["upstream/main", "canonical/team/main", "release/v2"]) { |
| 4458 | yield* git(cwd, ["config", "branch.feature/configured-base.gh-merge-base", baseRef]); |
| 4459 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4460 | assert.deepStrictEqual(status.branchChanges, { baseRef, insertions: 1, deletions: 0 }); |
| 4461 | assert.strictEqual(status.aheadCount, 1); |
| 4462 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4463 | const changes = preview.sources.find((source) => source.kind === "branch-range")!; |
| 4464 | assert.strictEqual(changes.baseRef, baseRef); |
| 4465 | assert.deepStrictEqual(changes.files, [ |
| 4466 | { |
| 4467 | path: "feature.txt", |
| 4468 | previousPath: null, |
| 4469 | changeType: "new", |
| 4470 | additions: 1, |
| 4471 | deletions: 0, |
| 4472 | }, |
| 4473 | ]); |
| 4474 | } |
| 4475 | |
| 4476 | for (const baseRef of ["origin/main", "upstream/missing", "main"]) { |
| 4477 | yield* git(cwd, ["config", "branch.feature/configured-base.gh-merge-base", baseRef]); |
| 4478 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4479 | assert.deepStrictEqual(status.branchChanges, { |
| 4480 | baseRef: "origin/main", |
| 4481 | insertions: 2, |
| 4482 | deletions: 0, |
| 4483 | }); |
| 4484 | assert.strictEqual(status.aheadCount, 2); |
| 4485 | } |
| 4486 | |
| 4487 | yield* git(cwd, [ |
| 4488 | "config", |
| 4489 | "branch.feature/configured-base.gh-merge-base", |
| 4490 | "refs/remotes/upstream/main", |
| 4491 | ]); |
| 4492 | yield* writeTextFile(cwd, "upstream.txt", "feature edits upstream file\n"); |
| 4493 | for (const shadowRef of ["refs/heads/upstream/main", "refs/tags/upstream/main"]) { |
| 4494 | yield* git(cwd, ["update-ref", shadowRef, "HEAD~2"]); |
| 4495 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4496 | assert.deepStrictEqual(status.branchChanges, { |
| 4497 | baseRef: "refs/remotes/upstream/main", |
| 4498 | insertions: 2, |
| 4499 | deletions: 1, |
| 4500 | }); |
| 4501 | assert.strictEqual(status.aheadCount, 1); |
| 4502 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4503 | const changes = preview.sources.find((source) => source.kind === "branch-range")!; |
| 4504 | assert.strictEqual(changes.baseRef, "refs/remotes/upstream/main"); |
| 4505 | assert.deepStrictEqual(changes.files, [ |
| 4506 | { |
| 4507 | path: "feature.txt", |
| 4508 | previousPath: null, |
| 4509 | changeType: "new", |
| 4510 | additions: 1, |
| 4511 | deletions: 0, |
| 4512 | }, |
| 4513 | { |
| 4514 | path: "upstream.txt", |
| 4515 | previousPath: null, |
| 4516 | changeType: "change", |
| 4517 | additions: 1, |
| 4518 | deletions: 1, |
| 4519 | }, |
| 4520 | ]); |
| 4521 | const contents = yield* driver.getReviewDiffFileContents( |
| 4522 | makeReviewDiffFileContentsInput(cwd, { |
| 4523 | sourceKind: "branch-range", |
| 4524 | baseRef: changes.baseRef, |
| 4525 | headRef: "feature/configured-base", |
| 4526 | oldPath: "upstream.txt", |
| 4527 | newPath: "upstream.txt", |
| 4528 | }), |
| 4529 | ); |
| 4530 | assert.deepStrictEqual(contents, { |
| 4531 | oldContents: "unrelated upstream work\n", |
| 4532 | newContents: "feature edits upstream file\n", |
| 4533 | }); |
| 4534 | yield* git(cwd, ["update-ref", "-d", shadowRef]); |
| 4535 | } |
| 4536 | }), |
| 4537 | ); |
| 4538 | |
| 4539 | it.effect("compares a plain recorded base with the remote that base branch tracks", () => |
| 4540 | Effect.gen(function* () { |
| 4541 | const cwd = yield* makeTmpDir(); |
| 4542 | const fork = yield* makeTmpDir(); |
| 4543 | const upstream = yield* makeTmpDir(); |
| 4544 | yield* initRepoWithCommit(cwd); |
| 4545 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4546 | yield* git(cwd, ["branch", "-M", "main"]); |
| 4547 | yield* git(fork, ["init", "--bare"]); |
| 4548 | yield* git(upstream, ["init", "--bare"]); |
| 4549 | yield* git(cwd, ["remote", "add", "origin", fork]); |
| 4550 | yield* git(cwd, ["remote", "add", "upstream", upstream]); |
| 4551 | yield* git(cwd, ["push", "origin", "main"]); |
| 4552 | yield* writeTextFile(cwd, "upstream.txt", "unrelated upstream work\n"); |
| 4553 | yield* git(cwd, ["add", "upstream.txt"]); |
| 4554 | yield* git(cwd, ["commit", "-m", "upstream work"]); |
| 4555 | yield* git(cwd, ["push", "-u", "upstream", "main"]); |
| 4556 | yield* git(cwd, ["checkout", "-b", "feature/from-local-main"]); |
| 4557 | yield* git(cwd, ["config", "branch.feature/from-local-main.t3-merge-base", "main"]); |
| 4558 | yield* writeTextFile(cwd, "feature.txt", "intended branch change\n"); |
| 4559 | yield* git(cwd, ["add", "feature.txt"]); |
| 4560 | yield* git(cwd, ["commit", "-m", "feature work"]); |
| 4561 | |
| 4562 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4563 | assert.deepStrictEqual(status.branchChanges, { |
| 4564 | baseRef: "upstream/main", |
| 4565 | insertions: 1, |
| 4566 | deletions: 0, |
| 4567 | }); |
| 4568 | assert.strictEqual(status.aheadCount, 1); |
| 4569 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4570 | const changes = preview.sources.find((source) => source.kind === "branch-range")!; |
| 4571 | assert.strictEqual(changes.baseRef, "upstream/main"); |
| 4572 | assert.deepStrictEqual( |
| 4573 | changes.files?.map((file) => file.path), |
| 4574 | ["feature.txt"], |
| 4575 | ); |
| 4576 | }), |
| 4577 | ); |
| 4578 | |
| 4579 | it.effect("does not guess a Changes base for a branch renamed during the status read", () => |
| 4580 | Effect.gen(function* () { |
| 4581 | const cwd = yield* makeTmpDir(); |
| 4582 | const fork = yield* makeTmpDir(); |
| 4583 | const upstream = yield* makeTmpDir(); |
| 4584 | yield* initRepoWithCommit(cwd); |
| 4585 | yield* git(cwd, ["branch", "-M", "main"]); |
| 4586 | yield* git(fork, ["init", "--bare"]); |
| 4587 | yield* git(upstream, ["init", "--bare"]); |
| 4588 | yield* git(cwd, ["remote", "add", "origin", fork]); |
| 4589 | yield* git(cwd, ["remote", "add", "upstream", upstream]); |
| 4590 | yield* git(cwd, ["push", "origin", "main"]); |
| 4591 | yield* writeTextFile(cwd, "upstream.txt", "work missing from the fork\n"); |
| 4592 | yield* git(cwd, ["add", "upstream.txt"]); |
| 4593 | yield* git(cwd, ["commit", "-m", "upstream work"]); |
| 4594 | yield* git(cwd, ["push", "upstream", "main"]); |
| 4595 | yield* git(cwd, ["fetch", "origin"]); |
| 4596 | yield* git(cwd, ["fetch", "upstream"]); |
| 4597 | yield* git(cwd, ["checkout", "-b", "t3/temporary"]); |
| 4598 | yield* git(cwd, ["config", "branch.t3/temporary.t3-merge-base", "main"]); |
| 4599 | yield* git(cwd, [ |
| 4600 | "config", |
| 4601 | "branch.t3/temporary.t3-merge-base-ref", |
| 4602 | "refs/remotes/upstream/main", |
| 4603 | ]); |
| 4604 | yield* writeTextFile(cwd, "feature.txt", "thread work\n"); |
| 4605 | |
| 4606 | const outer = yield* GitVcsDriver.GitVcsDriver; |
| 4607 | const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 4608 | const renameClaimed = yield* Ref.make(false); |
| 4609 | const renamed = yield* Deferred.make<void>(); |
| 4610 | // Rename after `git status` has read HEAD, as the thread launcher does after the first turn. |
| 4611 | // Base config reads start only after status completes; hold every one until the rename lands. |
| 4612 | const spawner = ChildProcessSpawner.make((command) => |
| 4613 | Effect.gen(function* () { |
| 4614 | if ( |
| 4615 | ChildProcess.isStandardCommand(command) && |
| 4616 | command.args[0] === "config" && |
| 4617 | !command.args.includes("status.showUntrackedFiles") |
| 4618 | ) { |
| 4619 | if (!(yield* Ref.getAndSet(renameClaimed, true))) { |
| 4620 | yield* git(cwd, ["branch", "-m", "t3/temporary", "feature/named"]).pipe( |
| 4621 | Effect.provideService(GitVcsDriver.GitVcsDriver, outer), |
| 4622 | Effect.orDie, |
| 4623 | ); |
| 4624 | yield* Deferred.succeed(renamed, undefined); |
| 4625 | } |
| 4626 | yield* Deferred.await(renamed); |
| 4627 | } |
| 4628 | return yield* delegate.spawn(command); |
| 4629 | }), |
| 4630 | ); |
| 4631 | const driver = yield* makeGitVcsDriverCore().pipe( |
| 4632 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 4633 | Effect.provide(layerServerConfig), |
| 4634 | ); |
| 4635 | |
| 4636 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4637 | |
| 4638 | assert.strictEqual(status.branch, "t3/temporary"); |
| 4639 | assert.deepStrictEqual(status.branchChanges, { |
| 4640 | baseRef: null, |
| 4641 | insertions: 1, |
| 4642 | deletions: 0, |
| 4643 | }); |
| 4644 | }), |
| 4645 | ); |
| 4646 | |
| 4647 | it.effect("keeps local branch bases consistent when tags share their names", () => |
| 4648 | Effect.gen(function* () { |
| 4649 | const cwd = yield* makeTmpDir(); |
| 4650 | yield* initRepoWithCommit(cwd); |
| 4651 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4652 | yield* git(cwd, ["branch", "-M", "main"]); |
| 4653 | const initialCommit = yield* git(cwd, ["rev-parse", "HEAD"]); |
| 4654 | yield* git(cwd, ["update-ref", "refs/tags/main", initialCommit]); |
| 4655 | yield* git(cwd, ["update-ref", "refs/tags/release/v2", initialCommit]); |
| 4656 | yield* writeTextFile(cwd, "README.md", "# test\nbase work\n"); |
| 4657 | yield* git(cwd, ["commit", "-am", "base work"]); |
| 4658 | yield* git(cwd, ["branch", "release/v2", "HEAD"]); |
| 4659 | yield* git(cwd, ["checkout", "-b", "feature/local-base", "HEAD"]); |
| 4660 | yield* writeTextFile(cwd, "README.md", "# test\nbase work\nfeature work\n"); |
| 4661 | yield* git(cwd, ["commit", "-am", "feature work"]); |
| 4662 | |
| 4663 | for (const configuredBase of [undefined, "main", "release/v2"]) { |
| 4664 | if (configuredBase !== undefined) { |
| 4665 | yield* git(cwd, ["config", "branch.feature/local-base.gh-merge-base", configuredBase]); |
| 4666 | } |
| 4667 | const baseRef = configuredBase ?? "main"; |
| 4668 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4669 | assert.deepStrictEqual(status.branchChanges, { baseRef, insertions: 1, deletions: 0 }); |
| 4670 | assert.strictEqual(status.aheadCount, 1); |
| 4671 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4672 | const changes = preview.sources.find((source) => source.kind === "branch-range")!; |
| 4673 | assert.strictEqual(changes.baseRef, baseRef); |
| 4674 | assert.deepStrictEqual(changes.files, [ |
| 4675 | { |
| 4676 | path: "README.md", |
| 4677 | previousPath: null, |
| 4678 | changeType: "change", |
| 4679 | additions: 1, |
| 4680 | deletions: 0, |
| 4681 | }, |
| 4682 | ]); |
| 4683 | const scoped = yield* driver.getReviewDiffPreview({ |
| 4684 | cwd, |
| 4685 | baseRef, |
| 4686 | file: { path: "README.md", previousPath: null, sourceKind: "branch-range" }, |
| 4687 | }); |
| 4688 | const scopedChanges = scoped.sources.find((source) => source.kind === "branch-range")!; |
| 4689 | assert.deepStrictEqual(scopedChanges.files, changes.files); |
| 4690 | assert.strictEqual(scopedChanges.diff, changes.diff); |
| 4691 | const contents = yield* driver.getReviewDiffFileContents( |
| 4692 | makeReviewDiffFileContentsInput(cwd, { |
| 4693 | sourceKind: "branch-range", |
| 4694 | baseRef: changes.baseRef, |
| 4695 | headRef: "feature/local-base", |
| 4696 | }), |
| 4697 | ); |
| 4698 | assert.deepStrictEqual(contents, { |
| 4699 | oldContents: "# test\nbase work\n", |
| 4700 | newContents: "# test\nbase work\nfeature work\n", |
| 4701 | }); |
| 4702 | } |
| 4703 | |
| 4704 | for (const baseRef of ["refs/tags/main", initialCommit, "HEAD~2"]) { |
| 4705 | const contents = yield* driver.getReviewDiffFileContents( |
| 4706 | makeReviewDiffFileContentsInput(cwd, { |
| 4707 | sourceKind: "branch-range", |
| 4708 | baseRef, |
| 4709 | headRef: "feature/local-base", |
| 4710 | }), |
| 4711 | ); |
| 4712 | assert.strictEqual(contents.oldContents, "# test\n"); |
| 4713 | } |
| 4714 | }), |
| 4715 | ); |
| 4716 | |
| 4717 | it.effect("Changes accepts an explicit base on a detached HEAD and rejects a bad one", () => |
| 4718 | Effect.gen(function* () { |
| 4719 | const cwd = yield* makeTmpDir(); |
| 4720 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 4721 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4722 | yield* git(cwd, ["checkout", "--detach"]); |
| 4723 | yield* writeTextFile(cwd, "detached.txt", "detached\n"); |
| 4724 | yield* git(cwd, ["add", "detached.txt"]); |
| 4725 | yield* git(cwd, ["commit", "-m", "detached work"]); |
| 4726 | |
| 4727 | const explicit = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); |
| 4728 | assert.deepStrictEqual( |
| 4729 | explicit.sources.find((source) => source.kind === "branch-range")!.files, |
| 4730 | [ |
| 4731 | { |
| 4732 | path: "detached.txt", |
| 4733 | previousPath: null, |
| 4734 | changeType: "new", |
| 4735 | additions: 1, |
| 4736 | deletions: 0, |
| 4737 | }, |
| 4738 | ], |
| 4739 | ); |
| 4740 | const implicit = yield* driver.getReviewDiffPreview({ cwd }); |
| 4741 | assert.deepStrictEqual( |
| 4742 | implicit.sources.find((source) => source.kind === "branch-range")!.files, |
| 4743 | [], |
| 4744 | ); |
| 4745 | const error = yield* driver |
| 4746 | .getReviewDiffPreview({ cwd, baseRef: "missing-base" }) |
| 4747 | .pipe(Effect.flip); |
| 4748 | assert.strictEqual(error.operation, "GitVcsDriver.resolveReviewMergeBase"); |
| 4749 | }), |
| 4750 | ); |
| 4751 | |
| 4752 | it.effect("Changes compares with the empty tree before the first commit", () => |
| 4753 | Effect.gen(function* () { |
| 4754 | const upstream = yield* makeTmpDir(); |
| 4755 | yield* initRepoWithCommit(upstream); |
| 4756 | yield* git(upstream, ["branch", "-M", "main"]); |
| 4757 | const cwd = yield* makeTmpDir(); |
| 4758 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4759 | yield* git(cwd, ["init", "-b", "main"]); |
| 4760 | yield* git(cwd, ["remote", "add", "origin", upstream]); |
| 4761 | yield* git(cwd, ["fetch", "origin"]); |
| 4762 | yield* writeTextFile(cwd, "new.txt", "one\ntwo\n"); |
| 4763 | |
| 4764 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4765 | const changes = preview.sources.find((source) => source.kind === "branch-range")!; |
| 4766 | assert.isNull(changes.baseRef); |
| 4767 | assert.deepStrictEqual(changes.files, [ |
| 4768 | { path: "new.txt", previousPath: null, changeType: "new", additions: 2, deletions: 0 }, |
| 4769 | ]); |
| 4770 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4771 | assert.deepStrictEqual(status.branchChanges, { |
| 4772 | baseRef: null, |
| 4773 | insertions: 2, |
| 4774 | deletions: 0, |
| 4775 | }); |
| 4776 | }), |
| 4777 | ); |
| 4778 | |
| 4779 | it.effect("Changes does not show newer base commits as deletions", () => |
| 4780 | Effect.gen(function* () { |
| 4781 | const cwd = yield* makeTmpDir(); |
| 4782 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 4783 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4784 | yield* git(cwd, ["checkout", "-b", "feature/rebased"]); |
| 4785 | yield* writeTextFile(cwd, "feature.txt", "feature\n"); |
| 4786 | yield* git(cwd, ["add", "feature.txt"]); |
| 4787 | yield* git(cwd, ["commit", "-m", "feature work"]); |
| 4788 | yield* git(cwd, ["checkout", initialBranch]); |
| 4789 | yield* writeTextFile(cwd, "upstream.txt", "upstream\n"); |
| 4790 | yield* git(cwd, ["add", "upstream.txt"]); |
| 4791 | yield* git(cwd, ["commit", "-m", "base moves"]); |
| 4792 | yield* git(cwd, ["checkout", "feature/rebased"]); |
| 4793 | |
| 4794 | for (const rebase of [false, true]) { |
| 4795 | if (rebase) yield* git(cwd, ["rebase", initialBranch]); |
| 4796 | const preview = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); |
| 4797 | assert.deepStrictEqual( |
| 4798 | preview.sources.find((source) => source.kind === "branch-range")!.files, |
| 4799 | [ |
| 4800 | { |
| 4801 | path: "feature.txt", |
| 4802 | previousPath: null, |
| 4803 | changeType: "new", |
| 4804 | additions: 1, |
| 4805 | deletions: 0, |
| 4806 | }, |
| 4807 | ], |
| 4808 | ); |
| 4809 | } |
| 4810 | }), |
| 4811 | ); |
| 4812 | }); |
| 4813 | |
| 4814 | describe("repository status", () => { |
| 4815 | it.effect("reads the current branch and upstream by name when other refs share them", () => |
| 4816 | Effect.gen(function* () { |
| 4817 | const cwd = yield* makeTmpDir(); |
| 4818 | const remote = yield* makeTmpDir("git-vcs-driver-remote-"); |
| 4819 | yield* initRepoWithCommit(cwd); |
| 4820 | yield* git(remote, ["init", "--bare"]); |
| 4821 | yield* git(cwd, ["remote", "add", "origin", remote]); |
| 4822 | yield* git(cwd, ["checkout", "-b", "release"]); |
| 4823 | yield* git(cwd, ["push", "-u", "origin", "release"]); |
| 4824 | yield* git(cwd, ["commit", "--allow-empty", "-m", "unpushed"]); |
| 4825 | yield* git(cwd, ["branch", "origin/release"]); |
| 4826 | yield* git(cwd, ["tag", "release"]); |
| 4827 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4828 | |
| 4829 | const remoteStatus = yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false }); |
| 4830 | assert.equal(remoteStatus.branch, "release"); |
| 4831 | assert.equal(remoteStatus.upstreamRef, "origin/release"); |
| 4832 | assert.equal(remoteStatus.aheadCount, 1); |
| 4833 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4834 | const branchRange = preview.sources.find((source) => source.kind === "branch-range"); |
| 4835 | assert.equal(branchRange?.headRef, "release"); |
| 4836 | }), |
| 4837 | ); |
| 4838 | |
| 4839 | it.effect("reports a local upstream without a slash and its divergence", () => |
| 4840 | Effect.gen(function* () { |
| 4841 | const cwd = yield* makeTmpDir(); |
| 4842 | yield* initRepoWithCommit(cwd); |
| 4843 | const initialBranch = yield* git(cwd, ["symbolic-ref", "--short", "HEAD"]); |
| 4844 | yield* git(cwd, ["branch", "feature"]); |
| 4845 | yield* git(cwd, ["commit", "--allow-empty", "-m", "advance base"]); |
| 4846 | yield* git(cwd, ["checkout", "feature"]); |
| 4847 | yield* git(cwd, ["branch", `--set-upstream-to=${initialBranch}`]); |
| 4848 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4849 | |
| 4850 | const remoteStatus = yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false }); |
| 4851 | assert.equal(remoteStatus.upstreamRef, initialBranch); |
| 4852 | assert.equal(remoteStatus.hasUpstream, true); |
| 4853 | assert.equal(remoteStatus.aheadCount, 0); |
| 4854 | assert.equal(remoteStatus.behindCount, 1); |
| 4855 | }), |
| 4856 | ); |
| 4857 | |
| 4858 | it.effect("does not open a project folder laid out as a bare repository", () => |
| 4859 | Effect.gen(function* () { |
| 4860 | const cwd = yield* makeTmpDir(); |
| 4861 | yield* initRepoWithCommit(cwd); |
| 4862 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4863 | const fileSystem = yield* FileSystem.FileSystem; |
| 4864 | const pathService = yield* Path.Path; |
| 4865 | // Plain files a project save or a clone can hold. Git discovers them as a bare repository. |
| 4866 | const planted = pathService.join(cwd, "planted"); |
| 4867 | yield* writeTextFile(planted, "HEAD", "ref: refs/heads/main\n"); |
| 4868 | yield* writeTextFile(planted, "objects/info/keep", ""); |
| 4869 | yield* writeTextFile(planted, "refs/heads/keep", ""); |
| 4870 | yield* writeTextFile( |
| 4871 | planted, |
| 4872 | "config", |
| 4873 | '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n', |
| 4874 | ); |
| 4875 | |
| 4876 | yield* Effect.exit(driver.statusDetailsLocal(planted)); |
| 4877 | assert.isFalse(yield* fileSystem.exists(pathService.join(planted, "fsmonitor-runs"))); |
| 4878 | assert.isTrue((yield* driver.statusDetailsLocal(cwd)).isRepo); |
| 4879 | }), |
| 4880 | ); |
| 4881 | |
| 4882 | it.effect("reads Changes totals and review diffs without minimizing", () => |
| 4883 | Effect.gen(function* () { |
| 4884 | const cwd = yield* makeTmpDir(); |
| 4885 | const { initialBranch } = yield* initRepoWithCommit(cwd); |
| 4886 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4887 | yield* git(cwd, ["config", "diff.algorithm", "myers"]); |
| 4888 | // Repeated lines make the default and minimal algorithms choose different edits. |
| 4889 | const lines = Array.from({ length: 2000 }, (_, index) => index); |
| 4890 | yield* writeTextFile( |
| 4891 | cwd, |
| 4892 | "repeated.txt", |
| 4893 | lines.map((index) => `${(index ^ (index >> 3)) % 16}\n`).join(""), |
| 4894 | ); |
| 4895 | yield* git(cwd, ["add", "."]); |
| 4896 | yield* git(cwd, ["commit", "-m", "repeated lines"]); |
| 4897 | yield* git(cwd, ["checkout", "-b", "feature/totals"]); |
| 4898 | yield* writeTextFile( |
| 4899 | cwd, |
| 4900 | "repeated.txt", |
| 4901 | lines.map((index) => `${(index ^ (index >> 5)) % 16}\n`).join(""), |
| 4902 | ); |
| 4903 | const defaultStat = yield* git(cwd, ["diff", "--numstat", "HEAD", "--"]); |
| 4904 | const minimalStat = yield* git(cwd, ["diff", "--minimal", "--numstat", "HEAD", "--"]); |
| 4905 | assert.notEqual(defaultStat, minimalStat); |
| 4906 | const [insertions, deletions] = defaultStat.split("\t"); |
| 4907 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4908 | assert.deepStrictEqual(status.branchChanges, { |
| 4909 | baseRef: initialBranch, |
| 4910 | insertions: Number(insertions), |
| 4911 | deletions: Number(deletions), |
| 4912 | }); |
| 4913 | |
| 4914 | const defaultPatch = yield* git(cwd, [ |
| 4915 | "diff", |
| 4916 | "--patch", |
| 4917 | "--no-color", |
| 4918 | "--no-ext-diff", |
| 4919 | "--no-textconv", |
| 4920 | "--src-prefix=a/", |
| 4921 | "--dst-prefix=b/", |
| 4922 | "HEAD", |
| 4923 | "--", |
| 4924 | ]); |
| 4925 | const preview = yield* driver.getReviewDiffPreview({ cwd }); |
| 4926 | for (const source of preview.sources) { |
| 4927 | assert.deepStrictEqual(source.files, [ |
| 4928 | { |
| 4929 | path: "repeated.txt", |
| 4930 | previousPath: null, |
| 4931 | changeType: "change", |
| 4932 | additions: Number(insertions), |
| 4933 | deletions: Number(deletions), |
| 4934 | }, |
| 4935 | ]); |
| 4936 | assert.strictEqual(source.diff.trim(), defaultPatch); |
| 4937 | } |
| 4938 | }), |
| 4939 | ); |
| 4940 | |
| 4941 | it.effect.skipIf(!symlinksSupported)( |
| 4942 | "lists the real repository through a symlink when a decoy repo occupies the lexical common dir", |
| 4943 | () => |
| 4944 | Effect.gen(function* () { |
| 4945 | const fileSystem = yield* FileSystem.FileSystem; |
| 4946 | const pathService = yield* Path.Path; |
| 4947 | const sandbox = yield* makeTmpDir("git-symlink-subdir-"); |
| 4948 | yield* initRepoWithCommit(sandbox); |
| 4949 | yield* git(sandbox, ["branch", "-M", "decoy-only"]); |
| 4950 | const repo = pathService.join(sandbox, "repo"); |
| 4951 | const link = pathService.join(sandbox, "nest", "link"); |
| 4952 | yield* fileSystem.makeDirectory(pathService.join(repo, "sub", "dir"), { |
| 4953 | recursive: true, |
| 4954 | }); |
| 4955 | yield* fileSystem.makeDirectory(pathService.dirname(link), { recursive: true }); |
| 4956 | yield* fileSystem.symlink(pathService.join(repo, "sub", "dir"), link); |
| 4957 | |
| 4958 | yield* initRepoWithCommit(repo); |
| 4959 | yield* git(repo, ["checkout", "-b", "real-only"]); |
| 4960 | |
| 4961 | // The decoy must exist before the first lookup, which caches repository paths. |
| 4962 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4963 | const refs = yield* driver.listRefs({ cwd: link }); |
| 4964 | assert.isTrue(refs.isRepo); |
| 4965 | assert.isFalse(refs.refs.some((ref) => ref.name === "decoy-only")); |
| 4966 | assert.isTrue(refs.refs.some((ref) => ref.name === "real-only")); |
| 4967 | |
| 4968 | yield* driver.createWorktree({ |
| 4969 | cwd: link, |
| 4970 | path: pathService.join(yield* makeTmpDir("git-worktrees-"), "real"), |
| 4971 | refName: "real-only", |
| 4972 | newRefName: "feature/real-created", |
| 4973 | }); |
| 4974 | const createdRefs = yield* driver.listRefs({ cwd: link }); |
| 4975 | assert.isFalse(createdRefs.isAtRepositoryRoot); |
| 4976 | assert.isFalse(createdRefs.refs.some((ref) => ref.name === "decoy-only")); |
| 4977 | assert.isTrue(createdRefs.refs.some((ref) => ref.name === "real-only" && ref.current)); |
| 4978 | assert.isTrue(createdRefs.refs.some((ref) => ref.name === "feature/real-created")); |
| 4979 | }), |
| 4980 | ); |
| 4981 | |
| 4982 | it.effect("reads Changes totals without rewriting the real index for stat-dirty files", () => |
| 4983 | Effect.gen(function* () { |
| 4984 | const cwd = yield* makeTmpDir(); |
| 4985 | yield* initRepoWithCommit(cwd); |
| 4986 | const driver = yield* GitVcsDriver.GitVcsDriver; |
| 4987 | const fileSystem = yield* FileSystem.FileSystem; |
| 4988 | const path = yield* Path.Path; |
| 4989 | yield* writeTextFile(cwd, "tracked.txt", "same content\n"); |
| 4990 | yield* git(cwd, ["add", "tracked.txt"]); |
| 4991 | yield* git(cwd, ["commit", "-m", "add tracked file"]); |
| 4992 | yield* fileSystem.utimes(path.join(cwd, "tracked.txt"), 1_000_000_000, 1_000_000_000); |
| 4993 | const indexPath = path.join(cwd, ".git", "index"); |
| 4994 | const originalIndex = yield* fileSystem.readFile(indexPath); |
| 4995 | |
| 4996 | const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); |
| 4997 | |
| 4998 | assert.strictEqual(status.branchChanges?.insertions, 0); |
| 4999 | assert.strictEqual(status.branchChanges?.deletions, 0); |
| 5000 | // Writing the index takes index.lock, which makes concurrent user Git writes fail. |
Showing first 5,000 of 10,302 lines.
View raw