| ... | ... | @@ -294,7 +294,7 @@ function trace2ChildKey(record: Record<string, unknown>): string | null { |
| 294 | 294 | |
| 295 | 295 | const Trace2Record = Schema.Record(Schema.String, Schema.Unknown); |
| 296 | 296 | |
| 297 | | const createTrace2Monitor = Effect.fn(function* ( |
| 297 | const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( |
| 298 | 298 | input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">, |
| 299 | 299 | progress: ExecuteGitProgress | undefined, |
| 300 | 300 | ): Effect.fn.Return< |
| ... | ... | @@ -321,61 +321,58 @@ const createTrace2Monitor = Effect.fn(function* ( |
| 321 | 321 | remainder: "", |
| 322 | 322 | }); |
| 323 | 323 | |
| 324 | | const handleTraceLine = (line: string) => |
| 325 | | Effect.gen(function* () { |
| 326 | | const trimmedLine = line.trim(); |
| 327 | | if (trimmedLine.length === 0) { |
| 328 | | return; |
| 329 | | } |
| 324 | const handleTraceLine = Effect.fn("handleTraceLine")(function* (line: string) { |
| 325 | const trimmedLine = line.trim(); |
| 326 | if (trimmedLine.length === 0) { |
| 327 | return; |
| 328 | } |
| 330 | 329 | |
| 331 | | const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine); |
| 332 | | if (Result.isFailure(traceRecord)) { |
| 333 | | yield* Effect.logDebug( |
| 334 | | `GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`, |
| 335 | | traceRecord.failure, |
| 336 | | ); |
| 337 | | return; |
| 338 | | } |
| 330 | const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine); |
| 331 | if (Result.isFailure(traceRecord)) { |
| 332 | yield* Effect.logDebug( |
| 333 | `GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`, |
| 334 | traceRecord.failure, |
| 335 | ); |
| 336 | return; |
| 337 | } |
| 339 | 338 | |
| 340 | | if (traceRecord.success.child_class !== "hook") { |
| 341 | | return; |
| 342 | | } |
| 339 | if (traceRecord.success.child_class !== "hook") { |
| 340 | return; |
| 341 | } |
| 343 | 342 | |
| 344 | | const event = traceRecord.success.event; |
| 345 | | const childKey = trace2ChildKey(traceRecord.success); |
| 346 | | if (childKey === null) { |
| 347 | | return; |
| 348 | | } |
| 349 | | const started = hookStartByChildKey.get(childKey); |
| 350 | | const hookNameFromEvent = |
| 351 | | typeof traceRecord.success.hook_name === "string" |
| 352 | | ? traceRecord.success.hook_name.trim() |
| 353 | | : ""; |
| 354 | | const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? ""); |
| 355 | | if (hookName.length === 0) { |
| 356 | | return; |
| 357 | | } |
| 343 | const event = traceRecord.success.event; |
| 344 | const childKey = trace2ChildKey(traceRecord.success); |
| 345 | if (childKey === null) { |
| 346 | return; |
| 347 | } |
| 348 | const started = hookStartByChildKey.get(childKey); |
| 349 | const hookNameFromEvent = |
| 350 | typeof traceRecord.success.hook_name === "string" ? traceRecord.success.hook_name.trim() : ""; |
| 351 | const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? ""); |
| 352 | if (hookName.length === 0) { |
| 353 | return; |
| 354 | } |
| 358 | 355 | |
| 359 | | if (event === "child_start") { |
| 360 | | hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); |
| 361 | | if (progress.onHookStarted) { |
| 362 | | yield* progress.onHookStarted(hookName); |
| 363 | | } |
| 364 | | return; |
| 356 | if (event === "child_start") { |
| 357 | hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); |
| 358 | if (progress.onHookStarted) { |
| 359 | yield* progress.onHookStarted(hookName); |
| 365 | 360 | } |
| 361 | return; |
| 362 | } |
| 366 | 363 | |
| 367 | | if (event === "child_exit") { |
| 368 | | hookStartByChildKey.delete(childKey); |
| 369 | | if (progress.onHookFinished) { |
| 370 | | const code = traceRecord.success.code; |
| 371 | | yield* progress.onHookFinished({ |
| 372 | | hookName: started?.hookName ?? hookName, |
| 373 | | exitCode: typeof code === "number" && Number.isInteger(code) ? code : null, |
| 374 | | durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null, |
| 375 | | }); |
| 376 | | } |
| 364 | if (event === "child_exit") { |
| 365 | hookStartByChildKey.delete(childKey); |
| 366 | if (progress.onHookFinished) { |
| 367 | const code = traceRecord.success.code; |
| 368 | yield* progress.onHookFinished({ |
| 369 | hookName: started?.hookName ?? hookName, |
| 370 | exitCode: typeof code === "number" && Number.isInteger(code) ? code : null, |
| 371 | durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null, |
| 372 | }); |
| 377 | 373 | } |
| 378 | | }); |
| 374 | } |
| 375 | }); |
| 379 | 376 | |
| 380 | 377 | const deltaMutex = yield* Semaphore.make(1); |
| 381 | 378 | const readTraceDelta = deltaMutex.withPermit( |
| ... | ... | @@ -418,21 +415,21 @@ const createTrace2Monitor = Effect.fn(function* ( |
| 418 | 415 | return readTraceDelta; |
| 419 | 416 | }).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); |
| 420 | 417 | |
| 421 | | yield* Effect.addFinalizer(() => |
| 422 | | Effect.gen(function* () { |
| 423 | | yield* readTraceDelta; |
| 424 | | const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [ |
| 425 | | remainder.trim(), |
| 426 | | { |
| 427 | | processedChars, |
| 428 | | remainder: "", |
| 429 | | }, |
| 430 | | ]); |
| 431 | | if (finalLine.length > 0) { |
| 432 | | yield* handleTraceLine(finalLine); |
| 433 | | } |
| 434 | | }), |
| 435 | | ); |
| 418 | const finalizeTrace2Monitor = Effect.fn("finalizeTrace2Monitor")(function* () { |
| 419 | yield* readTraceDelta; |
| 420 | const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [ |
| 421 | remainder.trim(), |
| 422 | { |
| 423 | processedChars, |
| 424 | remainder: "", |
| 425 | }, |
| 426 | ]); |
| 427 | if (finalLine.length > 0) { |
| 428 | yield* handleTraceLine(finalLine); |
| 429 | } |
| 430 | }); |
| 431 | |
| 432 | yield* Effect.addFinalizer(finalizeTrace2Monitor); |
| 436 | 433 | |
| 437 | 434 | return { |
| 438 | 435 | env: { |
| ... | ... | @@ -442,7 +439,7 @@ const createTrace2Monitor = Effect.fn(function* ( |
| 442 | 439 | }; |
| 443 | 440 | }); |
| 444 | 441 | |
| 445 | | const collectOutput = Effect.fn(function* <E>( |
| 442 | const collectOutput = Effect.fn("collectOutput")(function* <E>( |
| 446 | 443 | input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">, |
| 447 | 444 | stream: Stream.Stream<Uint8Array, E>, |
| 448 | 445 | maxOutputBytes: number, |
| ... | ... | @@ -455,55 +452,56 @@ const collectOutput = Effect.fn(function* <E>( |
| 455 | 452 | let lineBuffer = ""; |
| 456 | 453 | let truncated = false; |
| 457 | 454 | |
| 458 | | const emitCompleteLines = (flush: boolean) => |
| 459 | | Effect.gen(function* () { |
| 460 | | let newlineIndex = lineBuffer.indexOf("\n"); |
| 461 | | while (newlineIndex >= 0) { |
| 462 | | const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, ""); |
| 463 | | lineBuffer = lineBuffer.slice(newlineIndex + 1); |
| 464 | | if (line.length > 0 && onLine) { |
| 465 | | yield* onLine(line); |
| 466 | | } |
| 467 | | newlineIndex = lineBuffer.indexOf("\n"); |
| 455 | const emitCompleteLines = Effect.fn("emitCompleteLines")(function* (flush: boolean) { |
| 456 | let newlineIndex = lineBuffer.indexOf("\n"); |
| 457 | while (newlineIndex >= 0) { |
| 458 | const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, ""); |
| 459 | lineBuffer = lineBuffer.slice(newlineIndex + 1); |
| 460 | if (line.length > 0 && onLine) { |
| 461 | yield* onLine(line); |
| 468 | 462 | } |
| 463 | newlineIndex = lineBuffer.indexOf("\n"); |
| 464 | } |
| 469 | 465 | |
| 470 | | if (flush) { |
| 471 | | const trailing = lineBuffer.replace(/\r$/, ""); |
| 472 | | lineBuffer = ""; |
| 473 | | if (trailing.length > 0 && onLine) { |
| 474 | | yield* onLine(trailing); |
| 475 | | } |
| 466 | if (flush) { |
| 467 | const trailing = lineBuffer.replace(/\r$/, ""); |
| 468 | lineBuffer = ""; |
| 469 | if (trailing.length > 0 && onLine) { |
| 470 | yield* onLine(trailing); |
| 476 | 471 | } |
| 477 | | }); |
| 472 | } |
| 473 | }); |
| 478 | 474 | |
| 479 | | yield* Stream.runForEach(stream, (chunk) => |
| 480 | | Effect.gen(function* () { |
| 481 | | if (truncateOutputAtMaxBytes && truncated) { |
| 482 | | return; |
| 483 | | } |
| 484 | | const nextBytes = bytes + chunk.byteLength; |
| 485 | | if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) { |
| 486 | | return yield* new GitCommandError({ |
| 487 | | operation: input.operation, |
| 488 | | command: quoteGitCommand(input.args), |
| 489 | | cwd: input.cwd, |
| 490 | | detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, |
| 491 | | }); |
| 492 | | } |
| 475 | const processChunk = Effect.fn("processChunk")(function* (chunk: Uint8Array) { |
| 476 | if (truncateOutputAtMaxBytes && truncated) { |
| 477 | return; |
| 478 | } |
| 479 | const nextBytes = bytes + chunk.byteLength; |
| 480 | if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) { |
| 481 | return yield* new GitCommandError({ |
| 482 | operation: input.operation, |
| 483 | command: quoteGitCommand(input.args), |
| 484 | cwd: input.cwd, |
| 485 | detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, |
| 486 | }); |
| 487 | } |
| 493 | 488 | |
| 494 | | const chunkToDecode = |
| 495 | | truncateOutputAtMaxBytes && nextBytes > maxOutputBytes |
| 496 | | ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes)) |
| 497 | | : chunk; |
| 498 | | bytes += chunkToDecode.byteLength; |
| 499 | | truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes; |
| 489 | const chunkToDecode = |
| 490 | truncateOutputAtMaxBytes && nextBytes > maxOutputBytes |
| 491 | ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes)) |
| 492 | : chunk; |
| 493 | bytes += chunkToDecode.byteLength; |
| 494 | truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes; |
| 495 | |
| 496 | const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); |
| 497 | text += decoded; |
| 498 | lineBuffer += decoded; |
| 499 | yield* emitCompleteLines(false); |
| 500 | }); |
| 500 | 501 | |
| 501 | | const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); |
| 502 | | text += decoded; |
| 503 | | lineBuffer += decoded; |
| 504 | | yield* emitCompleteLines(false); |
| 505 | | }), |
| 506 | | ).pipe(Effect.mapError(toGitCommandError(input, "output stream failed."))); |
| 502 | yield* Stream.runForEach(stream, processChunk).pipe( |
| 503 | Effect.mapError(toGitCommandError(input, "output stream failed.")), |
| 504 | ); |
| 507 | 505 | |
| 508 | 506 | const remainder = truncated ? "" : decoder.decode(); |
| 509 | 507 | text += remainder; |
| ... | ... | @@ -512,1367 +510,1343 @@ const collectOutput = Effect.fn(function* <E>( |
| 512 | 510 | return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text; |
| 513 | 511 | }); |
| 514 | 512 | |
| 515 | | export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"] }) => |
| 516 | | Effect.gen(function* () { |
| 517 | | const fileSystem = yield* FileSystem.FileSystem; |
| 518 | | const path = yield* Path.Path; |
| 519 | | const { worktreesDir } = yield* ServerConfig; |
| 520 | | |
| 521 | | let execute: GitCoreShape["execute"]; |
| 522 | | |
| 523 | | if (options?.executeOverride) { |
| 524 | | execute = options.executeOverride; |
| 525 | | } else { |
| 526 | | const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 527 | | execute = Effect.fnUntraced(function* (input) { |
| 528 | | const commandInput = { |
| 529 | | ...input, |
| 530 | | args: [...input.args], |
| 531 | | } as const; |
| 532 | | const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; |
| 533 | | const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; |
| 534 | | const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false; |
| 535 | | |
| 536 | | const commandEffect = Effect.gen(function* () { |
| 537 | | const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( |
| 538 | | Effect.provideService(Path.Path, path), |
| 539 | | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 540 | | Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")), |
| 541 | | ); |
| 542 | | const child = yield* commandSpawner |
| 543 | | .spawn( |
| 544 | | ChildProcess.make("git", commandInput.args, { |
| 545 | | cwd: commandInput.cwd, |
| 546 | | env: { |
| 547 | | ...process.env, |
| 548 | | ...input.env, |
| 549 | | ...trace2Monitor.env, |
| 550 | | }, |
| 551 | | }), |
| 552 | | ) |
| 553 | | .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); |
| 554 | | |
| 555 | | const [stdout, stderr, exitCode] = yield* Effect.all( |
| 556 | | [ |
| 557 | | collectOutput( |
| 558 | | commandInput, |
| 559 | | child.stdout, |
| 560 | | maxOutputBytes, |
| 561 | | truncateOutputAtMaxBytes, |
| 562 | | input.progress?.onStdoutLine, |
| 563 | | ), |
| 564 | | collectOutput( |
| 565 | | commandInput, |
| 566 | | child.stderr, |
| 567 | | maxOutputBytes, |
| 568 | | truncateOutputAtMaxBytes, |
| 569 | | input.progress?.onStderrLine, |
| 570 | | ), |
| 571 | | child.exitCode.pipe( |
| 572 | | Effect.map((value) => Number(value)), |
| 573 | | Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), |
| 574 | | ), |
| 575 | | ], |
| 576 | | { concurrency: "unbounded" }, |
| 577 | | ); |
| 578 | | yield* trace2Monitor.flush; |
| 579 | | |
| 580 | | if (!input.allowNonZeroExit && exitCode !== 0) { |
| 581 | | const trimmedStderr = stderr.trim(); |
| 582 | | return yield* new GitCommandError({ |
| 583 | | operation: commandInput.operation, |
| 584 | | command: quoteGitCommand(commandInput.args), |
| 513 | export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { |
| 514 | executeOverride?: GitCoreShape["execute"]; |
| 515 | }) { |
| 516 | const fileSystem = yield* FileSystem.FileSystem; |
| 517 | const path = yield* Path.Path; |
| 518 | const { worktreesDir } = yield* ServerConfig; |
| 519 | |
| 520 | let execute: GitCoreShape["execute"]; |
| 521 | |
| 522 | if (options?.executeOverride) { |
| 523 | execute = options.executeOverride; |
| 524 | } else { |
| 525 | const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 526 | execute = Effect.fnUntraced(function* (input) { |
| 527 | const commandInput = { |
| 528 | ...input, |
| 529 | args: [...input.args], |
| 530 | } as const; |
| 531 | const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; |
| 532 | const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; |
| 533 | const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false; |
| 534 | |
| 535 | const runGitCommand = Effect.fn("runGitCommand")(function* () { |
| 536 | const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( |
| 537 | Effect.provideService(Path.Path, path), |
| 538 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 539 | Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")), |
| 540 | ); |
| 541 | const child = yield* commandSpawner |
| 542 | .spawn( |
| 543 | ChildProcess.make("git", commandInput.args, { |
| 585 | 544 | cwd: commandInput.cwd, |
| 586 | | detail: |
| 587 | | trimmedStderr.length > 0 |
| 588 | | ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}` |
| 589 | | : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`, |
| 590 | | }); |
| 591 | | } |
| 592 | | |
| 593 | | return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult; |
| 594 | | }); |
| 595 | | |
| 596 | | return yield* commandEffect.pipe( |
| 597 | | Effect.scoped, |
| 598 | | Effect.timeoutOption(timeoutMs), |
| 599 | | Effect.flatMap((result) => |
| 600 | | Option.match(result, { |
| 601 | | onNone: () => |
| 602 | | Effect.fail( |
| 603 | | new GitCommandError({ |
| 604 | | operation: commandInput.operation, |
| 605 | | command: quoteGitCommand(commandInput.args), |
| 606 | | cwd: commandInput.cwd, |
| 607 | | detail: `${quoteGitCommand(commandInput.args)} timed out.`, |
| 608 | | }), |
| 609 | | ), |
| 610 | | onSome: Effect.succeed, |
| 545 | env: { |
| 546 | ...process.env, |
| 547 | ...input.env, |
| 548 | ...trace2Monitor.env, |
| 549 | }, |
| 611 | 550 | }), |
| 612 | | ), |
| 613 | | ); |
| 614 | | }); |
| 615 | | } |
| 551 | ) |
| 552 | .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); |
| 616 | 553 | |
| 617 | | const executeGit = ( |
| 618 | | operation: string, |
| 619 | | cwd: string, |
| 620 | | args: readonly string[], |
| 621 | | options: ExecuteGitOptions = {}, |
| 622 | | ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> => |
| 623 | | execute({ |
| 624 | | operation, |
| 625 | | cwd, |
| 626 | | args, |
| 627 | | allowNonZeroExit: true, |
| 628 | | ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), |
| 629 | | ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), |
| 630 | | ...(options.truncateOutputAtMaxBytes !== undefined |
| 631 | | ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } |
| 632 | | : {}), |
| 633 | | ...(options.progress ? { progress: options.progress } : {}), |
| 634 | | }).pipe( |
| 635 | | Effect.flatMap((result) => { |
| 636 | | if (options.allowNonZeroExit || result.code === 0) { |
| 637 | | return Effect.succeed(result); |
| 638 | | } |
| 639 | | const stderr = result.stderr.trim(); |
| 640 | | if (stderr.length > 0) { |
| 641 | | return Effect.fail(createGitCommandError(operation, cwd, args, stderr)); |
| 642 | | } |
| 643 | | if (options.fallbackErrorMessage) { |
| 644 | | return Effect.fail( |
| 645 | | createGitCommandError(operation, cwd, args, options.fallbackErrorMessage), |
| 646 | | ); |
| 647 | | } |
| 648 | | return Effect.fail( |
| 649 | | createGitCommandError( |
| 650 | | operation, |
| 651 | | cwd, |
| 652 | | args, |
| 653 | | `${commandLabel(args)} failed: code=${result.code ?? "null"}`, |
| 554 | const [stdout, stderr, exitCode] = yield* Effect.all( |
| 555 | [ |
| 556 | collectOutput( |
| 557 | commandInput, |
| 558 | child.stdout, |
| 559 | maxOutputBytes, |
| 560 | truncateOutputAtMaxBytes, |
| 561 | input.progress?.onStdoutLine, |
| 654 | 562 | ), |
| 655 | | ); |
| 656 | | }), |
| 657 | | ); |
| 563 | collectOutput( |
| 564 | commandInput, |
| 565 | child.stderr, |
| 566 | maxOutputBytes, |
| 567 | truncateOutputAtMaxBytes, |
| 568 | input.progress?.onStderrLine, |
| 569 | ), |
| 570 | child.exitCode.pipe( |
| 571 | Effect.map((value) => Number(value)), |
| 572 | Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), |
| 573 | ), |
| 574 | ], |
| 575 | { concurrency: "unbounded" }, |
| 576 | ); |
| 577 | yield* trace2Monitor.flush; |
| 578 | |
| 579 | if (!input.allowNonZeroExit && exitCode !== 0) { |
| 580 | const trimmedStderr = stderr.trim(); |
| 581 | return yield* new GitCommandError({ |
| 582 | operation: commandInput.operation, |
| 583 | command: quoteGitCommand(commandInput.args), |
| 584 | cwd: commandInput.cwd, |
| 585 | detail: |
| 586 | trimmedStderr.length > 0 |
| 587 | ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}` |
| 588 | : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`, |
| 589 | }); |
| 590 | } |
| 658 | 591 | |
| 659 | | const runGit = ( |
| 660 | | operation: string, |
| 661 | | cwd: string, |
| 662 | | args: readonly string[], |
| 663 | | allowNonZeroExit = false, |
| 664 | | ): Effect.Effect<void, GitCommandError> => |
| 665 | | executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid); |
| 666 | | |
| 667 | | const runGitStdout = ( |
| 668 | | operation: string, |
| 669 | | cwd: string, |
| 670 | | args: readonly string[], |
| 671 | | allowNonZeroExit = false, |
| 672 | | ): Effect.Effect<string, GitCommandError> => |
| 673 | | executeGit(operation, cwd, args, { allowNonZeroExit }).pipe( |
| 674 | | Effect.map((result) => result.stdout), |
| 592 | return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult; |
| 593 | }); |
| 594 | |
| 595 | return yield* runGitCommand().pipe( |
| 596 | Effect.scoped, |
| 597 | Effect.timeoutOption(timeoutMs), |
| 598 | Effect.flatMap((result) => |
| 599 | Option.match(result, { |
| 600 | onNone: () => |
| 601 | Effect.fail( |
| 602 | new GitCommandError({ |
| 603 | operation: commandInput.operation, |
| 604 | command: quoteGitCommand(commandInput.args), |
| 605 | cwd: commandInput.cwd, |
| 606 | detail: `${quoteGitCommand(commandInput.args)} timed out.`, |
| 607 | }), |
| 608 | ), |
| 609 | onSome: Effect.succeed, |
| 610 | }), |
| 611 | ), |
| 675 | 612 | ); |
| 613 | }); |
| 614 | } |
| 676 | 615 | |
| 677 | | const runGitStdoutWithOptions = ( |
| 678 | | operation: string, |
| 679 | | cwd: string, |
| 680 | | args: readonly string[], |
| 681 | | options: ExecuteGitOptions = {}, |
| 682 | | ): Effect.Effect<string, GitCommandError> => |
| 683 | | executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout)); |
| 684 | | |
| 685 | | const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> => |
| 686 | | executeGit( |
| 687 | | "GitCore.branchExists", |
| 688 | | cwd, |
| 689 | | ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], |
| 690 | | { |
| 691 | | allowNonZeroExit: true, |
| 692 | | timeoutMs: 5_000, |
| 693 | | }, |
| 694 | | ).pipe(Effect.map((result) => result.code === 0)); |
| 695 | | |
| 696 | | const resolveAvailableBranchName = ( |
| 697 | | cwd: string, |
| 698 | | desiredBranch: string, |
| 699 | | ): Effect.Effect<string, GitCommandError> => |
| 700 | | Effect.gen(function* () { |
| 701 | | const isDesiredTaken = yield* branchExists(cwd, desiredBranch); |
| 702 | | if (!isDesiredTaken) { |
| 703 | | return desiredBranch; |
| 616 | const executeGit = ( |
| 617 | operation: string, |
| 618 | cwd: string, |
| 619 | args: readonly string[], |
| 620 | options: ExecuteGitOptions = {}, |
| 621 | ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> => |
| 622 | execute({ |
| 623 | operation, |
| 624 | cwd, |
| 625 | args, |
| 626 | allowNonZeroExit: true, |
| 627 | ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), |
| 628 | ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), |
| 629 | ...(options.truncateOutputAtMaxBytes !== undefined |
| 630 | ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } |
| 631 | : {}), |
| 632 | ...(options.progress ? { progress: options.progress } : {}), |
| 633 | }).pipe( |
| 634 | Effect.flatMap((result) => { |
| 635 | if (options.allowNonZeroExit || result.code === 0) { |
| 636 | return Effect.succeed(result); |
| 704 | 637 | } |
| 705 | | |
| 706 | | for (let suffix = 1; suffix <= 100; suffix += 1) { |
| 707 | | const candidate = `${desiredBranch}-${suffix}`; |
| 708 | | const isCandidateTaken = yield* branchExists(cwd, candidate); |
| 709 | | if (!isCandidateTaken) { |
| 710 | | return candidate; |
| 711 | | } |
| 638 | const stderr = result.stderr.trim(); |
| 639 | if (stderr.length > 0) { |
| 640 | return Effect.fail(createGitCommandError(operation, cwd, args, stderr)); |
| 712 | 641 | } |
| 713 | | |
| 714 | | return yield* createGitCommandError( |
| 715 | | "GitCore.renameBranch", |
| 716 | | cwd, |
| 717 | | ["branch", "-m", "--", desiredBranch], |
| 718 | | `Could not find an available branch name for '${desiredBranch}'.`, |
| 642 | if (options.fallbackErrorMessage) { |
| 643 | return Effect.fail( |
| 644 | createGitCommandError(operation, cwd, args, options.fallbackErrorMessage), |
| 645 | ); |
| 646 | } |
| 647 | return Effect.fail( |
| 648 | createGitCommandError( |
| 649 | operation, |
| 650 | cwd, |
| 651 | args, |
| 652 | `${commandLabel(args)} failed: code=${result.code ?? "null"}`, |
| 653 | ), |
| 719 | 654 | ); |
| 720 | | }); |
| 655 | }), |
| 656 | ); |
| 657 | |
| 658 | const runGit = ( |
| 659 | operation: string, |
| 660 | cwd: string, |
| 661 | args: readonly string[], |
| 662 | allowNonZeroExit = false, |
| 663 | ): Effect.Effect<void, GitCommandError> => |
| 664 | executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid); |
| 665 | |
| 666 | const runGitStdout = ( |
| 667 | operation: string, |
| 668 | cwd: string, |
| 669 | args: readonly string[], |
| 670 | allowNonZeroExit = false, |
| 671 | ): Effect.Effect<string, GitCommandError> => |
| 672 | executeGit(operation, cwd, args, { allowNonZeroExit }).pipe( |
| 673 | Effect.map((result) => result.stdout), |
| 674 | ); |
| 675 | |
| 676 | const runGitStdoutWithOptions = ( |
| 677 | operation: string, |
| 678 | cwd: string, |
| 679 | args: readonly string[], |
| 680 | options: ExecuteGitOptions = {}, |
| 681 | ): Effect.Effect<string, GitCommandError> => |
| 682 | executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout)); |
| 683 | |
| 684 | const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> => |
| 685 | executeGit( |
| 686 | "GitCore.branchExists", |
| 687 | cwd, |
| 688 | ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], |
| 689 | { |
| 690 | allowNonZeroExit: true, |
| 691 | timeoutMs: 5_000, |
| 692 | }, |
| 693 | ).pipe(Effect.map((result) => result.code === 0)); |
| 694 | |
| 695 | const resolveAvailableBranchName = Effect.fn("resolveAvailableBranchName")(function* ( |
| 696 | cwd: string, |
| 697 | desiredBranch: string, |
| 698 | ) { |
| 699 | const isDesiredTaken = yield* branchExists(cwd, desiredBranch); |
| 700 | if (!isDesiredTaken) { |
| 701 | return desiredBranch; |
| 702 | } |
| 721 | 703 | |
| 722 | | const resolveCurrentUpstream = ( |
| 723 | | cwd: string, |
| 724 | | ): Effect.Effect< |
| 725 | | { upstreamRef: string; remoteName: string; upstreamBranch: string } | null, |
| 726 | | GitCommandError |
| 727 | | > => |
| 728 | | Effect.gen(function* () { |
| 729 | | const upstreamRef = yield* runGitStdout( |
| 730 | | "GitCore.resolveCurrentUpstream", |
| 731 | | cwd, |
| 732 | | ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], |
| 733 | | true, |
| 734 | | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 704 | for (let suffix = 1; suffix <= 100; suffix += 1) { |
| 705 | const candidate = `${desiredBranch}-${suffix}`; |
| 706 | const isCandidateTaken = yield* branchExists(cwd, candidate); |
| 707 | if (!isCandidateTaken) { |
| 708 | return candidate; |
| 709 | } |
| 710 | } |
| 735 | 711 | |
| 736 | | if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { |
| 737 | | return null; |
| 738 | | } |
| 712 | return yield* createGitCommandError( |
| 713 | "GitCore.renameBranch", |
| 714 | cwd, |
| 715 | ["branch", "-m", "--", desiredBranch], |
| 716 | `Could not find an available branch name for '${desiredBranch}'.`, |
| 717 | ); |
| 718 | }); |
| 739 | 719 | |
| 740 | | const separatorIndex = upstreamRef.indexOf("/"); |
| 741 | | if (separatorIndex <= 0) { |
| 742 | | return null; |
| 743 | | } |
| 744 | | const remoteName = upstreamRef.slice(0, separatorIndex); |
| 745 | | const upstreamBranch = upstreamRef.slice(separatorIndex + 1); |
| 746 | | if (remoteName.length === 0 || upstreamBranch.length === 0) { |
| 747 | | return null; |
| 748 | | } |
| 720 | const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* (cwd: string) { |
| 721 | const upstreamRef = yield* runGitStdout( |
| 722 | "GitCore.resolveCurrentUpstream", |
| 723 | cwd, |
| 724 | ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], |
| 725 | true, |
| 726 | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 749 | 727 | |
| 750 | | return { |
| 751 | | upstreamRef, |
| 752 | | remoteName, |
| 753 | | upstreamBranch, |
| 754 | | }; |
| 755 | | }); |
| 728 | if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { |
| 729 | return null; |
| 730 | } |
| 756 | 731 | |
| 757 | | const fetchUpstreamRef = ( |
| 758 | | cwd: string, |
| 759 | | upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, |
| 760 | | ): Effect.Effect<void, GitCommandError> => { |
| 761 | | const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; |
| 762 | | return runGit( |
| 763 | | "GitCore.fetchUpstreamRef", |
| 764 | | cwd, |
| 765 | | ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], |
| 766 | | true, |
| 767 | | ); |
| 768 | | }; |
| 732 | const separatorIndex = upstreamRef.indexOf("/"); |
| 733 | if (separatorIndex <= 0) { |
| 734 | return null; |
| 735 | } |
| 736 | const remoteName = upstreamRef.slice(0, separatorIndex); |
| 737 | const upstreamBranch = upstreamRef.slice(separatorIndex + 1); |
| 738 | if (remoteName.length === 0 || upstreamBranch.length === 0) { |
| 739 | return null; |
| 740 | } |
| 769 | 741 | |
| 770 | | const fetchUpstreamRefForStatus = ( |
| 771 | | cwd: string, |
| 772 | | upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, |
| 773 | | ): Effect.Effect<void, GitCommandError> => { |
| 774 | | const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; |
| 775 | | return executeGit( |
| 776 | | "GitCore.fetchUpstreamRefForStatus", |
| 777 | | cwd, |
| 778 | | ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], |
| 779 | | { |
| 780 | | allowNonZeroExit: true, |
| 781 | | timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), |
| 782 | | }, |
| 783 | | ).pipe(Effect.asVoid); |
| 742 | return { |
| 743 | upstreamRef, |
| 744 | remoteName, |
| 745 | upstreamBranch, |
| 784 | 746 | }; |
| 747 | }); |
| 785 | 748 | |
| 786 | | const statusUpstreamRefreshCache = yield* Cache.makeWith({ |
| 787 | | capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, |
| 788 | | lookup: (cacheKey: StatusUpstreamRefreshCacheKey) => |
| 789 | | Effect.gen(function* () { |
| 790 | | yield* fetchUpstreamRefForStatus(cacheKey.cwd, { |
| 791 | | upstreamRef: cacheKey.upstreamRef, |
| 792 | | remoteName: cacheKey.remoteName, |
| 793 | | upstreamBranch: cacheKey.upstreamBranch, |
| 794 | | }); |
| 795 | | return true as const; |
| 796 | | }), |
| 797 | | // Keep successful refreshes warm; drop failures immediately so next request can retry. |
| 798 | | timeToLive: (exit) => |
| 799 | | Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero, |
| 800 | | }); |
| 749 | const fetchUpstreamRef = ( |
| 750 | cwd: string, |
| 751 | upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, |
| 752 | ): Effect.Effect<void, GitCommandError> => { |
| 753 | const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; |
| 754 | return runGit( |
| 755 | "GitCore.fetchUpstreamRef", |
| 756 | cwd, |
| 757 | ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], |
| 758 | true, |
| 759 | ); |
| 760 | }; |
| 801 | 761 | |
| 802 | | const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect<void, GitCommandError> => |
| 803 | | Effect.gen(function* () { |
| 804 | | const upstream = yield* resolveCurrentUpstream(cwd); |
| 805 | | if (!upstream) return; |
| 806 | | yield* Cache.get( |
| 807 | | statusUpstreamRefreshCache, |
| 808 | | new StatusUpstreamRefreshCacheKey({ |
| 809 | | cwd, |
| 810 | | upstreamRef: upstream.upstreamRef, |
| 811 | | remoteName: upstream.remoteName, |
| 812 | | upstreamBranch: upstream.upstreamBranch, |
| 813 | | }), |
| 814 | | ); |
| 815 | | }); |
| 762 | const fetchUpstreamRefForStatus = ( |
| 763 | cwd: string, |
| 764 | upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, |
| 765 | ): Effect.Effect<void, GitCommandError> => { |
| 766 | const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; |
| 767 | return executeGit( |
| 768 | "GitCore.fetchUpstreamRefForStatus", |
| 769 | cwd, |
| 770 | ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], |
| 771 | { |
| 772 | allowNonZeroExit: true, |
| 773 | timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), |
| 774 | }, |
| 775 | ).pipe(Effect.asVoid); |
| 776 | }; |
| 816 | 777 | |
| 817 | | const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect<void, GitCommandError> => |
| 818 | | Effect.gen(function* () { |
| 819 | | const upstream = yield* resolveCurrentUpstream(cwd); |
| 820 | | if (!upstream) return; |
| 821 | | yield* fetchUpstreamRef(cwd, upstream); |
| 822 | | }); |
| 778 | const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* ( |
| 779 | cacheKey: StatusUpstreamRefreshCacheKey, |
| 780 | ) { |
| 781 | yield* fetchUpstreamRefForStatus(cacheKey.cwd, { |
| 782 | upstreamRef: cacheKey.upstreamRef, |
| 783 | remoteName: cacheKey.remoteName, |
| 784 | upstreamBranch: cacheKey.upstreamBranch, |
| 785 | }); |
| 786 | return true as const; |
| 787 | }); |
| 823 | 788 | |
| 824 | | const resolveDefaultBranchName = ( |
| 825 | | cwd: string, |
| 826 | | remoteName: string, |
| 827 | | ): Effect.Effect<string | null, GitCommandError> => |
| 828 | | executeGit( |
| 829 | | "GitCore.resolveDefaultBranchName", |
| 830 | | cwd, |
| 831 | | ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], |
| 832 | | { allowNonZeroExit: true }, |
| 833 | | ).pipe( |
| 834 | | Effect.map((result) => { |
| 835 | | if (result.code !== 0) { |
| 836 | | return null; |
| 837 | | } |
| 838 | | return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName); |
| 839 | | }), |
| 840 | | ); |
| 789 | const statusUpstreamRefreshCache = yield* Cache.makeWith({ |
| 790 | capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, |
| 791 | lookup: refreshStatusUpstreamCacheEntry, |
| 792 | // Keep successful refreshes warm; drop failures immediately so next request can retry. |
| 793 | timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero), |
| 794 | }); |
| 841 | 795 | |
| 842 | | const remoteBranchExists = ( |
| 843 | | cwd: string, |
| 844 | | remoteName: string, |
| 845 | | branch: string, |
| 846 | | ): Effect.Effect<boolean, GitCommandError> => |
| 847 | | executeGit( |
| 848 | | "GitCore.remoteBranchExists", |
| 796 | const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( |
| 797 | cwd: string, |
| 798 | ) { |
| 799 | const upstream = yield* resolveCurrentUpstream(cwd); |
| 800 | if (!upstream) return; |
| 801 | yield* Cache.get( |
| 802 | statusUpstreamRefreshCache, |
| 803 | new StatusUpstreamRefreshCacheKey({ |
| 849 | 804 | cwd, |
| 850 | | ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`], |
| 851 | | { |
| 852 | | allowNonZeroExit: true, |
| 853 | | }, |
| 854 | | ).pipe(Effect.map((result) => result.code === 0)); |
| 855 | | |
| 856 | | const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> => |
| 857 | | executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], { |
| 858 | | allowNonZeroExit: true, |
| 859 | | }).pipe(Effect.map((result) => result.code === 0)); |
| 860 | | |
| 861 | | const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> => |
| 862 | | runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( |
| 863 | | Effect.map((stdout) => parseRemoteNames(stdout).toReversed()), |
| 864 | | ); |
| 805 | upstreamRef: upstream.upstreamRef, |
| 806 | remoteName: upstream.remoteName, |
| 807 | upstreamBranch: upstream.upstreamBranch, |
| 808 | }), |
| 809 | ); |
| 810 | }); |
| 865 | 811 | |
| 866 | | const resolvePrimaryRemoteName = (cwd: string): Effect.Effect<string, GitCommandError> => |
| 867 | | Effect.gen(function* () { |
| 868 | | if (yield* originRemoteExists(cwd)) { |
| 869 | | return "origin"; |
| 870 | | } |
| 871 | | const remotes = yield* listRemoteNames(cwd); |
| 872 | | const [firstRemote] = remotes; |
| 873 | | if (firstRemote) { |
| 874 | | return firstRemote; |
| 875 | | } |
| 876 | | return yield* createGitCommandError( |
| 877 | | "GitCore.resolvePrimaryRemoteName", |
| 878 | | cwd, |
| 879 | | ["remote"], |
| 880 | | "No git remote is configured for this repository.", |
| 881 | | ); |
| 882 | | }); |
| 812 | const refreshCheckedOutBranchUpstream = Effect.fn("refreshCheckedOutBranchUpstream")(function* ( |
| 813 | cwd: string, |
| 814 | ) { |
| 815 | const upstream = yield* resolveCurrentUpstream(cwd); |
| 816 | if (!upstream) return; |
| 817 | yield* fetchUpstreamRef(cwd, upstream); |
| 818 | }); |
| 883 | 819 | |
| 884 | | const resolvePushRemoteName = ( |
| 885 | | cwd: string, |
| 886 | | branch: string, |
| 887 | | ): Effect.Effect<string | null, GitCommandError> => |
| 888 | | Effect.gen(function* () { |
| 889 | | const branchPushRemote = yield* runGitStdout( |
| 890 | | "GitCore.resolvePushRemoteName.branchPushRemote", |
| 891 | | cwd, |
| 892 | | ["config", "--get", `branch.${branch}.pushRemote`], |
| 893 | | true, |
| 894 | | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 895 | | if (branchPushRemote.length > 0) { |
| 896 | | return branchPushRemote; |
| 820 | const resolveDefaultBranchName = ( |
| 821 | cwd: string, |
| 822 | remoteName: string, |
| 823 | ): Effect.Effect<string | null, GitCommandError> => |
| 824 | executeGit( |
| 825 | "GitCore.resolveDefaultBranchName", |
| 826 | cwd, |
| 827 | ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], |
| 828 | { allowNonZeroExit: true }, |
| 829 | ).pipe( |
| 830 | Effect.map((result) => { |
| 831 | if (result.code !== 0) { |
| 832 | return null; |
| 897 | 833 | } |
| 834 | return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName); |
| 835 | }), |
| 836 | ); |
| 837 | |
| 838 | const remoteBranchExists = ( |
| 839 | cwd: string, |
| 840 | remoteName: string, |
| 841 | branch: string, |
| 842 | ): Effect.Effect<boolean, GitCommandError> => |
| 843 | executeGit( |
| 844 | "GitCore.remoteBranchExists", |
| 845 | cwd, |
| 846 | ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`], |
| 847 | { |
| 848 | allowNonZeroExit: true, |
| 849 | }, |
| 850 | ).pipe(Effect.map((result) => result.code === 0)); |
| 851 | |
| 852 | const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> => |
| 853 | executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], { |
| 854 | allowNonZeroExit: true, |
| 855 | }).pipe(Effect.map((result) => result.code === 0)); |
| 856 | |
| 857 | const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> => |
| 858 | runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( |
| 859 | Effect.map((stdout) => parseRemoteNames(stdout).toReversed()), |
| 860 | ); |
| 861 | |
| 862 | const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) { |
| 863 | if (yield* originRemoteExists(cwd)) { |
| 864 | return "origin"; |
| 865 | } |
| 866 | const remotes = yield* listRemoteNames(cwd); |
| 867 | const [firstRemote] = remotes; |
| 868 | if (firstRemote) { |
| 869 | return firstRemote; |
| 870 | } |
| 871 | return yield* createGitCommandError( |
| 872 | "GitCore.resolvePrimaryRemoteName", |
| 873 | cwd, |
| 874 | ["remote"], |
| 875 | "No git remote is configured for this repository.", |
| 876 | ); |
| 877 | }); |
| 898 | 878 | |
| 899 | | const pushDefaultRemote = yield* runGitStdout( |
| 900 | | "GitCore.resolvePushRemoteName.remotePushDefault", |
| 901 | | cwd, |
| 902 | | ["config", "--get", "remote.pushDefault"], |
| 903 | | true, |
| 904 | | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 905 | | if (pushDefaultRemote.length > 0) { |
| 906 | | return pushDefaultRemote; |
| 907 | | } |
| 879 | const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* ( |
| 880 | cwd: string, |
| 881 | branch: string, |
| 882 | ) { |
| 883 | const branchPushRemote = yield* runGitStdout( |
| 884 | "GitCore.resolvePushRemoteName.branchPushRemote", |
| 885 | cwd, |
| 886 | ["config", "--get", `branch.${branch}.pushRemote`], |
| 887 | true, |
| 888 | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 889 | if (branchPushRemote.length > 0) { |
| 890 | return branchPushRemote; |
| 891 | } |
| 908 | 892 | |
| 909 | | return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null))); |
| 910 | | }); |
| 893 | const pushDefaultRemote = yield* runGitStdout( |
| 894 | "GitCore.resolvePushRemoteName.remotePushDefault", |
| 895 | cwd, |
| 896 | ["config", "--get", "remote.pushDefault"], |
| 897 | true, |
| 898 | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 899 | if (pushDefaultRemote.length > 0) { |
| 900 | return pushDefaultRemote; |
| 901 | } |
| 911 | 902 | |
| 912 | | const ensureRemote: GitCoreShape["ensureRemote"] = (input) => |
| 913 | | Effect.gen(function* () { |
| 914 | | const preferredName = sanitizeRemoteName(input.preferredName); |
| 915 | | const normalizedTargetUrl = normalizeRemoteUrl(input.url); |
| 916 | | const remoteFetchUrls = yield* runGitStdout( |
| 917 | | "GitCore.ensureRemote.listRemoteUrls", |
| 918 | | input.cwd, |
| 919 | | ["remote", "-v"], |
| 920 | | ).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); |
| 921 | | |
| 922 | | for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { |
| 923 | | if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) { |
| 924 | | return remoteName; |
| 925 | | } |
| 926 | | } |
| 903 | return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null))); |
| 904 | }); |
| 927 | 905 | |
| 928 | | let remoteName = preferredName; |
| 929 | | let suffix = 1; |
| 930 | | while (remoteFetchUrls.has(remoteName)) { |
| 931 | | remoteName = `${preferredName}-${suffix}`; |
| 932 | | suffix += 1; |
| 933 | | } |
| 906 | const ensureRemote: GitCoreShape["ensureRemote"] = Effect.fn("ensureRemote")(function* (input) { |
| 907 | const preferredName = sanitizeRemoteName(input.preferredName); |
| 908 | const normalizedTargetUrl = normalizeRemoteUrl(input.url); |
| 909 | const remoteFetchUrls = yield* runGitStdout("GitCore.ensureRemote.listRemoteUrls", input.cwd, [ |
| 910 | "remote", |
| 911 | "-v", |
| 912 | ]).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); |
| 934 | 913 | |
| 935 | | yield* runGit("GitCore.ensureRemote.add", input.cwd, [ |
| 936 | | "remote", |
| 937 | | "add", |
| 938 | | remoteName, |
| 939 | | input.url, |
| 940 | | ]); |
| 914 | for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { |
| 915 | if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) { |
| 941 | 916 | return remoteName; |
| 942 | | }); |
| 943 | | |
| 944 | | const resolveBaseBranchForNoUpstream = ( |
| 945 | | cwd: string, |
| 946 | | branch: string, |
| 947 | | ): Effect.Effect<string | null, GitCommandError> => |
| 948 | | Effect.gen(function* () { |
| 949 | | const configuredBaseBranch = yield* runGitStdout( |
| 950 | | "GitCore.resolveBaseBranchForNoUpstream.config", |
| 951 | | cwd, |
| 952 | | ["config", "--get", `branch.${branch}.gh-merge-base`], |
| 953 | | true, |
| 954 | | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 917 | } |
| 918 | } |
| 955 | 919 | |
| 956 | | const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( |
| 957 | | Effect.catch(() => Effect.succeed(null)), |
| 958 | | ); |
| 959 | | const defaultBranch = |
| 960 | | primaryRemoteName === null |
| 961 | | ? null |
| 962 | | : yield* resolveDefaultBranchName(cwd, primaryRemoteName); |
| 963 | | const candidates = [ |
| 964 | | configuredBaseBranch.length > 0 ? configuredBaseBranch : null, |
| 965 | | defaultBranch, |
| 966 | | ...DEFAULT_BASE_BRANCH_CANDIDATES, |
| 967 | | ]; |
| 968 | | |
| 969 | | for (const candidate of candidates) { |
| 970 | | if (!candidate) { |
| 971 | | continue; |
| 972 | | } |
| 920 | let remoteName = preferredName; |
| 921 | let suffix = 1; |
| 922 | while (remoteFetchUrls.has(remoteName)) { |
| 923 | remoteName = `${preferredName}-${suffix}`; |
| 924 | suffix += 1; |
| 925 | } |
| 973 | 926 | |
| 974 | | const remotePrefix = |
| 975 | | primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null; |
| 976 | | const normalizedCandidate = candidate.startsWith("origin/") |
| 977 | | ? candidate.slice("origin/".length) |
| 978 | | : remotePrefix && candidate.startsWith(remotePrefix) |
| 979 | | ? candidate.slice(remotePrefix.length) |
| 980 | | : candidate; |
| 981 | | if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { |
| 982 | | continue; |
| 983 | | } |
| 927 | yield* runGit("GitCore.ensureRemote.add", input.cwd, ["remote", "add", remoteName, input.url]); |
| 928 | return remoteName; |
| 929 | }); |
| 984 | 930 | |
| 985 | | if (yield* branchExists(cwd, normalizedCandidate)) { |
| 986 | | return normalizedCandidate; |
| 987 | | } |
| 931 | const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* ( |
| 932 | cwd: string, |
| 933 | branch: string, |
| 934 | ) { |
| 935 | const configuredBaseBranch = yield* runGitStdout( |
| 936 | "GitCore.resolveBaseBranchForNoUpstream.config", |
| 937 | cwd, |
| 938 | ["config", "--get", `branch.${branch}.gh-merge-base`], |
| 939 | true, |
| 940 | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 941 | |
| 942 | const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( |
| 943 | Effect.catch(() => Effect.succeed(null)), |
| 944 | ); |
| 945 | const defaultBranch = |
| 946 | primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName); |
| 947 | const candidates = [ |
| 948 | configuredBaseBranch.length > 0 ? configuredBaseBranch : null, |
| 949 | defaultBranch, |
| 950 | ...DEFAULT_BASE_BRANCH_CANDIDATES, |
| 951 | ]; |
| 952 | |
| 953 | for (const candidate of candidates) { |
| 954 | if (!candidate) { |
| 955 | continue; |
| 956 | } |
| 988 | 957 | |
| 989 | | if ( |
| 990 | | primaryRemoteName && |
| 991 | | (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate)) |
| 992 | | ) { |
| 993 | | return `${primaryRemoteName}/${normalizedCandidate}`; |
| 994 | | } |
| 995 | | } |
| 958 | const remotePrefix = |
| 959 | primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null; |
| 960 | const normalizedCandidate = candidate.startsWith("origin/") |
| 961 | ? candidate.slice("origin/".length) |
| 962 | : remotePrefix && candidate.startsWith(remotePrefix) |
| 963 | ? candidate.slice(remotePrefix.length) |
| 964 | : candidate; |
| 965 | if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { |
| 966 | continue; |
| 967 | } |
| 996 | 968 | |
| 997 | | return null; |
| 998 | | }); |
| 969 | if (yield* branchExists(cwd, normalizedCandidate)) { |
| 970 | return normalizedCandidate; |
| 971 | } |
| 999 | 972 | |
| 1000 | | const computeAheadCountAgainstBase = ( |
| 1001 | | cwd: string, |
| 1002 | | branch: string, |
| 1003 | | ): Effect.Effect<number, GitCommandError> => |
| 1004 | | Effect.gen(function* () { |
| 1005 | | const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch); |
| 1006 | | if (!baseBranch) { |
| 1007 | | return 0; |
| 1008 | | } |
| 973 | if ( |
| 974 | primaryRemoteName && |
| 975 | (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate)) |
| 976 | ) { |
| 977 | return `${primaryRemoteName}/${normalizedCandidate}`; |
| 978 | } |
| 979 | } |
| 1009 | 980 | |
| 1010 | | const result = yield* executeGit( |
| 1011 | | "GitCore.computeAheadCountAgainstBase", |
| 1012 | | cwd, |
| 1013 | | ["rev-list", "--count", `${baseBranch}..HEAD`], |
| 1014 | | { allowNonZeroExit: true }, |
| 1015 | | ); |
| 1016 | | if (result.code !== 0) { |
| 1017 | | return 0; |
| 1018 | | } |
| 981 | return null; |
| 982 | }); |
| 1019 | 983 | |
| 1020 | | const parsed = Number.parseInt(result.stdout.trim(), 10); |
| 1021 | | return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; |
| 1022 | | }); |
| 984 | const computeAheadCountAgainstBase = Effect.fn("computeAheadCountAgainstBase")(function* ( |
| 985 | cwd: string, |
| 986 | branch: string, |
| 987 | ) { |
| 988 | const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch); |
| 989 | if (!baseBranch) { |
| 990 | return 0; |
| 991 | } |
| 1023 | 992 | |
| 1024 | | const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> => |
| 1025 | | Effect.gen(function* () { |
| 1026 | | const branchRecency = yield* executeGit( |
| 1027 | | "GitCore.readBranchRecency", |
| 1028 | | cwd, |
| 1029 | | [ |
| 1030 | | "for-each-ref", |
| 1031 | | "--format=%(refname:short)%09%(committerdate:unix)", |
| 1032 | | "refs/heads", |
| 1033 | | "refs/remotes", |
| 1034 | | ], |
| 1035 | | { |
| 1036 | | timeoutMs: 15_000, |
| 1037 | | allowNonZeroExit: true, |
| 1038 | | }, |
| 1039 | | ); |
| 993 | const result = yield* executeGit( |
| 994 | "GitCore.computeAheadCountAgainstBase", |
| 995 | cwd, |
| 996 | ["rev-list", "--count", `${baseBranch}..HEAD`], |
| 997 | { allowNonZeroExit: true }, |
| 998 | ); |
| 999 | if (result.code !== 0) { |
| 1000 | return 0; |
| 1001 | } |
| 1040 | 1002 | |
| 1041 | | const branchLastCommit = new Map<string, number>(); |
| 1042 | | if (branchRecency.code !== 0) { |
| 1043 | | return branchLastCommit; |
| 1044 | | } |
| 1003 | const parsed = Number.parseInt(result.stdout.trim(), 10); |
| 1004 | return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; |
| 1005 | }); |
| 1045 | 1006 | |
| 1046 | | for (const line of branchRecency.stdout.split("\n")) { |
| 1047 | | if (line.length === 0) { |
| 1048 | | continue; |
| 1049 | | } |
| 1050 | | const [name, lastCommitRaw] = line.split("\t"); |
| 1051 | | if (!name) { |
| 1052 | | continue; |
| 1053 | | } |
| 1054 | | const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); |
| 1055 | | branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); |
| 1056 | | } |
| 1007 | const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) { |
| 1008 | const branchRecency = yield* executeGit( |
| 1009 | "GitCore.readBranchRecency", |
| 1010 | cwd, |
| 1011 | [ |
| 1012 | "for-each-ref", |
| 1013 | "--format=%(refname:short)%09%(committerdate:unix)", |
| 1014 | "refs/heads", |
| 1015 | "refs/remotes", |
| 1016 | ], |
| 1017 | { |
| 1018 | timeoutMs: 15_000, |
| 1019 | allowNonZeroExit: true, |
| 1020 | }, |
| 1021 | ); |
| 1057 | 1022 | |
| 1058 | | return branchLastCommit; |
| 1059 | | }); |
| 1023 | const branchLastCommit = new Map<string, number>(); |
| 1024 | if (branchRecency.code !== 0) { |
| 1025 | return branchLastCommit; |
| 1026 | } |
| 1060 | 1027 | |
| 1061 | | const statusDetails: GitCoreShape["statusDetails"] = (cwd) => |
| 1062 | | Effect.gen(function* () { |
| 1063 | | yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); |
| 1028 | for (const line of branchRecency.stdout.split("\n")) { |
| 1029 | if (line.length === 0) { |
| 1030 | continue; |
| 1031 | } |
| 1032 | const [name, lastCommitRaw] = line.split("\t"); |
| 1033 | if (!name) { |
| 1034 | continue; |
| 1035 | } |
| 1036 | const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); |
| 1037 | branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); |
| 1038 | } |
| 1064 | 1039 | |
| 1065 | | const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all( |
| 1066 | | [ |
| 1067 | | runGitStdout("GitCore.statusDetails.status", cwd, [ |
| 1068 | | "status", |
| 1069 | | "--porcelain=2", |
| 1070 | | "--branch", |
| 1071 | | ]), |
| 1072 | | runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), |
| 1073 | | runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [ |
| 1074 | | "diff", |
| 1075 | | "--cached", |
| 1076 | | "--numstat", |
| 1077 | | ]), |
| 1078 | | ], |
| 1079 | | { concurrency: "unbounded" }, |
| 1080 | | ); |
| 1040 | return branchLastCommit; |
| 1041 | }); |
| 1081 | 1042 | |
| 1082 | | let branch: string | null = null; |
| 1083 | | let upstreamRef: string | null = null; |
| 1084 | | let aheadCount = 0; |
| 1085 | | let behindCount = 0; |
| 1086 | | let hasWorkingTreeChanges = false; |
| 1087 | | const changedFilesWithoutNumstat = new Set<string>(); |
| 1088 | | |
| 1089 | | for (const line of statusStdout.split(/\r?\n/g)) { |
| 1090 | | if (line.startsWith("# branch.head ")) { |
| 1091 | | const value = line.slice("# branch.head ".length).trim(); |
| 1092 | | branch = value.startsWith("(") ? null : value; |
| 1093 | | continue; |
| 1094 | | } |
| 1095 | | if (line.startsWith("# branch.upstream ")) { |
| 1096 | | const value = line.slice("# branch.upstream ".length).trim(); |
| 1097 | | upstreamRef = value.length > 0 ? value : null; |
| 1098 | | continue; |
| 1099 | | } |
| 1100 | | if (line.startsWith("# branch.ab ")) { |
| 1101 | | const value = line.slice("# branch.ab ".length).trim(); |
| 1102 | | const parsed = parseBranchAb(value); |
| 1103 | | aheadCount = parsed.ahead; |
| 1104 | | behindCount = parsed.behind; |
| 1105 | | continue; |
| 1106 | | } |
| 1107 | | if (line.trim().length > 0 && !line.startsWith("#")) { |
| 1108 | | hasWorkingTreeChanges = true; |
| 1109 | | const pathValue = parsePorcelainPath(line); |
| 1110 | | if (pathValue) changedFilesWithoutNumstat.add(pathValue); |
| 1111 | | } |
| 1112 | | } |
| 1043 | const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) { |
| 1044 | yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); |
| 1045 | |
| 1046 | const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all( |
| 1047 | [ |
| 1048 | runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]), |
| 1049 | runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), |
| 1050 | runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]), |
| 1051 | ], |
| 1052 | { concurrency: "unbounded" }, |
| 1053 | ); |
| 1054 | |
| 1055 | let branch: string | null = null; |
| 1056 | let upstreamRef: string | null = null; |
| 1057 | let aheadCount = 0; |
| 1058 | let behindCount = 0; |
| 1059 | let hasWorkingTreeChanges = false; |
| 1060 | const changedFilesWithoutNumstat = new Set<string>(); |
| 1061 | |
| 1062 | for (const line of statusStdout.split(/\r?\n/g)) { |
| 1063 | if (line.startsWith("# branch.head ")) { |
| 1064 | const value = line.slice("# branch.head ".length).trim(); |
| 1065 | branch = value.startsWith("(") ? null : value; |
| 1066 | continue; |
| 1067 | } |
| 1068 | if (line.startsWith("# branch.upstream ")) { |
| 1069 | const value = line.slice("# branch.upstream ".length).trim(); |
| 1070 | upstreamRef = value.length > 0 ? value : null; |
| 1071 | continue; |
| 1072 | } |
| 1073 | if (line.startsWith("# branch.ab ")) { |
| 1074 | const value = line.slice("# branch.ab ".length).trim(); |
| 1075 | const parsed = parseBranchAb(value); |
| 1076 | aheadCount = parsed.ahead; |
| 1077 | behindCount = parsed.behind; |
| 1078 | continue; |
| 1079 | } |
| 1080 | if (line.trim().length > 0 && !line.startsWith("#")) { |
| 1081 | hasWorkingTreeChanges = true; |
| 1082 | const pathValue = parsePorcelainPath(line); |
| 1083 | if (pathValue) changedFilesWithoutNumstat.add(pathValue); |
| 1084 | } |
| 1085 | } |
| 1113 | 1086 | |
| 1114 | | if (!upstreamRef && branch) { |
| 1115 | | aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( |
| 1116 | | Effect.catch(() => Effect.succeed(0)), |
| 1117 | | ); |
| 1118 | | behindCount = 0; |
| 1119 | | } |
| 1087 | if (!upstreamRef && branch) { |
| 1088 | aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( |
| 1089 | Effect.catch(() => Effect.succeed(0)), |
| 1090 | ); |
| 1091 | behindCount = 0; |
| 1092 | } |
| 1120 | 1093 | |
| 1121 | | const stagedEntries = parseNumstatEntries(stagedNumstatStdout); |
| 1122 | | const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); |
| 1123 | | const fileStatMap = new Map<string, { insertions: number; deletions: number }>(); |
| 1124 | | for (const entry of [...stagedEntries, ...unstagedEntries]) { |
| 1125 | | const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; |
| 1126 | | existing.insertions += entry.insertions; |
| 1127 | | existing.deletions += entry.deletions; |
| 1128 | | fileStatMap.set(entry.path, existing); |
| 1129 | | } |
| 1094 | const stagedEntries = parseNumstatEntries(stagedNumstatStdout); |
| 1095 | const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); |
| 1096 | const fileStatMap = new Map<string, { insertions: number; deletions: number }>(); |
| 1097 | for (const entry of [...stagedEntries, ...unstagedEntries]) { |
| 1098 | const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; |
| 1099 | existing.insertions += entry.insertions; |
| 1100 | existing.deletions += entry.deletions; |
| 1101 | fileStatMap.set(entry.path, existing); |
| 1102 | } |
| 1130 | 1103 | |
| 1131 | | let insertions = 0; |
| 1132 | | let deletions = 0; |
| 1133 | | const files = Array.from(fileStatMap.entries()) |
| 1134 | | .map(([filePath, stat]) => { |
| 1135 | | insertions += stat.insertions; |
| 1136 | | deletions += stat.deletions; |
| 1137 | | return { path: filePath, insertions: stat.insertions, deletions: stat.deletions }; |
| 1138 | | }) |
| 1139 | | .toSorted((a, b) => a.path.localeCompare(b.path)); |
| 1140 | | |
| 1141 | | for (const filePath of changedFilesWithoutNumstat) { |
| 1142 | | if (fileStatMap.has(filePath)) continue; |
| 1143 | | files.push({ path: filePath, insertions: 0, deletions: 0 }); |
| 1144 | | } |
| 1145 | | files.sort((a, b) => a.path.localeCompare(b.path)); |
| 1104 | let insertions = 0; |
| 1105 | let deletions = 0; |
| 1106 | const files = Array.from(fileStatMap.entries()) |
| 1107 | .map(([filePath, stat]) => { |
| 1108 | insertions += stat.insertions; |
| 1109 | deletions += stat.deletions; |
| 1110 | return { path: filePath, insertions: stat.insertions, deletions: stat.deletions }; |
| 1111 | }) |
| 1112 | .toSorted((a, b) => a.path.localeCompare(b.path)); |
| 1113 | |
| 1114 | for (const filePath of changedFilesWithoutNumstat) { |
| 1115 | if (fileStatMap.has(filePath)) continue; |
| 1116 | files.push({ path: filePath, insertions: 0, deletions: 0 }); |
| 1117 | } |
| 1118 | files.sort((a, b) => a.path.localeCompare(b.path)); |
| 1146 | 1119 | |
| 1147 | | return { |
| 1148 | | branch, |
| 1149 | | upstreamRef, |
| 1150 | | hasWorkingTreeChanges, |
| 1151 | | workingTree: { |
| 1152 | | files, |
| 1153 | | insertions, |
| 1154 | | deletions, |
| 1155 | | }, |
| 1156 | | hasUpstream: upstreamRef !== null, |
| 1157 | | aheadCount, |
| 1158 | | behindCount, |
| 1159 | | }; |
| 1160 | | }); |
| 1120 | return { |
| 1121 | branch, |
| 1122 | upstreamRef, |
| 1123 | hasWorkingTreeChanges, |
| 1124 | workingTree: { |
| 1125 | files, |
| 1126 | insertions, |
| 1127 | deletions, |
| 1128 | }, |
| 1129 | hasUpstream: upstreamRef !== null, |
| 1130 | aheadCount, |
| 1131 | behindCount, |
| 1132 | }; |
| 1133 | }); |
| 1161 | 1134 | |
| 1162 | | const status: GitCoreShape["status"] = (input) => |
| 1163 | | statusDetails(input.cwd).pipe( |
| 1164 | | Effect.map((details) => ({ |
| 1165 | | branch: details.branch, |
| 1166 | | hasWorkingTreeChanges: details.hasWorkingTreeChanges, |
| 1167 | | workingTree: details.workingTree, |
| 1168 | | hasUpstream: details.hasUpstream, |
| 1169 | | aheadCount: details.aheadCount, |
| 1170 | | behindCount: details.behindCount, |
| 1171 | | pr: null, |
| 1172 | | })), |
| 1135 | const status: GitCoreShape["status"] = (input) => |
| 1136 | statusDetails(input.cwd).pipe( |
| 1137 | Effect.map((details) => ({ |
| 1138 | branch: details.branch, |
| 1139 | hasWorkingTreeChanges: details.hasWorkingTreeChanges, |
| 1140 | workingTree: details.workingTree, |
| 1141 | hasUpstream: details.hasUpstream, |
| 1142 | aheadCount: details.aheadCount, |
| 1143 | behindCount: details.behindCount, |
| 1144 | pr: null, |
| 1145 | })), |
| 1146 | ); |
| 1147 | |
| 1148 | const prepareCommitContext: GitCoreShape["prepareCommitContext"] = Effect.fn( |
| 1149 | "prepareCommitContext", |
| 1150 | )(function* (cwd, filePaths) { |
| 1151 | if (filePaths && filePaths.length > 0) { |
| 1152 | yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe( |
| 1153 | Effect.catch(() => Effect.void), |
| 1173 | 1154 | ); |
| 1155 | yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [ |
| 1156 | "add", |
| 1157 | "-A", |
| 1158 | "--", |
| 1159 | ...filePaths, |
| 1160 | ]); |
| 1161 | } else { |
| 1162 | yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]); |
| 1163 | } |
| 1174 | 1164 | |
| 1175 | | const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd, filePaths) => |
| 1176 | | Effect.gen(function* () { |
| 1177 | | if (filePaths && filePaths.length > 0) { |
| 1178 | | yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe( |
| 1179 | | Effect.catch(() => Effect.void), |
| 1180 | | ); |
| 1181 | | yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [ |
| 1182 | | "add", |
| 1183 | | "-A", |
| 1184 | | "--", |
| 1185 | | ...filePaths, |
| 1186 | | ]); |
| 1187 | | } else { |
| 1188 | | yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]); |
| 1189 | | } |
| 1165 | const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [ |
| 1166 | "diff", |
| 1167 | "--cached", |
| 1168 | "--name-status", |
| 1169 | ]).pipe(Effect.map((stdout) => stdout.trim())); |
| 1170 | if (stagedSummary.length === 0) { |
| 1171 | return null; |
| 1172 | } |
| 1190 | 1173 | |
| 1191 | | const stagedSummary = yield* runGitStdout( |
| 1192 | | "GitCore.prepareCommitContext.stagedSummary", |
| 1193 | | cwd, |
| 1194 | | ["diff", "--cached", "--name-status"], |
| 1195 | | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 1196 | | if (stagedSummary.length === 0) { |
| 1197 | | return null; |
| 1198 | | } |
| 1174 | const stagedPatch = yield* runGitStdoutWithOptions( |
| 1175 | "GitCore.prepareCommitContext.stagedPatch", |
| 1176 | cwd, |
| 1177 | ["diff", "--cached", "--patch", "--minimal"], |
| 1178 | { |
| 1179 | maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, |
| 1180 | truncateOutputAtMaxBytes: true, |
| 1181 | }, |
| 1182 | ); |
| 1183 | |
| 1184 | return { |
| 1185 | stagedSummary, |
| 1186 | stagedPatch, |
| 1187 | }; |
| 1188 | }); |
| 1199 | 1189 | |
| 1200 | | const stagedPatch = yield* runGitStdoutWithOptions( |
| 1201 | | "GitCore.prepareCommitContext.stagedPatch", |
| 1190 | const commit: GitCoreShape["commit"] = Effect.fn("commit")(function* ( |
| 1191 | cwd, |
| 1192 | subject, |
| 1193 | body, |
| 1194 | options?: GitCommitOptions, |
| 1195 | ) { |
| 1196 | const args = ["commit", "-m", subject]; |
| 1197 | const trimmedBody = body.trim(); |
| 1198 | if (trimmedBody.length > 0) { |
| 1199 | args.push("-m", trimmedBody); |
| 1200 | } |
| 1201 | const progress = |
| 1202 | options?.progress?.onOutputLine === undefined |
| 1203 | ? options?.progress |
| 1204 | : { |
| 1205 | ...options.progress, |
| 1206 | onStdoutLine: (line: string) => |
| 1207 | options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? Effect.void, |
| 1208 | onStderrLine: (line: string) => |
| 1209 | options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? Effect.void, |
| 1210 | }; |
| 1211 | yield* executeGit("GitCore.commit.commit", cwd, args, { |
| 1212 | ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), |
| 1213 | ...(progress ? { progress } : {}), |
| 1214 | }).pipe(Effect.asVoid); |
| 1215 | const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ |
| 1216 | "rev-parse", |
| 1217 | "HEAD", |
| 1218 | ]).pipe(Effect.map((stdout) => stdout.trim())); |
| 1219 | |
| 1220 | return { commitSha }; |
| 1221 | }); |
| 1222 | |
| 1223 | const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = Effect.fn("pushCurrentBranch")( |
| 1224 | function* (cwd, fallbackBranch) { |
| 1225 | const details = yield* statusDetails(cwd); |
| 1226 | const branch = details.branch ?? fallbackBranch; |
| 1227 | if (!branch) { |
| 1228 | return yield* createGitCommandError( |
| 1229 | "GitCore.pushCurrentBranch", |
| 1202 | 1230 | cwd, |
| 1203 | | ["diff", "--cached", "--patch", "--minimal"], |
| 1204 | | { |
| 1205 | | maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, |
| 1206 | | truncateOutputAtMaxBytes: true, |
| 1207 | | }, |
| 1231 | ["push"], |
| 1232 | "Cannot push from detached HEAD.", |
| 1208 | 1233 | ); |
| 1234 | } |
| 1209 | 1235 | |
| 1210 | | return { |
| 1211 | | stagedSummary, |
| 1212 | | stagedPatch, |
| 1213 | | }; |
| 1214 | | }); |
| 1215 | | |
| 1216 | | const commit: GitCoreShape["commit"] = (cwd, subject, body, options?: GitCommitOptions) => |
| 1217 | | Effect.gen(function* () { |
| 1218 | | const args = ["commit", "-m", subject]; |
| 1219 | | const trimmedBody = body.trim(); |
| 1220 | | if (trimmedBody.length > 0) { |
| 1221 | | args.push("-m", trimmedBody); |
| 1236 | const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; |
| 1237 | if (hasNoLocalDelta) { |
| 1238 | if (details.hasUpstream) { |
| 1239 | return { |
| 1240 | status: "skipped_up_to_date" as const, |
| 1241 | branch, |
| 1242 | ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), |
| 1243 | }; |
| 1222 | 1244 | } |
| 1223 | | const progress = options?.progress |
| 1224 | | ? { |
| 1225 | | ...(options.progress.onOutputLine |
| 1226 | | ? { |
| 1227 | | onStdoutLine: (line: string) => |
| 1228 | | options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? |
| 1229 | | Effect.void, |
| 1230 | | onStderrLine: (line: string) => |
| 1231 | | options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? |
| 1232 | | Effect.void, |
| 1233 | | } |
| 1234 | | : {}), |
| 1235 | | ...(options.progress.onHookStarted |
| 1236 | | ? { onHookStarted: options.progress.onHookStarted } |
| 1237 | | : {}), |
| 1238 | | ...(options.progress.onHookFinished |
| 1239 | | ? { onHookFinished: options.progress.onHookFinished } |
| 1240 | | : {}), |
| 1241 | | } |
| 1242 | | : null; |
| 1243 | | yield* executeGit("GitCore.commit.commit", cwd, args, { |
| 1244 | | ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), |
| 1245 | | ...(progress ? { progress } : {}), |
| 1246 | | }).pipe(Effect.asVoid); |
| 1247 | | const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ |
| 1248 | | "rev-parse", |
| 1249 | | "HEAD", |
| 1250 | | ]).pipe(Effect.map((stdout) => stdout.trim())); |
| 1251 | | |
| 1252 | | return { commitSha }; |
| 1253 | | }); |
| 1254 | 1245 | |
| 1255 | | const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) => |
| 1256 | | Effect.gen(function* () { |
| 1257 | | const details = yield* statusDetails(cwd); |
| 1258 | | const branch = details.branch ?? fallbackBranch; |
| 1259 | | if (!branch) { |
| 1260 | | return yield* createGitCommandError( |
| 1261 | | "GitCore.pushCurrentBranch", |
| 1262 | | cwd, |
| 1263 | | ["push"], |
| 1264 | | "Cannot push from detached HEAD.", |
| 1246 | const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( |
| 1247 | Effect.catch(() => Effect.succeed(null)), |
| 1248 | ); |
| 1249 | if (comparableBaseBranch) { |
| 1250 | const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( |
| 1251 | Effect.catch(() => Effect.succeed(null)), |
| 1265 | 1252 | ); |
| 1266 | | } |
| 1267 | | |
| 1268 | | const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; |
| 1269 | | if (hasNoLocalDelta) { |
| 1270 | | if (details.hasUpstream) { |
| 1253 | if (!publishRemoteName) { |
| 1271 | 1254 | return { |
| 1272 | 1255 | status: "skipped_up_to_date" as const, |
| 1273 | 1256 | branch, |
| 1274 | | ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), |
| 1275 | 1257 | }; |
| 1276 | 1258 | } |
| 1277 | 1259 | |
| 1278 | | const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( |
| 1279 | | Effect.catch(() => Effect.succeed(null)), |
| 1260 | const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe( |
| 1261 | Effect.catch(() => Effect.succeed(false)), |
| 1280 | 1262 | ); |
| 1281 | | if (comparableBaseBranch) { |
| 1282 | | const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( |
| 1283 | | Effect.catch(() => Effect.succeed(null)), |
| 1284 | | ); |
| 1285 | | if (!publishRemoteName) { |
| 1286 | | return { |
| 1287 | | status: "skipped_up_to_date" as const, |
| 1288 | | branch, |
| 1289 | | }; |
| 1290 | | } |
| 1291 | | |
| 1292 | | const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe( |
| 1293 | | Effect.catch(() => Effect.succeed(false)), |
| 1294 | | ); |
| 1295 | | if (hasRemoteBranch) { |
| 1296 | | return { |
| 1297 | | status: "skipped_up_to_date" as const, |
| 1298 | | branch, |
| 1299 | | }; |
| 1300 | | } |
| 1263 | if (hasRemoteBranch) { |
| 1264 | return { |
| 1265 | status: "skipped_up_to_date" as const, |
| 1266 | branch, |
| 1267 | }; |
| 1301 | 1268 | } |
| 1302 | 1269 | } |
| 1270 | } |
| 1303 | 1271 | |
| 1304 | | if (!details.hasUpstream) { |
| 1305 | | const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); |
| 1306 | | if (!publishRemoteName) { |
| 1307 | | return yield* createGitCommandError( |
| 1308 | | "GitCore.pushCurrentBranch", |
| 1309 | | cwd, |
| 1310 | | ["push"], |
| 1311 | | "Cannot push because no git remote is configured for this repository.", |
| 1312 | | ); |
| 1313 | | } |
| 1314 | | yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [ |
| 1315 | | "push", |
| 1316 | | "-u", |
| 1317 | | publishRemoteName, |
| 1318 | | branch, |
| 1319 | | ]); |
| 1320 | | return { |
| 1321 | | status: "pushed" as const, |
| 1322 | | branch, |
| 1323 | | upstreamBranch: `${publishRemoteName}/${branch}`, |
| 1324 | | setUpstream: true, |
| 1325 | | }; |
| 1326 | | } |
| 1327 | | |
| 1328 | | const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe( |
| 1329 | | Effect.catch(() => Effect.succeed(null)), |
| 1330 | | ); |
| 1331 | | if (currentUpstream) { |
| 1332 | | yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [ |
| 1333 | | "push", |
| 1334 | | currentUpstream.remoteName, |
| 1335 | | `HEAD:${currentUpstream.upstreamBranch}`, |
| 1336 | | ]); |
| 1337 | | return { |
| 1338 | | status: "pushed" as const, |
| 1339 | | branch, |
| 1340 | | upstreamBranch: currentUpstream.upstreamRef, |
| 1341 | | setUpstream: false, |
| 1342 | | }; |
| 1272 | if (!details.hasUpstream) { |
| 1273 | const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); |
| 1274 | if (!publishRemoteName) { |
| 1275 | return yield* createGitCommandError( |
| 1276 | "GitCore.pushCurrentBranch", |
| 1277 | cwd, |
| 1278 | ["push"], |
| 1279 | "Cannot push because no git remote is configured for this repository.", |
| 1280 | ); |
| 1343 | 1281 | } |
| 1282 | yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [ |
| 1283 | "push", |
| 1284 | "-u", |
| 1285 | publishRemoteName, |
| 1286 | branch, |
| 1287 | ]); |
| 1288 | return { |
| 1289 | status: "pushed" as const, |
| 1290 | branch, |
| 1291 | upstreamBranch: `${publishRemoteName}/${branch}`, |
| 1292 | setUpstream: true, |
| 1293 | }; |
| 1294 | } |
| 1344 | 1295 | |
| 1345 | | yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]); |
| 1296 | const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe( |
| 1297 | Effect.catch(() => Effect.succeed(null)), |
| 1298 | ); |
| 1299 | if (currentUpstream) { |
| 1300 | yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [ |
| 1301 | "push", |
| 1302 | currentUpstream.remoteName, |
| 1303 | `HEAD:${currentUpstream.upstreamBranch}`, |
| 1304 | ]); |
| 1346 | 1305 | return { |
| 1347 | 1306 | status: "pushed" as const, |
| 1348 | 1307 | branch, |
| 1349 | | ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), |
| 1308 | upstreamBranch: currentUpstream.upstreamRef, |
| 1350 | 1309 | setUpstream: false, |
| 1351 | 1310 | }; |
| 1352 | | }); |
| 1311 | } |
| 1353 | 1312 | |
| 1354 | | const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) => |
| 1355 | | Effect.gen(function* () { |
| 1356 | | const details = yield* statusDetails(cwd); |
| 1357 | | const branch = details.branch; |
| 1358 | | if (!branch) { |
| 1359 | | return yield* createGitCommandError( |
| 1360 | | "GitCore.pullCurrentBranch", |
| 1361 | | cwd, |
| 1362 | | ["pull", "--ff-only"], |
| 1363 | | "Cannot pull from detached HEAD.", |
| 1364 | | ); |
| 1365 | | } |
| 1366 | | if (!details.hasUpstream) { |
| 1367 | | return yield* createGitCommandError( |
| 1368 | | "GitCore.pullCurrentBranch", |
| 1369 | | cwd, |
| 1370 | | ["pull", "--ff-only"], |
| 1371 | | "Current branch has no upstream configured. Push with upstream first.", |
| 1372 | | ); |
| 1373 | | } |
| 1374 | | const beforeSha = yield* runGitStdout( |
| 1375 | | "GitCore.pullCurrentBranch.beforeSha", |
| 1313 | yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]); |
| 1314 | return { |
| 1315 | status: "pushed" as const, |
| 1316 | branch, |
| 1317 | ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), |
| 1318 | setUpstream: false, |
| 1319 | }; |
| 1320 | }, |
| 1321 | ); |
| 1322 | |
| 1323 | const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = Effect.fn("pullCurrentBranch")( |
| 1324 | function* (cwd) { |
| 1325 | const details = yield* statusDetails(cwd); |
| 1326 | const branch = details.branch; |
| 1327 | if (!branch) { |
| 1328 | return yield* createGitCommandError( |
| 1329 | "GitCore.pullCurrentBranch", |
| 1376 | 1330 | cwd, |
| 1377 | | ["rev-parse", "HEAD"], |
| 1378 | | true, |
| 1379 | | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 1380 | | yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { |
| 1381 | | timeoutMs: 30_000, |
| 1382 | | fallbackErrorMessage: "git pull failed", |
| 1383 | | }); |
| 1384 | | const afterSha = yield* runGitStdout( |
| 1385 | | "GitCore.pullCurrentBranch.afterSha", |
| 1331 | ["pull", "--ff-only"], |
| 1332 | "Cannot pull from detached HEAD.", |
| 1333 | ); |
| 1334 | } |
| 1335 | if (!details.hasUpstream) { |
| 1336 | return yield* createGitCommandError( |
| 1337 | "GitCore.pullCurrentBranch", |
| 1386 | 1338 | cwd, |
| 1387 | | ["rev-parse", "HEAD"], |
| 1388 | | true, |
| 1389 | | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 1390 | | |
| 1391 | | const refreshed = yield* statusDetails(cwd); |
| 1392 | | return { |
| 1393 | | status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", |
| 1394 | | branch, |
| 1395 | | upstreamBranch: refreshed.upstreamRef, |
| 1396 | | }; |
| 1339 | ["pull", "--ff-only"], |
| 1340 | "Current branch has no upstream configured. Push with upstream first.", |
| 1341 | ); |
| 1342 | } |
| 1343 | const beforeSha = yield* runGitStdout( |
| 1344 | "GitCore.pullCurrentBranch.beforeSha", |
| 1345 | cwd, |
| 1346 | ["rev-parse", "HEAD"], |
| 1347 | true, |
| 1348 | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 1349 | yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { |
| 1350 | timeoutMs: 30_000, |
| 1351 | fallbackErrorMessage: "git pull failed", |
| 1397 | 1352 | }); |
| 1353 | const afterSha = yield* runGitStdout( |
| 1354 | "GitCore.pullCurrentBranch.afterSha", |
| 1355 | cwd, |
| 1356 | ["rev-parse", "HEAD"], |
| 1357 | true, |
| 1358 | ).pipe(Effect.map((stdout) => stdout.trim())); |
| 1359 | |
| 1360 | const refreshed = yield* statusDetails(cwd); |
| 1361 | return { |
| 1362 | status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", |
| 1363 | branch, |
| 1364 | upstreamBranch: refreshed.upstreamRef, |
| 1365 | }; |
| 1366 | }, |
| 1367 | ); |
| 1398 | 1368 | |
| 1399 | | const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) => |
| 1400 | | Effect.gen(function* () { |
| 1401 | | const range = `${baseBranch}..HEAD`; |
| 1402 | | const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( |
| 1403 | | [ |
| 1404 | | runGitStdoutWithOptions( |
| 1405 | | "GitCore.readRangeContext.log", |
| 1406 | | cwd, |
| 1407 | | ["log", "--oneline", range], |
| 1408 | | { |
| 1409 | | maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES, |
| 1410 | | truncateOutputAtMaxBytes: true, |
| 1411 | | }, |
| 1412 | | ), |
| 1413 | | runGitStdoutWithOptions( |
| 1414 | | "GitCore.readRangeContext.diffStat", |
| 1415 | | cwd, |
| 1416 | | ["diff", "--stat", range], |
| 1417 | | { |
| 1418 | | maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, |
| 1419 | | truncateOutputAtMaxBytes: true, |
| 1420 | | }, |
| 1421 | | ), |
| 1422 | | runGitStdoutWithOptions( |
| 1423 | | "GitCore.readRangeContext.diffPatch", |
| 1424 | | cwd, |
| 1425 | | ["diff", "--patch", "--minimal", range], |
| 1426 | | { |
| 1427 | | maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, |
| 1428 | | truncateOutputAtMaxBytes: true, |
| 1429 | | }, |
| 1430 | | ), |
| 1431 | | ], |
| 1432 | | { concurrency: "unbounded" }, |
| 1433 | | ); |
| 1369 | const readRangeContext: GitCoreShape["readRangeContext"] = Effect.fn("readRangeContext")( |
| 1370 | function* (cwd, baseBranch) { |
| 1371 | const range = `${baseBranch}..HEAD`; |
| 1372 | const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( |
| 1373 | [ |
| 1374 | runGitStdoutWithOptions( |
| 1375 | "GitCore.readRangeContext.log", |
| 1376 | cwd, |
| 1377 | ["log", "--oneline", range], |
| 1378 | { |
| 1379 | maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES, |
| 1380 | truncateOutputAtMaxBytes: true, |
| 1381 | }, |
| 1382 | ), |
| 1383 | runGitStdoutWithOptions( |
| 1384 | "GitCore.readRangeContext.diffStat", |
| 1385 | cwd, |
| 1386 | ["diff", "--stat", range], |
| 1387 | { |
| 1388 | maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, |
| 1389 | truncateOutputAtMaxBytes: true, |
| 1390 | }, |
| 1391 | ), |
| 1392 | runGitStdoutWithOptions( |
| 1393 | "GitCore.readRangeContext.diffPatch", |
| 1394 | cwd, |
| 1395 | ["diff", "--patch", "--minimal", range], |
| 1396 | { |
| 1397 | maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, |
| 1398 | truncateOutputAtMaxBytes: true, |
| 1399 | }, |
| 1400 | ), |
| 1401 | ], |
| 1402 | { concurrency: "unbounded" }, |
| 1403 | ); |
| 1434 | 1404 | |
| 1435 | | return { |
| 1436 | | commitSummary, |
| 1437 | | diffSummary, |
| 1438 | | diffPatch, |
| 1439 | | }; |
| 1440 | | }); |
| 1405 | return { |
| 1406 | commitSummary, |
| 1407 | diffSummary, |
| 1408 | diffPatch, |
| 1409 | }; |
| 1410 | }, |
| 1411 | ); |
| 1412 | |
| 1413 | const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => |
| 1414 | runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( |
| 1415 | Effect.map((stdout) => stdout.trim()), |
| 1416 | Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), |
| 1417 | ); |
| 1418 | |
| 1419 | const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) { |
| 1420 | const branchRecencyPromise = readBranchRecency(input.cwd).pipe( |
| 1421 | Effect.catch(() => Effect.succeed(new Map<string, number>())), |
| 1422 | ); |
| 1423 | const localBranchResult = yield* executeGit( |
| 1424 | "GitCore.listBranches.branchNoColor", |
| 1425 | input.cwd, |
| 1426 | ["branch", "--no-color"], |
| 1427 | { |
| 1428 | timeoutMs: 10_000, |
| 1429 | allowNonZeroExit: true, |
| 1430 | }, |
| 1431 | ); |
| 1441 | 1432 | |
| 1442 | | const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => |
| 1443 | | runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( |
| 1444 | | Effect.map((stdout) => stdout.trim()), |
| 1445 | | Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), |
| 1433 | if (localBranchResult.code !== 0) { |
| 1434 | const stderr = localBranchResult.stderr.trim(); |
| 1435 | if (stderr.toLowerCase().includes("not a git repository")) { |
| 1436 | return { branches: [], isRepo: false, hasOriginRemote: false }; |
| 1437 | } |
| 1438 | return yield* createGitCommandError( |
| 1439 | "GitCore.listBranches", |
| 1440 | input.cwd, |
| 1441 | ["branch", "--no-color"], |
| 1442 | stderr || "git branch failed", |
| 1446 | 1443 | ); |
| 1444 | } |
| 1447 | 1445 | |
| 1448 | | const listBranches: GitCoreShape["listBranches"] = (input) => |
| 1449 | | Effect.gen(function* () { |
| 1450 | | const branchRecencyPromise = readBranchRecency(input.cwd).pipe( |
| 1451 | | Effect.catch(() => Effect.succeed(new Map<string, number>())), |
| 1452 | | ); |
| 1453 | | const localBranchResult = yield* executeGit( |
| 1454 | | "GitCore.listBranches.branchNoColor", |
| 1455 | | input.cwd, |
| 1456 | | ["branch", "--no-color"], |
| 1457 | | { |
| 1458 | | timeoutMs: 10_000, |
| 1459 | | allowNonZeroExit: true, |
| 1460 | | }, |
| 1461 | | ); |
| 1446 | const remoteBranchResultEffect = executeGit( |
| 1447 | "GitCore.listBranches.remoteBranches", |
| 1448 | input.cwd, |
| 1449 | ["branch", "--no-color", "--remotes"], |
| 1450 | { |
| 1451 | timeoutMs: 10_000, |
| 1452 | allowNonZeroExit: true, |
| 1453 | }, |
| 1454 | ).pipe( |
| 1455 | Effect.catch((error) => |
| 1456 | Effect.logWarning( |
| 1457 | `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`, |
| 1458 | ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), |
| 1459 | ), |
| 1460 | ); |
| 1461 | |
| 1462 | const remoteNamesResultEffect = executeGit( |
| 1463 | "GitCore.listBranches.remoteNames", |
| 1464 | input.cwd, |
| 1465 | ["remote"], |
| 1466 | { |
| 1467 | timeoutMs: 5_000, |
| 1468 | allowNonZeroExit: true, |
| 1469 | }, |
| 1470 | ).pipe( |
| 1471 | Effect.catch((error) => |
| 1472 | Effect.logWarning( |
| 1473 | `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`, |
| 1474 | ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), |
| 1475 | ), |
| 1476 | ); |
| 1462 | 1477 | |
| 1463 | | if (localBranchResult.code !== 0) { |
| 1464 | | const stderr = localBranchResult.stderr.trim(); |
| 1465 | | if (stderr.toLowerCase().includes("not a git repository")) { |
| 1466 | | return { branches: [], isRepo: false, hasOriginRemote: false }; |
| 1467 | | } |
| 1468 | | return yield* createGitCommandError( |
| 1469 | | "GitCore.listBranches", |
| 1478 | const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] = |
| 1479 | yield* Effect.all( |
| 1480 | [ |
| 1481 | executeGit( |
| 1482 | "GitCore.listBranches.defaultRef", |
| 1470 | 1483 | input.cwd, |
| 1471 | | ["branch", "--no-color"], |
| 1472 | | stderr || "git branch failed", |
| 1473 | | ); |
| 1474 | | } |
| 1475 | | |
| 1476 | | const remoteBranchResultEffect = executeGit( |
| 1477 | | "GitCore.listBranches.remoteBranches", |
| 1478 | | input.cwd, |
| 1479 | | ["branch", "--no-color", "--remotes"], |
| 1480 | | { |
| 1481 | | timeoutMs: 10_000, |
| 1482 | | allowNonZeroExit: true, |
| 1483 | | }, |
| 1484 | | ).pipe( |
| 1485 | | Effect.catch((error) => |
| 1486 | | Effect.logWarning( |
| 1487 | | `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`, |
| 1488 | | ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), |
| 1484 | ["symbolic-ref", "refs/remotes/origin/HEAD"], |
| 1485 | { |
| 1486 | timeoutMs: 5_000, |
| 1487 | allowNonZeroExit: true, |
| 1488 | }, |
| 1489 | 1489 | ), |
| 1490 | | ); |
| 1491 | | |
| 1492 | | const remoteNamesResultEffect = executeGit( |
| 1493 | | "GitCore.listBranches.remoteNames", |
| 1494 | | input.cwd, |
| 1495 | | ["remote"], |
| 1496 | | { |
| 1497 | | timeoutMs: 5_000, |
| 1498 | | allowNonZeroExit: true, |
| 1499 | | }, |
| 1500 | | ).pipe( |
| 1501 | | Effect.catch((error) => |
| 1502 | | Effect.logWarning( |
| 1503 | | `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`, |
| 1504 | | ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), |
| 1490 | executeGit( |
| 1491 | "GitCore.listBranches.worktreeList", |
| 1492 | input.cwd, |
| 1493 | ["worktree", "list", "--porcelain"], |
| 1494 | { |
| 1495 | timeoutMs: 5_000, |
| 1496 | allowNonZeroExit: true, |
| 1497 | }, |
| 1505 | 1498 | ), |
| 1506 | | ); |
| 1499 | remoteBranchResultEffect, |
| 1500 | remoteNamesResultEffect, |
| 1501 | branchRecencyPromise, |
| 1502 | ], |
| 1503 | { concurrency: "unbounded" }, |
| 1504 | ); |
| 1507 | 1505 | |
| 1508 | | const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] = |
| 1509 | | yield* Effect.all( |
| 1510 | | [ |
| 1511 | | executeGit( |
| 1512 | | "GitCore.listBranches.defaultRef", |
| 1513 | | input.cwd, |
| 1514 | | ["symbolic-ref", "refs/remotes/origin/HEAD"], |
| 1515 | | { |
| 1516 | | timeoutMs: 5_000, |
| 1517 | | allowNonZeroExit: true, |
| 1518 | | }, |
| 1519 | | ), |
| 1520 | | executeGit( |
| 1521 | | "GitCore.listBranches.worktreeList", |
| 1522 | | input.cwd, |
| 1523 | | ["worktree", "list", "--porcelain"], |
| 1524 | | { |
| 1525 | | timeoutMs: 5_000, |
| 1526 | | allowNonZeroExit: true, |
| 1527 | | }, |
| 1528 | | ), |
| 1529 | | remoteBranchResultEffect, |
| 1530 | | remoteNamesResultEffect, |
| 1531 | | branchRecencyPromise, |
| 1532 | | ], |
| 1533 | | { concurrency: "unbounded" }, |
| 1534 | | ); |
| 1506 | const remoteNames = |
| 1507 | remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; |
| 1508 | if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) { |
| 1509 | yield* Effect.logWarning( |
| 1510 | `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`, |
| 1511 | ); |
| 1512 | } |
| 1513 | if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) { |
| 1514 | yield* Effect.logWarning( |
| 1515 | `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, |
| 1516 | ); |
| 1517 | } |
| 1535 | 1518 | |
| 1536 | | const remoteNames = |
| 1537 | | remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; |
| 1538 | | if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) { |
| 1539 | | yield* Effect.logWarning( |
| 1540 | | `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`, |
| 1541 | | ); |
| 1542 | | } |
| 1543 | | if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) { |
| 1544 | | yield* Effect.logWarning( |
| 1545 | | `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, |
| 1519 | const defaultBranch = |
| 1520 | defaultRef.code === 0 |
| 1521 | ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") |
| 1522 | : null; |
| 1523 | |
| 1524 | const worktreeMap = new Map<string, string>(); |
| 1525 | if (worktreeList.code === 0) { |
| 1526 | let currentPath: string | null = null; |
| 1527 | for (const line of worktreeList.stdout.split("\n")) { |
| 1528 | if (line.startsWith("worktree ")) { |
| 1529 | const candidatePath = line.slice("worktree ".length); |
| 1530 | const exists = yield* fileSystem.stat(candidatePath).pipe( |
| 1531 | Effect.map(() => true), |
| 1532 | Effect.catch(() => Effect.succeed(false)), |
| 1546 | 1533 | ); |
| 1534 | currentPath = exists ? candidatePath : null; |
| 1535 | } else if (line.startsWith("branch refs/heads/") && currentPath) { |
| 1536 | worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); |
| 1537 | } else if (line === "") { |
| 1538 | currentPath = null; |
| 1547 | 1539 | } |
| 1540 | } |
| 1541 | } |
| 1548 | 1542 | |
| 1549 | | const defaultBranch = |
| 1550 | | defaultRef.code === 0 |
| 1551 | | ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") |
| 1552 | | : null; |
| 1553 | | |
| 1554 | | const worktreeMap = new Map<string, string>(); |
| 1555 | | if (worktreeList.code === 0) { |
| 1556 | | let currentPath: string | null = null; |
| 1557 | | for (const line of worktreeList.stdout.split("\n")) { |
| 1558 | | if (line.startsWith("worktree ")) { |
| 1559 | | const candidatePath = line.slice("worktree ".length); |
| 1560 | | const exists = yield* fileSystem.stat(candidatePath).pipe( |
| 1561 | | Effect.map(() => true), |
| 1562 | | Effect.catch(() => Effect.succeed(false)), |
| 1563 | | ); |
| 1564 | | currentPath = exists ? candidatePath : null; |
| 1565 | | } else if (line.startsWith("branch refs/heads/") && currentPath) { |
| 1566 | | worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); |
| 1567 | | } else if (line === "") { |
| 1568 | | currentPath = null; |
| 1569 | | } |
| 1570 | | } |
| 1571 | | } |
| 1572 | | |
| 1573 | | const localBranches = localBranchResult.stdout |
| 1574 | | .split("\n") |
| 1575 | | .map(parseBranchLine) |
| 1576 | | .filter((branch): branch is { name: string; current: boolean } => branch !== null) |
| 1577 | | .map((branch) => ({ |
| 1578 | | name: branch.name, |
| 1579 | | current: branch.current, |
| 1580 | | isRemote: false, |
| 1581 | | isDefault: branch.name === defaultBranch, |
| 1582 | | worktreePath: worktreeMap.get(branch.name) ?? null, |
| 1583 | | })) |
| 1584 | | .toSorted((a, b) => { |
| 1585 | | const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; |
| 1586 | | const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; |
| 1587 | | if (aPriority !== bPriority) return aPriority - bPriority; |
| 1588 | | |
| 1589 | | const aLastCommit = branchLastCommit.get(a.name) ?? 0; |
| 1590 | | const bLastCommit = branchLastCommit.get(b.name) ?? 0; |
| 1591 | | if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; |
| 1592 | | return a.name.localeCompare(b.name); |
| 1593 | | }); |
| 1594 | | |
| 1595 | | const remoteBranches = |
| 1596 | | remoteBranchResult.code === 0 |
| 1597 | | ? remoteBranchResult.stdout |
| 1598 | | .split("\n") |
| 1599 | | .map(parseBranchLine) |
| 1600 | | .filter((branch): branch is { name: string; current: boolean } => branch !== null) |
| 1601 | | .map((branch) => { |
| 1602 | | const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames); |
| 1603 | | const remoteBranch: { |
| 1604 | | name: string; |
| 1605 | | current: boolean; |
| 1606 | | isRemote: boolean; |
| 1607 | | remoteName?: string; |
| 1608 | | isDefault: boolean; |
| 1609 | | worktreePath: string | null; |
| 1610 | | } = { |
| 1611 | | name: branch.name, |
| 1612 | | current: false, |
| 1613 | | isRemote: true, |
| 1614 | | isDefault: false, |
| 1615 | | worktreePath: null, |
| 1616 | | }; |
| 1617 | | if (parsedRemoteRef) { |
| 1618 | | remoteBranch.remoteName = parsedRemoteRef.remoteName; |
| 1619 | | } |
| 1620 | | return remoteBranch; |
| 1621 | | }) |
| 1622 | | .toSorted((a, b) => { |
| 1623 | | const aLastCommit = branchLastCommit.get(a.name) ?? 0; |
| 1624 | | const bLastCommit = branchLastCommit.get(b.name) ?? 0; |
| 1625 | | if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; |
| 1626 | | return a.name.localeCompare(b.name); |
| 1627 | | }) |
| 1628 | | : []; |
| 1629 | | |
| 1630 | | const branches = [...localBranches, ...remoteBranches]; |
| 1631 | | |
| 1632 | | return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") }; |
| 1543 | const localBranches = localBranchResult.stdout |
| 1544 | .split("\n") |
| 1545 | .map(parseBranchLine) |
| 1546 | .filter((branch): branch is { name: string; current: boolean } => branch !== null) |
| 1547 | .map((branch) => ({ |
| 1548 | name: branch.name, |
| 1549 | current: branch.current, |
| 1550 | isRemote: false, |
| 1551 | isDefault: branch.name === defaultBranch, |
| 1552 | worktreePath: worktreeMap.get(branch.name) ?? null, |
| 1553 | })) |
| 1554 | .toSorted((a, b) => { |
| 1555 | const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; |
| 1556 | const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; |
| 1557 | if (aPriority !== bPriority) return aPriority - bPriority; |
| 1558 | |
| 1559 | const aLastCommit = branchLastCommit.get(a.name) ?? 0; |
| 1560 | const bLastCommit = branchLastCommit.get(b.name) ?? 0; |
| 1561 | if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; |
| 1562 | return a.name.localeCompare(b.name); |
| 1633 | 1563 | }); |
| 1634 | 1564 | |
| 1635 | | const createWorktree: GitCoreShape["createWorktree"] = (input) => |
| 1636 | | Effect.gen(function* () { |
| 1637 | | const targetBranch = input.newBranch ?? input.branch; |
| 1638 | | const sanitizedBranch = targetBranch.replace(/\//g, "-"); |
| 1639 | | const repoName = path.basename(input.cwd); |
| 1640 | | const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch); |
| 1641 | | const args = input.newBranch |
| 1642 | | ? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch] |
| 1643 | | : ["worktree", "add", worktreePath, input.branch]; |
| 1644 | | |
| 1645 | | yield* executeGit("GitCore.createWorktree", input.cwd, args, { |
| 1646 | | fallbackErrorMessage: "git worktree add failed", |
| 1647 | | }); |
| 1565 | const remoteBranches = |
| 1566 | remoteBranchResult.code === 0 |
| 1567 | ? remoteBranchResult.stdout |
| 1568 | .split("\n") |
| 1569 | .map(parseBranchLine) |
| 1570 | .filter((branch): branch is { name: string; current: boolean } => branch !== null) |
| 1571 | .map((branch) => { |
| 1572 | const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames); |
| 1573 | const remoteBranch: { |
| 1574 | name: string; |
| 1575 | current: boolean; |
| 1576 | isRemote: boolean; |
| 1577 | remoteName?: string; |
| 1578 | isDefault: boolean; |
| 1579 | worktreePath: string | null; |
| 1580 | } = { |
| 1581 | name: branch.name, |
| 1582 | current: false, |
| 1583 | isRemote: true, |
| 1584 | isDefault: false, |
| 1585 | worktreePath: null, |
| 1586 | }; |
| 1587 | if (parsedRemoteRef) { |
| 1588 | remoteBranch.remoteName = parsedRemoteRef.remoteName; |
| 1589 | } |
| 1590 | return remoteBranch; |
| 1591 | }) |
| 1592 | .toSorted((a, b) => { |
| 1593 | const aLastCommit = branchLastCommit.get(a.name) ?? 0; |
| 1594 | const bLastCommit = branchLastCommit.get(b.name) ?? 0; |
| 1595 | if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; |
| 1596 | return a.name.localeCompare(b.name); |
| 1597 | }) |
| 1598 | : []; |
| 1599 | |
| 1600 | const branches = [...localBranches, ...remoteBranches]; |
| 1601 | |
| 1602 | return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") }; |
| 1603 | }); |
| 1648 | 1604 | |
| 1649 | | return { |
| 1650 | | worktree: { |
| 1651 | | path: worktreePath, |
| 1652 | | branch: targetBranch, |
| 1653 | | }, |
| 1654 | | }; |
| 1605 | const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")( |
| 1606 | function* (input) { |
| 1607 | const targetBranch = input.newBranch ?? input.branch; |
| 1608 | const sanitizedBranch = targetBranch.replace(/\//g, "-"); |
| 1609 | const repoName = path.basename(input.cwd); |
| 1610 | const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch); |
| 1611 | const args = input.newBranch |
| 1612 | ? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch] |
| 1613 | : ["worktree", "add", worktreePath, input.branch]; |
| 1614 | |
| 1615 | yield* executeGit("GitCore.createWorktree", input.cwd, args, { |
| 1616 | fallbackErrorMessage: "git worktree add failed", |
| 1655 | 1617 | }); |
| 1656 | 1618 | |
| 1657 | | const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = (input) => |
| 1658 | | Effect.gen(function* () { |
| 1659 | | const remoteName = yield* resolvePrimaryRemoteName(input.cwd); |
| 1660 | | yield* executeGit( |
| 1661 | | "GitCore.fetchPullRequestBranch", |
| 1662 | | input.cwd, |
| 1663 | | [ |
| 1664 | | "fetch", |
| 1665 | | "--quiet", |
| 1666 | | "--no-tags", |
| 1667 | | remoteName, |
| 1668 | | `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, |
| 1669 | | ], |
| 1670 | | { |
| 1671 | | fallbackErrorMessage: "git fetch pull request branch failed", |
| 1672 | | }, |
| 1673 | | ); |
| 1674 | | }).pipe(Effect.asVoid); |
| 1675 | | |
| 1676 | | const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = (input) => |
| 1677 | | Effect.gen(function* () { |
| 1678 | | yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [ |
| 1679 | | "fetch", |
| 1680 | | "--quiet", |
| 1681 | | "--no-tags", |
| 1682 | | input.remoteName, |
| 1683 | | `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, |
| 1684 | | ]); |
| 1619 | return { |
| 1620 | worktree: { |
| 1621 | path: worktreePath, |
| 1622 | branch: targetBranch, |
| 1623 | }, |
| 1624 | }; |
| 1625 | }, |
| 1626 | ); |
| 1685 | 1627 | |
| 1686 | | const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch); |
| 1687 | | const targetRef = `${input.remoteName}/${input.remoteBranch}`; |
| 1688 | | yield* runGit( |
| 1689 | | "GitCore.fetchRemoteBranch.materialize", |
| 1690 | | input.cwd, |
| 1691 | | localBranchAlreadyExists |
| 1692 | | ? ["branch", "--force", input.localBranch, targetRef] |
| 1693 | | : ["branch", input.localBranch, targetRef], |
| 1694 | | ); |
| 1695 | | }).pipe(Effect.asVoid); |
| 1696 | | |
| 1697 | | const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) => |
| 1698 | | runGit("GitCore.setBranchUpstream", input.cwd, [ |
| 1699 | | "branch", |
| 1700 | | "--set-upstream-to", |
| 1701 | | `${input.remoteName}/${input.remoteBranch}`, |
| 1702 | | input.branch, |
| 1628 | const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = Effect.fn( |
| 1629 | "fetchPullRequestBranch", |
| 1630 | )(function* (input) { |
| 1631 | const remoteName = yield* resolvePrimaryRemoteName(input.cwd); |
| 1632 | yield* executeGit( |
| 1633 | "GitCore.fetchPullRequestBranch", |
| 1634 | input.cwd, |
| 1635 | [ |
| 1636 | "fetch", |
| 1637 | "--quiet", |
| 1638 | "--no-tags", |
| 1639 | remoteName, |
| 1640 | `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, |
| 1641 | ], |
| 1642 | { |
| 1643 | fallbackErrorMessage: "git fetch pull request branch failed", |
| 1644 | }, |
| 1645 | ); |
| 1646 | }); |
| 1647 | |
| 1648 | const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = Effect.fn("fetchRemoteBranch")( |
| 1649 | function* (input) { |
| 1650 | yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [ |
| 1651 | "fetch", |
| 1652 | "--quiet", |
| 1653 | "--no-tags", |
| 1654 | input.remoteName, |
| 1655 | `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, |
| 1703 | 1656 | ]); |
| 1704 | 1657 | |
| 1705 | | const removeWorktree: GitCoreShape["removeWorktree"] = (input) => |
| 1706 | | Effect.gen(function* () { |
| 1707 | | const args = ["worktree", "remove"]; |
| 1708 | | if (input.force) { |
| 1709 | | args.push("--force"); |
| 1710 | | } |
| 1711 | | args.push(input.path); |
| 1712 | | yield* executeGit("GitCore.removeWorktree", input.cwd, args, { |
| 1713 | | timeoutMs: 15_000, |
| 1714 | | fallbackErrorMessage: "git worktree remove failed", |
| 1715 | | }).pipe( |
| 1716 | | Effect.mapError((error) => |
| 1717 | | createGitCommandError( |
| 1718 | | "GitCore.removeWorktree", |
| 1719 | | input.cwd, |
| 1720 | | args, |
| 1721 | | `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, |
| 1722 | | error, |
| 1723 | | ), |
| 1724 | | ), |
| 1725 | | ); |
| 1726 | | }); |
| 1658 | const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch); |
| 1659 | const targetRef = `${input.remoteName}/${input.remoteBranch}`; |
| 1660 | yield* runGit( |
| 1661 | "GitCore.fetchRemoteBranch.materialize", |
| 1662 | input.cwd, |
| 1663 | localBranchAlreadyExists |
| 1664 | ? ["branch", "--force", input.localBranch, targetRef] |
| 1665 | : ["branch", input.localBranch, targetRef], |
| 1666 | ); |
| 1667 | }, |
| 1668 | ); |
| 1727 | 1669 | |
| 1728 | | const renameBranch: GitCoreShape["renameBranch"] = (input) => |
| 1729 | | Effect.gen(function* () { |
| 1730 | | if (input.oldBranch === input.newBranch) { |
| 1731 | | return { branch: input.newBranch }; |
| 1732 | | } |
| 1733 | | const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch); |
| 1734 | | |
| 1735 | | yield* executeGit( |
| 1736 | | "GitCore.renameBranch", |
| 1737 | | input.cwd, |
| 1738 | | ["branch", "-m", "--", input.oldBranch, targetBranch], |
| 1739 | | { |
| 1740 | | timeoutMs: 10_000, |
| 1741 | | fallbackErrorMessage: "git branch rename failed", |
| 1742 | | }, |
| 1743 | | ); |
| 1670 | const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) => |
| 1671 | runGit("GitCore.setBranchUpstream", input.cwd, [ |
| 1672 | "branch", |
| 1673 | "--set-upstream-to", |
| 1674 | `${input.remoteName}/${input.remoteBranch}`, |
| 1675 | input.branch, |
| 1676 | ]); |
| 1677 | |
| 1678 | const removeWorktree: GitCoreShape["removeWorktree"] = Effect.fn("removeWorktree")( |
| 1679 | function* (input) { |
| 1680 | const args = ["worktree", "remove"]; |
| 1681 | if (input.force) { |
| 1682 | args.push("--force"); |
| 1683 | } |
| 1684 | args.push(input.path); |
| 1685 | yield* executeGit("GitCore.removeWorktree", input.cwd, args, { |
| 1686 | timeoutMs: 15_000, |
| 1687 | fallbackErrorMessage: "git worktree remove failed", |
| 1688 | }).pipe( |
| 1689 | Effect.mapError((error) => |
| 1690 | createGitCommandError( |
| 1691 | "GitCore.removeWorktree", |
| 1692 | input.cwd, |
| 1693 | args, |
| 1694 | `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, |
| 1695 | error, |
| 1696 | ), |
| 1697 | ), |
| 1698 | ); |
| 1699 | }, |
| 1700 | ); |
| 1744 | 1701 | |
| 1745 | | return { branch: targetBranch }; |
| 1746 | | }); |
| 1702 | const renameBranch: GitCoreShape["renameBranch"] = Effect.fn("renameBranch")(function* (input) { |
| 1703 | if (input.oldBranch === input.newBranch) { |
| 1704 | return { branch: input.newBranch }; |
| 1705 | } |
| 1706 | const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch); |
| 1747 | 1707 | |
| 1748 | | const createBranch: GitCoreShape["createBranch"] = (input) => |
| 1749 | | executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { |
| 1708 | yield* executeGit( |
| 1709 | "GitCore.renameBranch", |
| 1710 | input.cwd, |
| 1711 | ["branch", "-m", "--", input.oldBranch, targetBranch], |
| 1712 | { |
| 1750 | 1713 | timeoutMs: 10_000, |
| 1751 | | fallbackErrorMessage: "git branch create failed", |
| 1752 | | }).pipe(Effect.asVoid); |
| 1714 | fallbackErrorMessage: "git branch rename failed", |
| 1715 | }, |
| 1716 | ); |
| 1753 | 1717 | |
| 1754 | | const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) => |
| 1755 | | Effect.gen(function* () { |
| 1756 | | const [localInputExists, remoteExists] = yield* Effect.all( |
| 1757 | | [ |
| 1758 | | executeGit( |
| 1759 | | "GitCore.checkoutBranch.localInputExists", |
| 1760 | | input.cwd, |
| 1761 | | ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`], |
| 1762 | | { |
| 1763 | | timeoutMs: 5_000, |
| 1764 | | allowNonZeroExit: true, |
| 1765 | | }, |
| 1766 | | ).pipe(Effect.map((result) => result.code === 0)), |
| 1767 | | executeGit( |
| 1768 | | "GitCore.checkoutBranch.remoteExists", |
| 1769 | | input.cwd, |
| 1770 | | ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`], |
| 1771 | | { |
| 1772 | | timeoutMs: 5_000, |
| 1773 | | allowNonZeroExit: true, |
| 1774 | | }, |
| 1775 | | ).pipe(Effect.map((result) => result.code === 0)), |
| 1776 | | ], |
| 1777 | | { concurrency: "unbounded" }, |
| 1778 | | ); |
| 1718 | return { branch: targetBranch }; |
| 1719 | }); |
| 1720 | |
| 1721 | const createBranch: GitCoreShape["createBranch"] = (input) => |
| 1722 | executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { |
| 1723 | timeoutMs: 10_000, |
| 1724 | fallbackErrorMessage: "git branch create failed", |
| 1725 | }).pipe(Effect.asVoid); |
| 1726 | |
| 1727 | const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")( |
| 1728 | function* (input) { |
| 1729 | const [localInputExists, remoteExists] = yield* Effect.all( |
| 1730 | [ |
| 1731 | executeGit( |
| 1732 | "GitCore.checkoutBranch.localInputExists", |
| 1733 | input.cwd, |
| 1734 | ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`], |
| 1735 | { |
| 1736 | timeoutMs: 5_000, |
| 1737 | allowNonZeroExit: true, |
| 1738 | }, |
| 1739 | ).pipe(Effect.map((result) => result.code === 0)), |
| 1740 | executeGit( |
| 1741 | "GitCore.checkoutBranch.remoteExists", |
| 1742 | input.cwd, |
| 1743 | ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`], |
| 1744 | { |
| 1745 | timeoutMs: 5_000, |
| 1746 | allowNonZeroExit: true, |
| 1747 | }, |
| 1748 | ).pipe(Effect.map((result) => result.code === 0)), |
| 1749 | ], |
| 1750 | { concurrency: "unbounded" }, |
| 1751 | ); |
| 1752 | |
| 1753 | const localTrackingBranch = remoteExists |
| 1754 | ? yield* executeGit( |
| 1755 | "GitCore.checkoutBranch.localTrackingBranch", |
| 1756 | input.cwd, |
| 1757 | ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], |
| 1758 | { |
| 1759 | timeoutMs: 5_000, |
| 1760 | allowNonZeroExit: true, |
| 1761 | }, |
| 1762 | ).pipe( |
| 1763 | Effect.map((result) => |
| 1764 | result.code === 0 |
| 1765 | ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) |
| 1766 | : null, |
| 1767 | ), |
| 1768 | ) |
| 1769 | : null; |
| 1779 | 1770 | |
| 1780 | | const localTrackingBranch = remoteExists |
| 1771 | const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch); |
| 1772 | const localTrackedBranchTargetExists = |
| 1773 | remoteExists && localTrackedBranchCandidate |
| 1781 | 1774 | ? yield* executeGit( |
| 1782 | | "GitCore.checkoutBranch.localTrackingBranch", |
| 1775 | "GitCore.checkoutBranch.localTrackedBranchTargetExists", |
| 1783 | 1776 | input.cwd, |
| 1784 | | ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], |
| 1777 | ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`], |
| 1785 | 1778 | { |
| 1786 | 1779 | timeoutMs: 5_000, |
| 1787 | 1780 | allowNonZeroExit: true, |
| 1788 | 1781 | }, |
| 1789 | | ).pipe( |
| 1790 | | Effect.map((result) => |
| 1791 | | result.code === 0 |
| 1792 | | ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) |
| 1793 | | : null, |
| 1794 | | ), |
| 1795 | | ) |
| 1796 | | : null; |
| 1797 | | |
| 1798 | | const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch); |
| 1799 | | const localTrackedBranchTargetExists = |
| 1800 | | remoteExists && localTrackedBranchCandidate |
| 1801 | | ? yield* executeGit( |
| 1802 | | "GitCore.checkoutBranch.localTrackedBranchTargetExists", |
| 1803 | | input.cwd, |
| 1804 | | ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`], |
| 1805 | | { |
| 1806 | | timeoutMs: 5_000, |
| 1807 | | allowNonZeroExit: true, |
| 1808 | | }, |
| 1809 | | ).pipe(Effect.map((result) => result.code === 0)) |
| 1810 | | : false; |
| 1811 | | |
| 1812 | | const checkoutArgs = localInputExists |
| 1782 | ).pipe(Effect.map((result) => result.code === 0)) |
| 1783 | : false; |
| 1784 | |
| 1785 | const checkoutArgs = localInputExists |
| 1786 | ? ["checkout", input.branch] |
| 1787 | : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists |
| 1813 | 1788 | ? ["checkout", input.branch] |
| 1814 | | : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists |
| 1815 | | ? ["checkout", input.branch] |
| 1816 | | : remoteExists && !localTrackingBranch |
| 1817 | | ? ["checkout", "--track", input.branch] |
| 1818 | | : remoteExists && localTrackingBranch |
| 1819 | | ? ["checkout", localTrackingBranch] |
| 1820 | | : ["checkout", input.branch]; |
| 1821 | | |
| 1822 | | yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, { |
| 1823 | | timeoutMs: 10_000, |
| 1824 | | fallbackErrorMessage: "git checkout failed", |
| 1825 | | }); |
| 1789 | : remoteExists && !localTrackingBranch |
| 1790 | ? ["checkout", "--track", input.branch] |
| 1791 | : remoteExists && localTrackingBranch |
| 1792 | ? ["checkout", localTrackingBranch] |
| 1793 | : ["checkout", input.branch]; |
| 1826 | 1794 | |
| 1827 | | // Refresh upstream refs in the background so checkout remains responsive. |
| 1828 | | yield* Effect.forkScoped( |
| 1829 | | refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })), |
| 1830 | | ); |
| 1795 | yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, { |
| 1796 | timeoutMs: 10_000, |
| 1797 | fallbackErrorMessage: "git checkout failed", |
| 1831 | 1798 | }); |
| 1832 | 1799 | |
| 1833 | | const initRepo: GitCoreShape["initRepo"] = (input) => |
| 1834 | | executeGit("GitCore.initRepo", input.cwd, ["init"], { |
| 1835 | | timeoutMs: 10_000, |
| 1836 | | fallbackErrorMessage: "git init failed", |
| 1837 | | }).pipe(Effect.asVoid); |
| 1838 | | |
| 1839 | | const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) => |
| 1840 | | runGitStdout("GitCore.listLocalBranchNames", cwd, [ |
| 1841 | | "branch", |
| 1842 | | "--list", |
| 1843 | | "--format=%(refname:short)", |
| 1844 | | ]).pipe( |
| 1845 | | Effect.map((stdout) => |
| 1846 | | stdout |
| 1847 | | .split("\n") |
| 1848 | | .map((line) => line.trim()) |
| 1849 | | .filter((line) => line.length > 0), |
| 1850 | | ), |
| 1800 | // Refresh upstream refs in the background so checkout remains responsive. |
| 1801 | yield* Effect.forkScoped( |
| 1802 | refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })), |
| 1851 | 1803 | ); |
| 1804 | }, |
| 1805 | ); |
| 1852 | 1806 | |
| 1853 | | return { |
| 1854 | | execute, |
| 1855 | | status, |
| 1856 | | statusDetails, |
| 1857 | | prepareCommitContext, |
| 1858 | | commit, |
| 1859 | | pushCurrentBranch, |
| 1860 | | pullCurrentBranch, |
| 1861 | | readRangeContext, |
| 1862 | | readConfigValue, |
| 1863 | | listBranches, |
| 1864 | | createWorktree, |
| 1865 | | fetchPullRequestBranch, |
| 1866 | | ensureRemote, |
| 1867 | | fetchRemoteBranch, |
| 1868 | | setBranchUpstream, |
| 1869 | | removeWorktree, |
| 1870 | | renameBranch, |
| 1871 | | createBranch, |
| 1872 | | checkoutBranch, |
| 1873 | | initRepo, |
| 1874 | | listLocalBranchNames, |
| 1875 | | } satisfies GitCoreShape; |
| 1876 | | }); |
| 1807 | const initRepo: GitCoreShape["initRepo"] = (input) => |
| 1808 | executeGit("GitCore.initRepo", input.cwd, ["init"], { |
| 1809 | timeoutMs: 10_000, |
| 1810 | fallbackErrorMessage: "git init failed", |
| 1811 | }).pipe(Effect.asVoid); |
| 1812 | |
| 1813 | const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) => |
| 1814 | runGitStdout("GitCore.listLocalBranchNames", cwd, [ |
| 1815 | "branch", |
| 1816 | "--list", |
| 1817 | "--format=%(refname:short)", |
| 1818 | ]).pipe( |
| 1819 | Effect.map((stdout) => |
| 1820 | stdout |
| 1821 | .split("\n") |
| 1822 | .map((line) => line.trim()) |
| 1823 | .filter((line) => line.length > 0), |
| 1824 | ), |
| 1825 | ); |
| 1826 | |
| 1827 | return { |
| 1828 | execute, |
| 1829 | status, |
| 1830 | statusDetails, |
| 1831 | prepareCommitContext, |
| 1832 | commit, |
| 1833 | pushCurrentBranch, |
| 1834 | pullCurrentBranch, |
| 1835 | readRangeContext, |
| 1836 | readConfigValue, |
| 1837 | listBranches, |
| 1838 | createWorktree, |
| 1839 | fetchPullRequestBranch, |
| 1840 | ensureRemote, |
| 1841 | fetchRemoteBranch, |
| 1842 | setBranchUpstream, |
| 1843 | removeWorktree, |
| 1844 | renameBranch, |
| 1845 | createBranch, |
| 1846 | checkoutBranch, |
| 1847 | initRepo, |
| 1848 | listLocalBranchNames, |
| 1849 | } satisfies GitCoreShape; |
| 1850 | }); |
| 1877 | 1851 | |
| 1878 | 1852 | export const GitCoreLive = Layer.effect(GitCore, makeGitCore()); |