Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00f33428b1 | ||
|
|
31fb1008c2 | ||
|
|
738cd85f63 | ||
|
|
ba7fcaa4db | ||
|
|
2002d5b709 | ||
|
|
54a838531f | ||
|
|
7cda30c710 | ||
|
|
3c928636a9 | ||
|
|
f4180a404f | ||
|
|
b133b0dbce | ||
|
|
e36a1556a2 | ||
|
|
598407ddde | ||
|
|
e1626fd742 | ||
|
|
25058ddfe5 | ||
|
|
66640c6c27 | ||
|
|
4b1daeea5b | ||
|
|
083fa715bf | ||
|
|
09696b9930 | ||
|
|
0587d8abda | ||
|
|
68df27e994 | ||
|
|
63521e21e9 | ||
|
|
2cf230668f | ||
|
|
1baf42ca60 | ||
|
|
b3d90d4221 | ||
|
|
d1bbd73e02 | ||
|
|
eb711cc7af | ||
|
|
0d4e8f75a9 | ||
|
|
d66295d2a3 | ||
|
|
03909848ec | ||
|
|
f473d20593 | ||
|
|
b449d78038 | ||
|
|
6406e21cf6 | ||
|
|
d8de522a0d | ||
|
|
c87e67bc04 | ||
|
|
8064641451 | ||
|
|
c3300acd4d | ||
|
|
131870ba8c | ||
|
|
2bf290532f | ||
|
|
2bf08b8656 | ||
|
|
98f873fe0a | ||
|
|
f337848d47 | ||
|
|
69b07777e2 | ||
|
|
3364f1f2af | ||
|
|
0fa4e4c3dd |
No files matched your search
@@ -5,7 +5,6 @@ import { spawnSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { expect } from "vitest";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
@@ -56,16 +55,6 @@ interface FakeGhScenario {
|
||||
failWith?: GitHubCliError;
|
||||
}
|
||||
|
||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
@@ -401,15 +390,24 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
? scenario.prListByHeadSelector?.[headSelector]
|
||||
: undefined;
|
||||
const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
|
||||
return Effect.succeed(fakeGhOutput(stdout));
|
||||
return Effect.succeed({
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "create") {
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
||||
),
|
||||
);
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "view") {
|
||||
@@ -421,8 +419,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
headRefName: "feature/pull-request",
|
||||
state: "open",
|
||||
};
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
JSON.stringify({
|
||||
...pullRequest,
|
||||
...(pullRequest.headRepositoryNameWithOwner
|
||||
@@ -440,8 +438,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
: {}),
|
||||
}) + "\n",
|
||||
),
|
||||
);
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "checkout") {
|
||||
@@ -463,7 +464,13 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
|
||||
}
|
||||
}
|
||||
return fakeGhOutput("");
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
},
|
||||
catch: (error) =>
|
||||
isGitHubCliError(error)
|
||||
@@ -490,17 +497,26 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
JSON.stringify({
|
||||
nameWithOwner: repository,
|
||||
url: cloneUrls.url,
|
||||
sshUrl: cloneUrls.sshUrl,
|
||||
}) + "\n",
|
||||
),
|
||||
);
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
return Effect.succeed(fakeGhOutput(`${scenario.defaultBranch ?? "main"}\n`));
|
||||
return Effect.succeed({
|
||||
stdout: `${scenario.defaultBranch ?? "main"}\n`,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
@@ -644,7 +660,6 @@ function makeManager(input?: {
|
||||
GitHubSourceControlProvider.make().pipe(
|
||||
Effect.map((provider) =>
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
|
||||
get: () => Effect.succeed(provider),
|
||||
resolveHandle: () => Effect.succeed({ provider, context: null }),
|
||||
resolve: () => Effect.succeed(provider),
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Array as Arr,
|
||||
@@ -39,10 +40,6 @@ import {
|
||||
sanitizeBranchFragment,
|
||||
sanitizeFeatureBranchName,
|
||||
} from "@t3tools/shared/git";
|
||||
import {
|
||||
getChangeRequestTerminologyForKind,
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
|
||||
@@ -357,14 +354,13 @@ function withDescription(title: string, description: string | undefined) {
|
||||
|
||||
function summarizeGitActionResult(
|
||||
result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
|
||||
terms: ChangeRequestTerminology,
|
||||
): {
|
||||
title: string;
|
||||
description?: string;
|
||||
} {
|
||||
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
||||
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
|
||||
const title = `${result.pr.status === "created" ? "Created" : "Opened"} ${terms.shortLabel}${prNumber}`;
|
||||
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
|
||||
return withDescription(title, truncateText(result.pr.title));
|
||||
}
|
||||
|
||||
@@ -489,6 +485,14 @@ function normalizePullRequestReference(reference: string): string {
|
||||
return hashNumber?.[1] ?? trimmed;
|
||||
}
|
||||
|
||||
function canonicalizeExistingPath(value: string): string {
|
||||
try {
|
||||
return realpathSync.native(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function toResolvedPullRequest(pr: {
|
||||
number: number;
|
||||
title: string;
|
||||
@@ -676,9 +680,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
const canonicalizeExistingPath = (value: string) =>
|
||||
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(value)));
|
||||
const normalizeStatusCacheKey = canonicalizeExistingPath;
|
||||
const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
|
||||
const nonRepositoryStatusDetails = {
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
@@ -717,9 +719,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateLocalStatusResultCache = (cwd: string) =>
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
|
||||
);
|
||||
Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
.statusDetails(cwd)
|
||||
@@ -757,9 +757,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateRemoteStatusResultCache = (cwd: string) =>
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),
|
||||
);
|
||||
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||
|
||||
const readConfigValueNullable = (cwd: string, key: string) =>
|
||||
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
@@ -944,11 +942,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
cwd: string,
|
||||
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
||||
) {
|
||||
const terms = yield* sourceControlProvider(cwd).pipe(
|
||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
||||
);
|
||||
const summary = summarizeGitActionResult(result, terms);
|
||||
const summary = summarizeGitActionResult(result);
|
||||
let latestOpenPr: PullRequestInfo | null = null;
|
||||
let currentBranchIsDefault = false;
|
||||
let finalBranchContext: {
|
||||
@@ -1013,7 +1007,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
result.pr.status === "opened_existing")
|
||||
? {
|
||||
kind: "open_pr" as const,
|
||||
label: `View ${terms.shortLabel}`,
|
||||
label: "View PR",
|
||||
url: openPr.url,
|
||||
}
|
||||
: (result.action === "push" || result.action === "commit_push") &&
|
||||
@@ -1021,7 +1015,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
!currentBranchIsDefault
|
||||
? {
|
||||
kind: "run_action" as const,
|
||||
label: `Create ${terms.shortLabel}`,
|
||||
label: "Create PR",
|
||||
action: { kind: "create_pr" as const },
|
||||
}
|
||||
: {
|
||||
@@ -1229,8 +1223,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
fallbackBranch: string | null,
|
||||
emit: GitActionProgressEmitter,
|
||||
) {
|
||||
const provider = yield* sourceControlProvider(cwd);
|
||||
const terms = getChangeRequestTerminologyForKind(provider.kind);
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
@@ -1267,7 +1259,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: `Generating ${terms.shortLabel} content...`,
|
||||
label: "Generating PR content...",
|
||||
});
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
|
||||
|
||||
@@ -1292,9 +1284,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: `Creating ${terms.singular}...`,
|
||||
label: "Creating pull request...",
|
||||
});
|
||||
yield* provider
|
||||
yield* (yield* sourceControlProvider(cwd))
|
||||
.createChangeRequest({
|
||||
cwd,
|
||||
baseRefName: baseBranch,
|
||||
@@ -1325,13 +1317,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
});
|
||||
|
||||
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(localStatusResultCache, cacheKey);
|
||||
return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||
});
|
||||
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
|
||||
function* (input) {
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(remoteStatusResultCache, cacheKey);
|
||||
return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||
},
|
||||
);
|
||||
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
|
||||
@@ -1391,7 +1381,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
};
|
||||
return yield* Effect.gen(function* () {
|
||||
const normalizedReference = normalizePullRequestReference(input.reference);
|
||||
const rootWorktreePath = yield* canonicalizeExistingPath(input.cwd);
|
||||
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
|
||||
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizedReference,
|
||||
@@ -1441,35 +1431,33 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const localPullRequestBranch =
|
||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||
|
||||
const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
|
||||
const result = yield* gitCore.listRefs({ cwd });
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
const findLocalHeadBranch = (cwd: string) =>
|
||||
gitCore.listRefs({ cwd }).pipe(
|
||||
Effect.map((result) => {
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
);
|
||||
if (localBranch) {
|
||||
return localBranch;
|
||||
}
|
||||
if (localPullRequestBranch === pullRequest.headBranch) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
result.refs.find(
|
||||
(branch) =>
|
||||
!branch.isRemote &&
|
||||
branch.name === pullRequest.headBranch &&
|
||||
branch.worktreePath !== null &&
|
||||
canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath,
|
||||
) ?? null
|
||||
);
|
||||
}),
|
||||
);
|
||||
if (localBranch) {
|
||||
return localBranch;
|
||||
}
|
||||
if (localPullRequestBranch === pullRequest.headBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const branch of result.refs) {
|
||||
if (branch.isRemote || branch.name !== pullRequest.headBranch || !branch.worktreePath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const worktreePath = yield* canonicalizeExistingPath(branch.worktreePath);
|
||||
if (worktreePath !== rootWorktreePath) {
|
||||
return branch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
|
||||
const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
|
||||
? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
||||
? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
||||
: null;
|
||||
if (
|
||||
existingBranchBeforeFetch?.worktreePath &&
|
||||
@@ -1497,7 +1485,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
|
||||
const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
|
||||
? yield* canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
||||
? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
||||
: null;
|
||||
if (
|
||||
existingBranchAfterFetch?.worktreePath &&
|
||||
@@ -1663,12 +1651,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
const commitAction = isCommitAction(input.action) ? input.action : null;
|
||||
const changeRequestTerms = wantsPr
|
||||
? yield* sourceControlProvider(input.cwd).pipe(
|
||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
||||
)
|
||||
: null;
|
||||
|
||||
const commit = commitAction
|
||||
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
||||
@@ -1706,7 +1688,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
.emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: `Preparing ${changeRequestTerms?.shortLabel ?? "PR"}...`,
|
||||
label: "Preparing PR...",
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { describe, vi } from "vitest";
|
||||
|
||||
import { GitManager } from "./GitManager.ts";
|
||||
import { GitWorkflowService, layer as GitWorkflowServiceLayer } from "./GitWorkflowService.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { VcsDriverRegistry, type VcsDriverRegistryShape } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
function makeLayer(input: { readonly detect: VcsDriverRegistryShape["detect"] }) {
|
||||
return GitWorkflowServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
detect: input.detect,
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver)({})),
|
||||
Layer.provide(Layer.mock(GitManager)({})),
|
||||
);
|
||||
}
|
||||
|
||||
describe("GitWorkflowService", () => {
|
||||
it.effect("returns an empty local status when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const status = yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(status, {
|
||||
kind: "unknown",
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an empty full status when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const status = yield* workflow.status({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(status, {
|
||||
kind: "unknown",
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not call GitManager status methods when no VCS repository is detected", () => {
|
||||
const localStatus = vi.fn();
|
||||
const remoteStatus = vi.fn();
|
||||
const status = vi.fn();
|
||||
|
||||
const testLayer = GitWorkflowServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver)({})),
|
||||
Layer.provide(
|
||||
Layer.mock(GitManager)({
|
||||
localStatus,
|
||||
remoteStatus,
|
||||
status,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
||||
yield* workflow.remoteStatus({ cwd: "/not-a-repo" });
|
||||
yield* workflow.status({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.equal(localStatus.mock.calls.length, 0);
|
||||
assert.equal(remoteStatus.mock.calls.length, 0);
|
||||
assert.equal(status.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("returns an empty ref list when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const refs = yield* workflow.listRefs({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(refs, {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -67,6 +67,7 @@ export interface GitWorkflowServiceShape {
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly initRepo: (input: { readonly cwd: string }) => Effect.Effect<void, GitCommandError>;
|
||||
readonly renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
@@ -95,16 +96,6 @@ const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =
|
||||
|
||||
const emptyWorkingTree = { files: [], insertions: 0, deletions: 0 } as const;
|
||||
|
||||
function nonRepositoryListRefs(): VcsListRefsResult {
|
||||
return {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const nonGitLocalStatus = (kind: VcsDriverKind, isRepo: boolean): VcsStatusLocalResult => ({
|
||||
kind,
|
||||
isRepo,
|
||||
@@ -168,33 +159,6 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const detectGitRepositoryForCommand = Effect.fn(
|
||||
"GitWorkflowService.detectGitRepositoryForCommand",
|
||||
)(function* (operation: string, cwd: string) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return false;
|
||||
}
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const routeGitManager =
|
||||
<Input extends { readonly cwd: string }, Output>(
|
||||
operation: string,
|
||||
@@ -277,10 +241,8 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
gitManager.preparePullRequestThread,
|
||||
),
|
||||
listRefs: (input) =>
|
||||
detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
|
||||
),
|
||||
ensureGitCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.andThen(git.listRefs(input)),
|
||||
),
|
||||
createWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
@@ -298,6 +260,7 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
|
||||
Effect.andThen(Effect.scoped(git.switchRef(input))),
|
||||
),
|
||||
initRepo: (input) => git.initRepo(input),
|
||||
renameBranch: (input) =>
|
||||
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
|
||||
Effect.andThen(git.renameBranch(input)),
|
||||
|
||||
@@ -126,7 +126,6 @@ import {
|
||||
type VcsDriverRegistryShape,
|
||||
type VcsDriverHandle,
|
||||
} from "./vcs/VcsDriverRegistry.ts";
|
||||
import { layer as VcsProvisioningServiceLayer } from "./vcs/VcsProvisioningService.ts";
|
||||
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
@@ -426,11 +425,9 @@ const buildAppUnderTest = (options?: {
|
||||
},
|
||||
}),
|
||||
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
|
||||
initRepository: () => Effect.void,
|
||||
...options?.layers?.vcsDriver,
|
||||
};
|
||||
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry)({
|
||||
get: () => Effect.succeed(defaultVcsDriver),
|
||||
detect: (input) =>
|
||||
defaultVcsDriver.detectRepository(input.cwd).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
@@ -506,9 +503,6 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provideMerge(gitManagerLayer),
|
||||
);
|
||||
const vcsProvisioningLayer = VcsProvisioningServiceLayer.pipe(
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster)({
|
||||
...options.layers.vcsStatusBroadcaster,
|
||||
@@ -555,7 +549,6 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectSetupScriptRunner)({
|
||||
@@ -2386,7 +2379,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
},
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
@@ -2525,6 +2517,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
removeWorktree: () => Effect.void,
|
||||
createRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
switchRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
initRepo: () => Effect.void,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2861,7 +2854,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
|
||||
},
|
||||
gitManager: {
|
||||
@@ -2939,7 +2931,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
|
||||
},
|
||||
gitManager: {
|
||||
|
||||
@@ -49,7 +49,6 @@ import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
@@ -185,7 +184,6 @@ const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(VcsProjectConfig.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
);
|
||||
|
||||
@@ -1,64 +1,53 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError, type VcsError } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, vi } from "vitest";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
|
||||
import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
vi.mock("../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
|
||||
const processOutput = (stdout: string): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
const mockRun = vi.fn<(input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>>();
|
||||
|
||||
const layer = GitHubCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: mockRun,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const mockedRunProcess = vi.mocked(runProcess);
|
||||
const layer = it.layer(GitHubCli.layer);
|
||||
|
||||
afterEach(() => {
|
||||
mockRun.mockReset();
|
||||
mockedRunProcess.mockReset();
|
||||
});
|
||||
|
||||
describe("GitHubCli.layer", () => {
|
||||
layer("GitHubCli.layer", (it) => {
|
||||
it.effect("parses pull request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: "octocat",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: "octocat",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -72,51 +61,51 @@ describe("GitHubCli.layer", () => {
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
expect(mockRun).toHaveBeenCalledWith({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: [
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"gh",
|
||||
[
|
||||
"pr",
|
||||
"view",
|
||||
"#42",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
expect.objectContaining({ cwd: "/repo" }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -130,44 +119,46 @@ describe("GitHubCli.layer", () => {
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
@@ -180,27 +171,29 @@ describe("GitHubCli.layer", () => {
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -208,33 +201,26 @@ describe("GitHubCli.layer", () => {
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the pull request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh pr view",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail:
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
}),
|
||||
mockedRunProcess.mockRejectedValueOnce(
|
||||
new Error(
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
),
|
||||
);
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const error = yield* gh
|
||||
.getPullRequest({
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "4888",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Pull request not found"), true);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
|
||||
import { GitHubCliError, TrimmedNonEmptyString, type VcsError } from "@t3tools/contracts";
|
||||
import { GitHubCliError, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import type { ProcessRunResult } from "../processRunner.ts";
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
@@ -34,7 +35,7 @@ export interface GitHubCliShape {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<VcsProcessOutput, GitHubCliError>;
|
||||
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
|
||||
|
||||
readonly listOpenPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
@@ -75,61 +76,53 @@ export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/source-control/GitHubCli",
|
||||
) {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: gh")) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeGitHubCliError(
|
||||
operation: "execute" | "stdout",
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const text = errorText(error);
|
||||
const lower = text.toLowerCase();
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
detail: `GitHub CLI command failed: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: text,
|
||||
detail: "GitHub CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -168,19 +161,16 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
|
||||
export const make = Effect.sync(() => {
|
||||
const execute: GitHubCliShape["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitHubCliError("execute", error)));
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("gh", input.args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
});
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
@@ -305,4 +295,4 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitHubCli, make());
|
||||
export const layer = Layer.effect(GitHubCli, make);
|
||||
@@ -1,17 +1,15 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitHubCli, type GitHubCliShape } from "./GitHubCli.ts";
|
||||
import type { VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
|
||||
const processResult = (stdout: string): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
const processResult = (stdout: string) => ({
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
function makeProvider(github: Partial<GitHubCliShape>) {
|
||||
|
||||
@@ -31,7 +31,6 @@ function makeRegistry(input: {
|
||||
} satisfies Partial<VcsDriverShape>;
|
||||
|
||||
const registryLayer = Layer.mock(VcsDriverRegistry)({
|
||||
get: () => Effect.succeed(driver as unknown as VcsDriverShape),
|
||||
resolve: () =>
|
||||
Effect.succeed({
|
||||
kind: "git",
|
||||
@@ -66,18 +65,6 @@ it.effect("routes GitHub remotes to the GitHub provider", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes directly by provider kind for remote-first workflows", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [],
|
||||
});
|
||||
|
||||
const provider = yield* registry.get("github");
|
||||
|
||||
assert.strictEqual(provider.kind, "github");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"detects GitLab remotes and returns an unsupported provider until one is registered",
|
||||
() =>
|
||||
|
||||
@@ -25,9 +25,6 @@ export interface SourceControlProviderHandle {
|
||||
}
|
||||
|
||||
export interface SourceControlProviderRegistryShape {
|
||||
readonly get: (
|
||||
kind: SourceControlProviderKind,
|
||||
) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
|
||||
readonly resolveHandle: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
|
||||
@@ -105,9 +102,6 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
registrations.map((registration) => [registration.kind, registration.provider]),
|
||||
);
|
||||
|
||||
const get: SourceControlProviderRegistryShape["get"] = (kind) =>
|
||||
Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
|
||||
|
||||
const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
|
||||
function* (cwd: string) {
|
||||
const handle = yield* vcsRegistry
|
||||
@@ -142,7 +136,6 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
);
|
||||
|
||||
return SourceControlProviderRegistry.of({
|
||||
get,
|
||||
resolveHandle,
|
||||
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
|
||||
});
|
||||
|
||||
@@ -503,12 +503,6 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const initRepository: VcsDriverShape["initRepository"] = (input) =>
|
||||
gitCommand(process, "GitVcsDriver.initRepository", input.cwd, ["init"], {
|
||||
timeoutMs: 10_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
return {
|
||||
capabilities,
|
||||
execute,
|
||||
@@ -517,7 +511,6 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
listWorkspaceFiles,
|
||||
listRemotes,
|
||||
filterIgnoredPaths,
|
||||
initRepository,
|
||||
} satisfies VcsDriverShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -269,9 +269,6 @@ export const makeVcsDriverShape = Effect.fn("makeJjVcsDriverShape")(function* ()
|
||||
: {}),
|
||||
});
|
||||
|
||||
const initRepository: VcsDriverShape["initRepository"] = (input) =>
|
||||
jjCommand(process, "JjVcsDriver.initRepository", input.cwd, ["git", "init"]);
|
||||
|
||||
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
|
||||
function* (cwd) {
|
||||
const root = yield* jjCommand(process, "JjVcsDriver.detectRepository.root", cwd, ["root"], {
|
||||
@@ -491,7 +488,6 @@ export const makeVcsDriverShape = Effect.fn("makeJjVcsDriverShape")(function* ()
|
||||
return {
|
||||
capabilities,
|
||||
execute,
|
||||
initRepository,
|
||||
detectRepository,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Context, type Effect } from "effect";
|
||||
import type {
|
||||
VcsDriverCapabilities,
|
||||
VcsError,
|
||||
VcsInitInput,
|
||||
VcsListRemotesResult,
|
||||
VcsListWorkspaceFilesResult,
|
||||
VcsRepositoryIdentity,
|
||||
@@ -25,7 +24,6 @@ export interface VcsDriverShape {
|
||||
cwd: string,
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, VcsError>;
|
||||
readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsDriver extends Context.Service<VcsDriver, VcsDriverShape>()("t3/vcs/VcsDriver") {}
|
||||
@@ -20,29 +20,6 @@ const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOut
|
||||
});
|
||||
|
||||
describe("VcsDriverRegistry", () => {
|
||||
it.effect("routes directly by VCS driver kind for non-repository workflows", () => {
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: () => Effect.succeed(processOutput("")),
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const driver = yield* registry.get("git");
|
||||
|
||||
assert.strictEqual(driver.capabilities.kind, "git");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
|
||||
@@ -22,7 +22,6 @@ export interface VcsDriverHandle {
|
||||
}
|
||||
|
||||
export interface VcsDriverRegistryShape {
|
||||
readonly get: (kind: VcsDriverKind) => Effect.Effect<VcsDriverShape, VcsError>;
|
||||
readonly detect: (
|
||||
input: VcsDriverResolveInput,
|
||||
) => Effect.Effect<VcsDriverHandle | null, VcsError>;
|
||||
@@ -73,16 +72,6 @@ export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
|
||||
jj,
|
||||
};
|
||||
|
||||
const get: VcsDriverRegistryShape["get"] = (kind) => {
|
||||
const driver = drivers[kind];
|
||||
if (!driver) {
|
||||
return Effect.fail(
|
||||
unsupported("VcsDriverRegistry.get", kind, `No ${kind} VCS driver is registered.`),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(driver);
|
||||
};
|
||||
|
||||
const detectWithDriver = Effect.fn("VcsDriverRegistry.detectWithDriver")(function* (
|
||||
kind: VcsDriverKind,
|
||||
driver: VcsDriverShape,
|
||||
@@ -106,7 +95,14 @@ export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
|
||||
const requestedKind = input.requestedKind;
|
||||
|
||||
if (requestedKind !== "auto" && requestedKind !== "unknown") {
|
||||
const driver = yield* get(requestedKind);
|
||||
const driver = drivers[requestedKind];
|
||||
if (!driver) {
|
||||
return yield* unsupported(
|
||||
"VcsDriverRegistry.detect",
|
||||
requestedKind,
|
||||
`No ${requestedKind} VCS driver is registered.`,
|
||||
);
|
||||
}
|
||||
return yield* detectWithDriver(requestedKind, driver, input.cwd);
|
||||
}
|
||||
|
||||
@@ -152,7 +148,6 @@ export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
|
||||
);
|
||||
|
||||
return VcsDriverRegistry.of({
|
||||
get,
|
||||
detect,
|
||||
resolve,
|
||||
});
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import type { VcsDriverShape } from "./VcsDriver.ts";
|
||||
import { VcsDriverRegistry } from "./VcsDriverRegistry.ts";
|
||||
import { VcsProvisioningService, layer } from "./VcsProvisioningService.ts";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
function makeDriver(calls: string[]): VcsDriverShape {
|
||||
return {
|
||||
capabilities: {
|
||||
kind: "git",
|
||||
supportsWorktrees: true,
|
||||
supportsBookmarks: false,
|
||||
supportsAtomicSnapshot: false,
|
||||
supportsPushDefaultRemote: true,
|
||||
ignoreClassifier: "native",
|
||||
},
|
||||
execute: () =>
|
||||
Effect.succeed({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
detectRepository: () => Effect.succeed(null),
|
||||
isInsideWorkTree: () => Effect.succeed(false),
|
||||
listWorkspaceFiles: () =>
|
||||
Effect.succeed({
|
||||
paths: [],
|
||||
truncated: false,
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
listRemotes: () =>
|
||||
Effect.succeed({
|
||||
remotes: [],
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
|
||||
initRepository: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(`${input.kind ?? "default"}:${input.cwd}`);
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
it.effect("routes repository initialization through an explicit VCS driver kind", () => {
|
||||
const calls: string[] = [];
|
||||
const driver = makeDriver(calls);
|
||||
const testLayer = layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const provisioning = yield* VcsProvisioningService;
|
||||
yield* provisioning.initRepository({ cwd: "/repo", kind: "git" });
|
||||
|
||||
assert.deepStrictEqual(calls, ["git:/repo"]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("defaults repository initialization to Git until callers choose a VCS kind", () => {
|
||||
const calls: string[] = [];
|
||||
const driver = makeDriver(calls);
|
||||
const testLayer = layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const provisioning = yield* VcsProvisioningService;
|
||||
yield* provisioning.initRepository({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(calls, ["default:/repo"]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
|
||||
import {
|
||||
type VcsDriverKind,
|
||||
type VcsError,
|
||||
type VcsInitInput,
|
||||
VcsUnsupportedOperationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { VcsDriverRegistry } from "./VcsDriverRegistry.ts";
|
||||
|
||||
export interface VcsProvisioningServiceShape {
|
||||
readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsProvisioningService extends Context.Service<
|
||||
VcsProvisioningService,
|
||||
VcsProvisioningServiceShape
|
||||
>()("t3/vcs/VcsProvisioningService") {}
|
||||
|
||||
function resolveRequestedKind(
|
||||
kind: VcsDriverKind | undefined,
|
||||
): Effect.Effect<VcsDriverKind, VcsUnsupportedOperationError> {
|
||||
if (kind === undefined) {
|
||||
return Effect.succeed("git");
|
||||
}
|
||||
if (kind === "unknown") {
|
||||
return Effect.fail(
|
||||
new VcsUnsupportedOperationError({
|
||||
operation: "VcsProvisioningService.resolveRequestedKind",
|
||||
kind,
|
||||
detail: "A concrete VCS driver kind is required for repository provisioning.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(kind);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeVcsProvisioningService")(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
|
||||
const initRepository: VcsProvisioningServiceShape["initRepository"] = Effect.fn(
|
||||
"VcsProvisioningService.initRepository",
|
||||
)(function* (input) {
|
||||
const kind = yield* resolveRequestedKind(input.kind);
|
||||
const driver = yield* registry.get(kind);
|
||||
return yield* driver.initRepository(input);
|
||||
});
|
||||
|
||||
return VcsProvisioningService.of({
|
||||
initRepository,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(VcsProvisioningService, make());
|
||||
@@ -201,19 +201,13 @@ export const layer = Layer.effect(
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
|
||||
const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
|
||||
function* (cwd: string) {
|
||||
yield* workflow.invalidateLocalStatus(cwd);
|
||||
const local = yield* workflow.localStatus({ cwd });
|
||||
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
|
||||
},
|
||||
);
|
||||
|
||||
const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshLocalStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* normalizeCwd(rawCwd);
|
||||
return yield* refreshLocalStatusCore(cwd);
|
||||
yield* workflow.invalidateLocalStatus(cwd);
|
||||
const local = yield* workflow.localStatus({ cwd });
|
||||
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
|
||||
});
|
||||
|
||||
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
|
||||
@@ -229,7 +223,7 @@ export const layer = Layer.effect(
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* normalizeCwd(rawCwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
refreshLocalStatusCore(cwd),
|
||||
refreshLocalStatus(cwd),
|
||||
refreshRemoteStatus(cwd),
|
||||
]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
|
||||
@@ -48,7 +48,6 @@ import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts";
|
||||
import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import { VcsProvisioningService } from "./vcs/VcsProvisioningService.ts";
|
||||
import { GitWorkflowService } from "./git/GitWorkflowService.ts";
|
||||
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
@@ -139,7 +138,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const keybindings = yield* Keybindings;
|
||||
const open = yield* Open;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsProvisioning = yield* VcsProvisioningService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
@@ -940,9 +938,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
[WS_METHODS.vcsInit]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsInit,
|
||||
vcsProvisioning
|
||||
.initRepository(input)
|
||||
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
gitWorkflow.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
|
||||
@@ -21,7 +21,6 @@ import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import { cn } from "../lib/utils";
|
||||
import { parsePullRequestReference } from "../pullRequestReference";
|
||||
import { getSourceControlPresentation } from "../sourceControlPresentation";
|
||||
import { useStore } from "../store";
|
||||
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { resolveVcsTerms } from "../vcsPresentation";
|
||||
@@ -234,11 +233,6 @@ export function BranchToolbarBranchSelector({
|
||||
);
|
||||
const currentGitBranch =
|
||||
branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
|
||||
const sourceControlPresentation = useMemo(
|
||||
() => getSourceControlPresentation(branchStatusQuery.data?.sourceControlProvider),
|
||||
[branchStatusQuery.data?.sourceControlProvider],
|
||||
);
|
||||
const SourceControlIcon = sourceControlPresentation.Icon;
|
||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||
envMode: effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
@@ -518,14 +512,9 @@ export function BranchToolbarBranchSelector({
|
||||
onCheckoutPullRequestRequest(prReference);
|
||||
}}
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2 py-1">
|
||||
<SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="flex min-w-0 flex-col items-start">
|
||||
<span className="truncate font-medium">
|
||||
Checkout {sourceControlPresentation.terminology.singular}
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground text-xs">{prReference}</span>
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-col items-start py-1">
|
||||
<span className="truncate font-medium">Checkout Pull Request</span>
|
||||
<span className="truncate text-muted-foreground text-xs">{prReference}</span>
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
|
||||
@@ -2297,7 +2297,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const checkoutItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("span")).find(
|
||||
(element) => element.textContent?.trim() === "Checkout pull request",
|
||||
(element) => element.textContent?.trim() === "Checkout Pull Request",
|
||||
) as HTMLSpanElement | null,
|
||||
"Unable to find checkout pull request option.",
|
||||
);
|
||||
|
||||
@@ -254,32 +254,6 @@ describe("when: ref is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: source control provider uses merge requests", () => {
|
||||
it("uses GitLab MR terminology in quick actions and menu items", () => {
|
||||
const gitlabStatus = status({
|
||||
aheadCount: 2,
|
||||
sourceControlProvider: {
|
||||
kind: "gitlab",
|
||||
name: "GitLab",
|
||||
baseUrl: "https://gitlab.com",
|
||||
},
|
||||
});
|
||||
|
||||
const quick = resolveQuickAction(gitlabStatus, false);
|
||||
const items = buildMenuItems(gitlabStatus, false);
|
||||
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
label: "Push & create MR",
|
||||
});
|
||||
assert.deepInclude(items[2], {
|
||||
id: "pr",
|
||||
label: "Create MR",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is clean, up to date, and has no open PR", () => {
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
@@ -683,7 +657,7 @@ describe("when: ref has no upstream configured", () => {
|
||||
assert.deepEqual(quick, {
|
||||
kind: "show_hint",
|
||||
label: "Push",
|
||||
hint: 'Add an "origin" remote before pushing or creating a pull request.',
|
||||
hint: 'Add an "origin" remote before pushing or creating a PR.',
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
@@ -867,7 +841,7 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push & create PR from default ref?",
|
||||
description:
|
||||
'This action will push local commits and create a pull request on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
'This action will push local commits and create a PR on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
continueLabel: "Push & create PR",
|
||||
});
|
||||
});
|
||||
@@ -882,7 +856,7 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
assert.deepEqual(copy, {
|
||||
title: "Commit, push & create PR from default ref?",
|
||||
description:
|
||||
'This action will commit, push, and create a pull request on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
'This action will commit, push, and create a PR on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
continueLabel: "Commit, push & create PR",
|
||||
});
|
||||
});
|
||||
@@ -911,7 +885,7 @@ describe("buildGitActionProgressStages", () => {
|
||||
"Pushing to origin/feature/test...",
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating pull request...",
|
||||
"Creating GitHub pull request...",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -925,7 +899,7 @@ describe("buildGitActionProgressStages", () => {
|
||||
assert.deepEqual(stages, [
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating pull request...",
|
||||
"Creating GitHub pull request...",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -955,7 +929,7 @@ describe("buildGitActionProgressStages", () => {
|
||||
"Pushing to origin/feature/test...",
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating pull request...",
|
||||
"Creating GitHub pull request...",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,11 +4,6 @@ import type {
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
import {
|
||||
DEFAULT_CHANGE_REQUEST_TERMINOLOGY,
|
||||
getChangeRequestTerminology,
|
||||
type ChangeRequestTerminology,
|
||||
} from "../sourceControlPresentation";
|
||||
|
||||
export type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
@@ -43,14 +38,6 @@ export type DefaultBranchConfirmableAction =
|
||||
| "commit_push"
|
||||
| "commit_push_pr";
|
||||
|
||||
function resolveChangeRequestTerminology(
|
||||
gitStatus: VcsStatusResult | null,
|
||||
): ChangeRequestTerminology {
|
||||
return gitStatus?.sourceControlProvider
|
||||
? getChangeRequestTerminology(gitStatus.sourceControlProvider)
|
||||
: DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
}
|
||||
|
||||
export function buildGitActionProgressStages(input: {
|
||||
action: GitStackedAction;
|
||||
hasCustomCommitMessage: boolean;
|
||||
@@ -58,15 +45,13 @@ export function buildGitActionProgressStages(input: {
|
||||
pushTarget?: string;
|
||||
featureBranch?: boolean;
|
||||
shouldPushBeforePr?: boolean;
|
||||
terminology?: ChangeRequestTerminology;
|
||||
}): string[] {
|
||||
const terminology = input.terminology ?? DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
const branchStages = input.featureBranch ? ["Preparing feature ref..."] : [];
|
||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||
const prStages = [
|
||||
`Preparing ${terminology.shortLabel}...`,
|
||||
`Generating ${terminology.shortLabel} content...`,
|
||||
`Creating ${terminology.singular}...`,
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating GitHub pull request...",
|
||||
];
|
||||
|
||||
if (input.action === "push") {
|
||||
@@ -97,7 +82,6 @@ export function buildMenuItems(
|
||||
hasPrimaryRemote = true,
|
||||
): GitActionMenuItem[] {
|
||||
if (!gitStatus) return [];
|
||||
const terminology = resolveChangeRequestTerminology(gitStatus);
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
@@ -142,14 +126,14 @@ export function buildMenuItems(
|
||||
hasOpenPr
|
||||
? {
|
||||
id: "pr",
|
||||
label: `View ${terminology.shortLabel}`,
|
||||
label: "View PR",
|
||||
disabled: !canOpenPr,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
}
|
||||
: {
|
||||
id: "pr",
|
||||
label: `Create ${terminology.shortLabel}`,
|
||||
label: "Create PR",
|
||||
disabled: !canCreatePr,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
@@ -183,14 +167,13 @@ export function resolveQuickAction(
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
const terminology = resolveChangeRequestTerminology(gitStatus);
|
||||
|
||||
if (!hasBranch) {
|
||||
return {
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: `Create and checkout a ref before pushing or opening a ${terminology.singular}.`,
|
||||
hint: "Create and checkout a ref before pushing or opening a PR.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -202,7 +185,7 @@ export function resolveQuickAction(
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
label: `Commit, push & ${terminology.shortLabel}`,
|
||||
label: "Commit, push & PR",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
@@ -212,18 +195,18 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!hasPrimaryRemote) {
|
||||
if (hasOpenPr && !isAhead) {
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: `Add an "origin" remote before pushing or creating a ${terminology.singular}.`,
|
||||
hint: 'Add an "origin" remote before pushing or creating a PR.',
|
||||
};
|
||||
}
|
||||
if (!isAhead) {
|
||||
if (hasOpenPr) {
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
@@ -241,7 +224,7 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: `Push & create ${terminology.shortLabel}`,
|
||||
label: "Push & create PR",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
@@ -275,7 +258,7 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: `Push & create ${terminology.shortLabel}`,
|
||||
label: "Push & create PR",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
@@ -283,7 +266,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (hasOpenPr && gitStatus.hasUpstream) {
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -311,11 +294,9 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
action: DefaultBranchConfirmableAction;
|
||||
branchName: string;
|
||||
includesCommit: boolean;
|
||||
terminology?: ChangeRequestTerminology;
|
||||
}): DefaultBranchActionDialogCopy {
|
||||
const branchLabel = input.branchName;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this ref or create a feature ref and run the same action there.`;
|
||||
const terminology = input.terminology ?? DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
|
||||
if (input.action === "push" || input.action === "commit_push") {
|
||||
if (input.includesCommit) {
|
||||
@@ -334,15 +315,15 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: `Commit, push & create ${terminology.shortLabel} from default ref?`,
|
||||
description: `This action will commit, push, and create a ${terminology.singular}${suffix}`,
|
||||
continueLabel: `Commit, push & create ${terminology.shortLabel}`,
|
||||
title: "Commit, push & create PR from default ref?",
|
||||
description: `This action will commit, push, and create a PR${suffix}`,
|
||||
continueLabel: `Commit, push & create PR`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: `Push & create ${terminology.shortLabel} from default ref?`,
|
||||
description: `This action will push local commits and create a ${terminology.singular}${suffix}`,
|
||||
continueLabel: `Push & create ${terminology.shortLabel}`,
|
||||
title: "Push & create PR from default ref?",
|
||||
description: `This action will push local commits and create a PR${suffix}`,
|
||||
continueLabel: "Push & create PR",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
import {
|
||||
buildGitActionProgressStages,
|
||||
buildMenuItems,
|
||||
@@ -51,7 +52,6 @@ import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { readEnvironmentApi } from "~/environmentApi";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { getSourceControlPresentation } from "~/sourceControlPresentation";
|
||||
import { useStore } from "~/store";
|
||||
import { createThreadSelectorByRef } from "~/storeSelectors";
|
||||
import { resolveVcsActionPresentation, resolveVcsTerms } from "~/vcsPresentation";
|
||||
@@ -138,7 +138,6 @@ function getMenuActionDisabledReason({
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const terminology = getSourceControlPresentation(gitStatus.sourceControlProvider).terminology;
|
||||
|
||||
if (item.id === "commit") {
|
||||
if (!hasChanges) {
|
||||
@@ -167,58 +166,46 @@ function getMenuActionDisabledReason({
|
||||
}
|
||||
|
||||
if (hasOpenPr) {
|
||||
return `View ${terminology.singular} is currently unavailable.`;
|
||||
return "View PR is currently unavailable.";
|
||||
}
|
||||
if (!hasBranch) {
|
||||
return `Detached HEAD: checkout a refName before creating a ${terminology.singular}.`;
|
||||
return "Detached HEAD: checkout a refName before creating a PR.";
|
||||
}
|
||||
if (hasChanges) {
|
||||
return `Commit local changes before creating a ${terminology.singular}.`;
|
||||
return "Commit local changes before creating a PR.";
|
||||
}
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
return `Add an "origin" remote before creating a ${terminology.singular}.`;
|
||||
return 'Add an "origin" remote before creating a PR.';
|
||||
}
|
||||
if (!isAhead) {
|
||||
return `No local commits to include in a ${terminology.singular}.`;
|
||||
return "No local commits to include in a PR.";
|
||||
}
|
||||
if (isBehind) {
|
||||
return `Branch is behind upstream. Pull/rebase before creating a ${terminology.singular}.`;
|
||||
return "Branch is behind upstream. Pull/rebase before creating a PR.";
|
||||
}
|
||||
return `Create ${terminology.singular} is currently unavailable.`;
|
||||
return "Create PR is currently unavailable.";
|
||||
}
|
||||
|
||||
const COMMIT_DIALOG_TITLE = "Commit changes";
|
||||
const COMMIT_DIALOG_DESCRIPTION =
|
||||
"Review and confirm your commit. Leave the message blank to auto-generate one.";
|
||||
|
||||
function GitActionItemIcon({
|
||||
icon,
|
||||
SourceControlIcon,
|
||||
}: {
|
||||
icon: GitActionIconName;
|
||||
SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
|
||||
}) {
|
||||
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
|
||||
if (icon === "commit") return <GitCommitIcon />;
|
||||
if (icon === "push") return <CloudUploadIcon />;
|
||||
return <SourceControlIcon />;
|
||||
return <GitHubIcon />;
|
||||
}
|
||||
|
||||
function GitQuickActionIcon({
|
||||
quickAction,
|
||||
SourceControlIcon,
|
||||
}: {
|
||||
quickAction: GitQuickAction;
|
||||
SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
|
||||
}) {
|
||||
function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
const iconClassName = "size-3.5";
|
||||
if (quickAction.kind === "open_pr") return <SourceControlIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "open_pr") return <GitHubIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_action") {
|
||||
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
|
||||
if (quickAction.action === "push" || quickAction.action === "commit_push") {
|
||||
return <CloudUploadIcon className={iconClassName} />;
|
||||
}
|
||||
return <SourceControlIcon className={iconClassName} />;
|
||||
return <GitHubIcon className={iconClassName} />;
|
||||
}
|
||||
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
|
||||
return <InfoIcon className={iconClassName} />;
|
||||
@@ -336,12 +323,6 @@ export default function GitActionsControl({
|
||||
environmentId: activeEnvironmentId,
|
||||
cwd: gitCwd,
|
||||
});
|
||||
const sourceControlPresentation = useMemo(
|
||||
() => getSourceControlPresentation(gitStatus?.sourceControlProvider),
|
||||
[gitStatus?.sourceControlProvider],
|
||||
);
|
||||
const changeRequestTerminology = sourceControlPresentation.terminology;
|
||||
const SourceControlIcon = sourceControlPresentation.Icon;
|
||||
// Default to true while loading so we don't flash init controls.
|
||||
const isRepo = gitStatus?.isRepo ?? true;
|
||||
const vcsKind = gitStatus?.kind ?? null;
|
||||
@@ -427,7 +408,6 @@ export default function GitActionsControl({
|
||||
action: pendingDefaultBranchAction.action,
|
||||
branchName: pendingDefaultBranchAction.branchName,
|
||||
includesCommit: pendingDefaultBranchAction.includesCommit,
|
||||
terminology: changeRequestTerminology,
|
||||
})
|
||||
: null;
|
||||
|
||||
@@ -493,7 +473,7 @@ export default function GitActionsControl({
|
||||
if (!prUrl) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "No open pull request found.",
|
||||
title: "No open PR found.",
|
||||
data: threadToastData,
|
||||
});
|
||||
return;
|
||||
@@ -502,7 +482,7 @@ export default function GitActionsControl({
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open pull request link",
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
...(threadToastData !== undefined ? { data: threadToastData } : {}),
|
||||
}),
|
||||
@@ -559,7 +539,6 @@ export default function GitActionsControl({
|
||||
hasCustomCommitMessage: !!commitMessage?.trim(),
|
||||
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
|
||||
featureBranch,
|
||||
terminology: changeRequestTerminology,
|
||||
shouldPushBeforePr:
|
||||
action === "create_pr" &&
|
||||
(!actionStatus?.hasUpstream || (actionStatus?.aheadCount ?? 0) > 0),
|
||||
@@ -934,10 +913,7 @@ export default function GitActionsControl({
|
||||
/>
|
||||
}
|
||||
>
|
||||
<GitQuickActionIcon
|
||||
quickAction={quickAction}
|
||||
SourceControlIcon={SourceControlIcon}
|
||||
/>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
@@ -953,7 +929,7 @@ export default function GitActionsControl({
|
||||
disabled={isGitActionRunning || quickAction.disabled}
|
||||
onClick={runQuickAction}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} SourceControlIcon={SourceControlIcon} />
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
@@ -993,10 +969,7 @@ export default function GitActionsControl({
|
||||
render={<span className="block w-max cursor-not-allowed" />}
|
||||
>
|
||||
<MenuItem className="w-full" disabled>
|
||||
<GitActionItemIcon
|
||||
icon={item.icon}
|
||||
SourceControlIcon={SourceControlIcon}
|
||||
/>
|
||||
<GitActionItemIcon icon={item.icon} />
|
||||
{item.label}
|
||||
</MenuItem>
|
||||
</PopoverTrigger>
|
||||
@@ -1015,15 +988,14 @@ export default function GitActionsControl({
|
||||
openDialogForMenuItem(item);
|
||||
}}
|
||||
>
|
||||
<GitActionItemIcon icon={item.icon} SourceControlIcon={SourceControlIcon} />
|
||||
<GitActionItemIcon icon={item.icon} />
|
||||
{item.label}
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{gitStatusForActions?.refName === null && (
|
||||
<p className="px-2 py-1.5 text-xs text-warning">
|
||||
Detached HEAD: create and checkout a refName to enable push and pull request
|
||||
actions.
|
||||
Detached HEAD: create and checkout a refName to enable push and PR actions.
|
||||
</p>
|
||||
)}
|
||||
{gitStatusForActions &&
|
||||
|
||||
@@ -15,31 +15,6 @@ export const GitHubIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const GitLabIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M22.6 9.3 20.9 4c-.2-.7-1.2-.7-1.5-.1l-2 5.4H6.6l-2-5.4c-.2-.6-1.2-.6-1.5.1L1.4 9.3c-.2.6 0 1.2.5 1.6L12 18.7l10.1-7.8c.5-.4.7-1 .5-1.6Z" />
|
||||
<path d="m12 18.7 4.1-9.4H7.9L12 18.7Z" opacity=".72" />
|
||||
<path d="M7.9 9.3H1.5L12 18.7 7.9 9.3ZM16.1 9.3 12 18.7l10.5-9.4h-6.4Z" opacity=".88" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const AzureDevOpsIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M21 5.2v12.7L16 22l-8-2.8V22l-4.9-6.4 4.9.4V4.8L16 2l5 3.2ZM16 6.4l-5 1.4v8.4l5 1.4V6.4Z" />
|
||||
<path d="m8 8.4-5 .8v5.6l5 .8V8.4Z" opacity=".72" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const BitbucketIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M2.4 3.5c-.4 0-.7.3-.6.8L4.3 20c.1.4.4.7.8.7h13.7c.4 0 .7-.3.8-.7l2.6-15.7c.1-.5-.2-.8-.7-.8H2.4Zm12.5 11.1H9.4L8.5 8.7h7.4l-1 5.9Z" />
|
||||
<path
|
||||
d="M21 8.7h-5.1l-1 5.9H9.4l-4.2 5c.2.6.5 1.1 1.2 1.1h12.4c.4 0 .7-.3.8-.7L21 8.7Z"
|
||||
opacity=".72"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const CursorIcon: Icon = ({ className, ...props }) => (
|
||||
<svg
|
||||
{...props}
|
||||
|
||||
@@ -7,10 +7,8 @@ import {
|
||||
gitPreparePullRequestThreadMutationOptions,
|
||||
gitResolvePullRequestQueryOptions,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { useGitStatus } from "~/lib/gitStatusState";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { parsePullRequestReference } from "~/pullRequestReference";
|
||||
import { getSourceControlPresentation } from "~/sourceControlPresentation";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -53,13 +51,6 @@ export function PullRequestThreadDialog({
|
||||
{ wait: 450 },
|
||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||
);
|
||||
const { data: gitStatus = null } = useGitStatus({ environmentId, cwd });
|
||||
const sourceControlPresentation = useMemo(
|
||||
() => getSourceControlPresentation(gitStatus?.sourceControlProvider),
|
||||
[gitStatus?.sourceControlProvider],
|
||||
);
|
||||
const terminology = sourceControlPresentation.terminology;
|
||||
const SourceControlIcon = sourceControlPresentation.Icon;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -170,20 +161,20 @@ export function PullRequestThreadDialog({
|
||||
const validationMessage = !referenceDirty
|
||||
? null
|
||||
: reference.trim().length === 0
|
||||
? `Paste a ${terminology.singular} URL, checkout command, or enter 123 / #123.`
|
||||
? "Paste a GitHub pull request URL, `gh pr checkout 123`, or enter 123 / #123."
|
||||
: parsedReference === null
|
||||
? `Use a ${terminology.singular} URL, checkout command, 123, or #123.`
|
||||
? "Use a GitHub pull request URL, `gh pr checkout 123`, 123, or #123."
|
||||
: null;
|
||||
const errorMessage =
|
||||
validationMessage ??
|
||||
(resolvedPullRequest === null && resolvePullRequestQuery.isError
|
||||
? resolvePullRequestQuery.error instanceof Error
|
||||
? resolvePullRequestQuery.error.message
|
||||
: `Failed to resolve ${terminology.singular}.`
|
||||
: "Failed to resolve pull request."
|
||||
: preparePullRequestThreadMutation.error instanceof Error
|
||||
? preparePullRequestThreadMutation.error.message
|
||||
: preparePullRequestThreadMutation.error
|
||||
? `Failed to prepare ${terminology.singular} thread.`
|
||||
? "Failed to prepare pull request thread."
|
||||
: null);
|
||||
|
||||
return (
|
||||
@@ -197,23 +188,18 @@ export function PullRequestThreadDialog({
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<SourceControlIcon className="size-4" />
|
||||
Checkout {terminology.singular}
|
||||
</DialogTitle>
|
||||
<DialogTitle>Checkout Pull Request</DialogTitle>
|
||||
<DialogDescription>
|
||||
Resolve a {sourceControlPresentation.providerName} {terminology.singular}, then create
|
||||
the draft thread in the main repo or in a dedicated worktree.
|
||||
Resolve a GitHub pull request, then create the draft thread in the main repo or in a
|
||||
dedicated worktree.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4">
|
||||
<label className="grid gap-1.5">
|
||||
<span className="text-xs font-medium text-foreground capitalize">
|
||||
{terminology.singular}
|
||||
</span>
|
||||
<span className="text-xs font-medium text-foreground">Pull request</span>
|
||||
<Input
|
||||
ref={referenceInputRef}
|
||||
placeholder={`${terminology.shortLabel} URL, checkout command, or #42`}
|
||||
placeholder="https://github.com/owner/repo/pull/42, gh pr checkout 42, or #42"
|
||||
value={reference}
|
||||
onChange={(event) => {
|
||||
setReferenceDirty(true);
|
||||
@@ -251,7 +237,7 @@ export function PullRequestThreadDialog({
|
||||
{isResolving ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground text-xs">
|
||||
<Spinner className="size-3.5" />
|
||||
Resolving {terminology.singular}...
|
||||
Resolving pull request...
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ArrowUpDownIcon,
|
||||
ChevronRightIcon,
|
||||
CloudIcon,
|
||||
GitPullRequestIcon,
|
||||
FolderPlusIcon,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
@@ -11,7 +12,6 @@ import {
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
ChangeRequestStatusIcon,
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
terminalStatusFromRunningIds,
|
||||
@@ -367,7 +367,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
},
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const prStatus = prStatusIndicator(pr);
|
||||
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
|
||||
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
|
||||
const threadMetaClassName = isConfirmingArchive
|
||||
@@ -558,7 +558,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
|
||||
onClick={handlePrClick}
|
||||
>
|
||||
<ChangeRequestStatusIcon className="size-3" />
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
@@ -1002,7 +1002,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open pull request link",
|
||||
title: "Unable to open PR link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -11,13 +11,12 @@ import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { type AppState, selectProjectByRef, useStore } from "../store";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
|
||||
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
|
||||
import type { SidebarThreadSummary } from "../types";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
export interface PrStatusIndicator {
|
||||
label: string;
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
colorClass: string;
|
||||
tooltip: string;
|
||||
url: string;
|
||||
@@ -31,44 +30,36 @@ export interface TerminalStatusIndicator {
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
): PrStatusIndicator | null {
|
||||
export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
if (!pr) return null;
|
||||
const presentation = resolveChangeRequestPresentation(provider);
|
||||
|
||||
if (pr.state === "open") {
|
||||
return {
|
||||
label: `${presentation.shortName} open`,
|
||||
label: "PR open",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
tooltip: `#${pr.number} ${presentation.shortName} open: ${pr.title}`,
|
||||
tooltip: `#${pr.number} PR open: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
label: "PR closed",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip: `#${pr.number} ${presentation.shortName} closed: ${pr.title}`,
|
||||
tooltip: `#${pr.number} PR closed: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (pr.state === "merged") {
|
||||
return {
|
||||
label: `${presentation.shortName} merged`,
|
||||
label: "PR merged",
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
tooltip: `#${pr.number} ${presentation.shortName} merged: ${pr.title}`,
|
||||
tooltip: `#${pr.number} PR merged: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ChangeRequestStatusIcon({ className }: { className?: string }) {
|
||||
return <GitPullRequestIcon className={className} />;
|
||||
}
|
||||
|
||||
export function resolveThreadPr(
|
||||
threadBranch: string | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
@@ -133,7 +124,7 @@ export function ThreadStatusLabel({
|
||||
|
||||
/**
|
||||
* Non-interactive leading status icons for a thread row in compact contexts
|
||||
* like the command palette. Shows the change request state icon (if present) and the
|
||||
* like the command palette. Shows the PR state icon (if present) and the
|
||||
* thread status dot, matching the sidebar's leading indicators.
|
||||
*/
|
||||
export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
|
||||
@@ -155,7 +146,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
cwd: thread.branch != null ? gitCwd : null,
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const prStatus = prStatusIndicator(pr);
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
@@ -179,7 +170,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ChangeRequestStatusIcon className="size-3" />
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
@@ -9,24 +9,6 @@ describe("parsePullRequestReference", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts Azure DevOps pull request URLs", () => {
|
||||
expect(
|
||||
parsePullRequestReference("https://dev.azure.com/acme/project/_git/t3code/pullrequest/42"),
|
||||
).toBe("https://dev.azure.com/acme/project/_git/t3code/pullrequest/42");
|
||||
});
|
||||
|
||||
it("accepts GitLab merge request URLs", () => {
|
||||
expect(parsePullRequestReference("https://gitlab.com/group/project/-/merge_requests/42")).toBe(
|
||||
"https://gitlab.com/group/project/-/merge_requests/42",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts legacy Azure DevOps pull request URLs", () => {
|
||||
expect(
|
||||
parsePullRequestReference("https://acme.visualstudio.com/project/_git/t3code/pullrequest/42"),
|
||||
).toBe("https://acme.visualstudio.com/project/_git/t3code/pullrequest/42");
|
||||
});
|
||||
|
||||
it("accepts raw numbers", () => {
|
||||
expect(parsePullRequestReference("42")).toBe("42");
|
||||
});
|
||||
@@ -49,20 +31,6 @@ describe("parsePullRequestReference", () => {
|
||||
).toBe("https://github.com/pingdotgg/t3code/pull/42");
|
||||
});
|
||||
|
||||
it("accepts glab mr checkout commands with raw numbers", () => {
|
||||
expect(parsePullRequestReference("glab mr checkout 42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts az repos pr checkout commands with raw numbers", () => {
|
||||
expect(parsePullRequestReference("az repos pr checkout --id 42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts az repos pr checkout commands with extra flags", () => {
|
||||
expect(parsePullRequestReference("az repos pr checkout --id 42 --remote-name origin")).toBe(
|
||||
"42",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects non-pull-request input", () => {
|
||||
expect(parsePullRequestReference("feature/my-branch")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1,22 +1,7 @@
|
||||
const GITHUB_PULL_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
|
||||
const GITLAB_MERGE_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/[^/\s]*gitlab[^/\s]*\/.+\/-\/merge_requests\/(\d+)(?:[/?#].*)?$/i;
|
||||
const AZURE_DEVOPS_PULL_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
|
||||
const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/;
|
||||
const GITHUB_CLI_PR_CHECKOUT_PATTERN = /^gh\s+pr\s+checkout\s+(.+)$/i;
|
||||
const GITLAB_CLI_MR_CHECKOUT_PATTERN = /^glab\s+mr\s+checkout\s+(.+)$/i;
|
||||
const AZURE_DEVOPS_CLI_PR_CHECKOUT_PATTERN = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
|
||||
|
||||
function parseAzureDevOpsCheckoutReference(args: string): string | null {
|
||||
const parts = args.trim().split(/\s+/).filter(Boolean);
|
||||
const idFlagIndex = parts.findIndex((part) => part === "--id" || part === "-i");
|
||||
if (idFlagIndex >= 0) {
|
||||
return parts[idFlagIndex + 1] ?? null;
|
||||
}
|
||||
return parts.find((part) => !part.startsWith("-")) ?? null;
|
||||
}
|
||||
|
||||
export function parsePullRequestReference(input: string): string | null {
|
||||
const trimmed = input.trim();
|
||||
@@ -25,23 +10,12 @@ export function parsePullRequestReference(input: string): string | null {
|
||||
}
|
||||
|
||||
const ghCliCheckoutMatch = GITHUB_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const glabCliCheckoutMatch = GITLAB_CLI_MR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const azureDevOpsCliCheckoutMatch = AZURE_DEVOPS_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const normalizedInput =
|
||||
ghCliCheckoutMatch?.[1]?.trim() ??
|
||||
glabCliCheckoutMatch?.[1]?.trim() ??
|
||||
(azureDevOpsCliCheckoutMatch?.[1]
|
||||
? parseAzureDevOpsCheckoutReference(azureDevOpsCliCheckoutMatch[1])
|
||||
: null) ??
|
||||
trimmed;
|
||||
const normalizedInput = ghCliCheckoutMatch?.[1]?.trim() ?? trimmed;
|
||||
if (normalizedInput.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const urlMatch =
|
||||
GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput) ??
|
||||
GITLAB_MERGE_REQUEST_URL_PATTERN.exec(normalizedInput) ??
|
||||
AZURE_DEVOPS_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
|
||||
if (urlMatch?.[1]) {
|
||||
return normalizedInput;
|
||||
}
|
||||
|
||||
@@ -1,62 +1,96 @@
|
||||
import { GitPullRequestIcon } from "lucide-react";
|
||||
import type { ElementType } from "react";
|
||||
import type { SourceControlProviderInfo } from "@t3tools/contracts";
|
||||
export {
|
||||
DEFAULT_CHANGE_REQUEST_TERMINOLOGY,
|
||||
formatChangeRequestAction,
|
||||
formatCreateChangeRequestPhrase,
|
||||
getChangeRequestTerminology,
|
||||
resolveChangeRequestPresentation,
|
||||
type ChangeRequestPresentation,
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
import {
|
||||
getChangeRequestTerminology,
|
||||
resolveChangeRequestPresentation,
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./components/Icons";
|
||||
|
||||
export interface SourceControlPresentation {
|
||||
export interface ChangeRequestPresentation {
|
||||
readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";
|
||||
readonly providerName: string;
|
||||
readonly terminology: ChangeRequestTerminology;
|
||||
readonly Icon: ElementType<{ className?: string }>;
|
||||
readonly shortName: string;
|
||||
readonly longName: string;
|
||||
readonly pluralLongName: string;
|
||||
readonly providerLongName: string;
|
||||
readonly checkoutCommandExample: string;
|
||||
readonly urlExample: string;
|
||||
}
|
||||
|
||||
export function getSourceControlPresentation(
|
||||
const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "github",
|
||||
providerName: "GitHub",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "GitHub pull request",
|
||||
checkoutCommandExample: "gh pr checkout 123",
|
||||
urlExample: "https://github.com/owner/repo/pull/42",
|
||||
};
|
||||
|
||||
const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "gitlab",
|
||||
providerName: "GitLab",
|
||||
shortName: "MR",
|
||||
longName: "merge request",
|
||||
pluralLongName: "merge requests",
|
||||
providerLongName: "GitLab merge request",
|
||||
checkoutCommandExample: "glab mr checkout 123",
|
||||
urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
|
||||
};
|
||||
|
||||
const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "azure-devops",
|
||||
providerName: "Azure DevOps",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Azure DevOps pull request",
|
||||
checkoutCommandExample: "az repos pr checkout --id 123",
|
||||
urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
|
||||
};
|
||||
|
||||
const BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "bitbucket",
|
||||
providerName: "Bitbucket",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Bitbucket pull request",
|
||||
checkoutCommandExample: "bb pr checkout 123",
|
||||
urlExample: "https://bitbucket.org/workspace/repo/pull-requests/42",
|
||||
};
|
||||
|
||||
const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "change-request",
|
||||
providerName: "source control",
|
||||
shortName: "change request",
|
||||
longName: "change request",
|
||||
pluralLongName: "change requests",
|
||||
providerLongName: "change request",
|
||||
checkoutCommandExample: "123",
|
||||
urlExample: "#42",
|
||||
};
|
||||
|
||||
export function resolveChangeRequestPresentation(
|
||||
provider: SourceControlProviderInfo | null | undefined,
|
||||
): SourceControlPresentation {
|
||||
const presentation = resolveChangeRequestPresentation(provider);
|
||||
switch (presentation.icon) {
|
||||
): ChangeRequestPresentation {
|
||||
switch (provider?.kind) {
|
||||
case "github":
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: GitHubIcon,
|
||||
};
|
||||
case undefined:
|
||||
return GITHUB_CHANGE_REQUEST_PRESENTATION;
|
||||
case "gitlab":
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: GitLabIcon,
|
||||
};
|
||||
return GITLAB_CHANGE_REQUEST_PRESENTATION;
|
||||
case "azure-devops":
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: AzureDevOpsIcon,
|
||||
};
|
||||
return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
|
||||
case "bitbucket":
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: BitbucketIcon,
|
||||
};
|
||||
case "change-request":
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: GitPullRequestIcon,
|
||||
};
|
||||
return BITBUCKET_CHANGE_REQUEST_PRESENTATION;
|
||||
case "unknown":
|
||||
return GENERIC_CHANGE_REQUEST_PRESENTATION;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatChangeRequestAction(
|
||||
verb: "View" | "Create",
|
||||
presentation: ChangeRequestPresentation,
|
||||
): string {
|
||||
return `${verb} ${presentation.shortName}`;
|
||||
}
|
||||
|
||||
export function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {
|
||||
return `create ${presentation.shortName}`;
|
||||
}
|
||||
@@ -180,7 +180,6 @@ export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type;
|
||||
|
||||
export const VcsInitInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
kind: Schema.optional(VcsDriverKind),
|
||||
});
|
||||
export type VcsInitInput = typeof VcsInitInput.Type;
|
||||
|
||||
|
||||
@@ -78,7 +78,6 @@ import {
|
||||
} from "./server.ts";
|
||||
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
|
||||
import { SourceControlDiscoveryResult } from "./sourceControl.ts";
|
||||
import { VcsError } from "./vcs.ts";
|
||||
|
||||
export const WS_METHODS = {
|
||||
// Project registry methods
|
||||
@@ -267,7 +266,7 @@ export const WsVcsSwitchRefRpc = Rpc.make(WS_METHODS.vcsSwitchRef, {
|
||||
|
||||
export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {
|
||||
payload: VcsInitInput,
|
||||
error: VcsError,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
detectSourceControlProviderFromRemoteUrl,
|
||||
getChangeRequestTerminologyForKind,
|
||||
resolveChangeRequestPresentation,
|
||||
} from "./sourceControl.ts";
|
||||
|
||||
describe("source control presentation", () => {
|
||||
it("uses merge request terminology for GitLab", () => {
|
||||
expect(getChangeRequestTerminologyForKind("gitlab")).toEqual({
|
||||
shortLabel: "MR",
|
||||
singular: "merge request",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses pull request terminology for GitHub-compatible providers", () => {
|
||||
expect(getChangeRequestTerminologyForKind("github")).toEqual({
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
});
|
||||
expect(getChangeRequestTerminologyForKind("azure-devops")).toEqual({
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
});
|
||||
expect(getChangeRequestTerminologyForKind("bitbucket")).toEqual({
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to generic change request copy for unknown providers", () => {
|
||||
expect(
|
||||
resolveChangeRequestPresentation({ kind: "unknown", name: "forge", baseUrl: "" }),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
shortName: "change request",
|
||||
longName: "change request",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectSourceControlProviderFromRemoteUrl", () => {
|
||||
it("detects common source control hosts", () => {
|
||||
expect(detectSourceControlProviderFromRemoteUrl("[email protected]:owner/repo.git")?.kind).toBe(
|
||||
"github",
|
||||
);
|
||||
expect(
|
||||
detectSourceControlProviderFromRemoteUrl("https://gitlab.com/group/repo.git")?.kind,
|
||||
).toBe("gitlab");
|
||||
expect(
|
||||
detectSourceControlProviderFromRemoteUrl("https://dev.azure.com/org/project/_git/repo")?.kind,
|
||||
).toBe("azure-devops");
|
||||
expect(
|
||||
detectSourceControlProviderFromRemoteUrl("[email protected]:workspace/repo.git")?.kind,
|
||||
).toBe("bitbucket");
|
||||
});
|
||||
});
|
||||
@@ -1,139 +1,4 @@
|
||||
import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";
|
||||
|
||||
export interface ChangeRequestPresentation {
|
||||
readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";
|
||||
readonly providerName: string;
|
||||
readonly shortName: string;
|
||||
readonly longName: string;
|
||||
readonly pluralLongName: string;
|
||||
readonly providerLongName: string;
|
||||
readonly checkoutCommandExample: string;
|
||||
readonly urlExample: string;
|
||||
}
|
||||
|
||||
export interface ChangeRequestTerminology {
|
||||
readonly shortLabel: string;
|
||||
readonly singular: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_CHANGE_REQUEST_TERMINOLOGY: ChangeRequestTerminology = {
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
};
|
||||
|
||||
const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "github",
|
||||
providerName: "GitHub",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "GitHub pull request",
|
||||
checkoutCommandExample: "gh pr checkout 123",
|
||||
urlExample: "https://github.com/owner/repo/pull/42",
|
||||
};
|
||||
|
||||
const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "gitlab",
|
||||
providerName: "GitLab",
|
||||
shortName: "MR",
|
||||
longName: "merge request",
|
||||
pluralLongName: "merge requests",
|
||||
providerLongName: "GitLab merge request",
|
||||
checkoutCommandExample: "glab mr checkout 123",
|
||||
urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
|
||||
};
|
||||
|
||||
const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "azure-devops",
|
||||
providerName: "Azure DevOps",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Azure DevOps pull request",
|
||||
checkoutCommandExample: "az repos pr checkout --id 123",
|
||||
urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
|
||||
};
|
||||
|
||||
const BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "bitbucket",
|
||||
providerName: "Bitbucket",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Bitbucket pull request",
|
||||
checkoutCommandExample: "bb pr checkout 123",
|
||||
urlExample: "https://bitbucket.org/workspace/repo/pull-requests/42",
|
||||
};
|
||||
|
||||
const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "change-request",
|
||||
providerName: "source control",
|
||||
shortName: "change request",
|
||||
longName: "change request",
|
||||
pluralLongName: "change requests",
|
||||
providerLongName: "change request",
|
||||
checkoutCommandExample: "123",
|
||||
urlExample: "#42",
|
||||
};
|
||||
|
||||
export function resolveChangeRequestPresentation(
|
||||
provider: SourceControlProviderInfo | null | undefined,
|
||||
): ChangeRequestPresentation {
|
||||
switch (provider?.kind) {
|
||||
case "github":
|
||||
case undefined:
|
||||
return GITHUB_CHANGE_REQUEST_PRESENTATION;
|
||||
case "gitlab":
|
||||
return GITLAB_CHANGE_REQUEST_PRESENTATION;
|
||||
case "azure-devops":
|
||||
return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
|
||||
case "bitbucket":
|
||||
return BITBUCKET_CHANGE_REQUEST_PRESENTATION;
|
||||
case "unknown":
|
||||
return GENERIC_CHANGE_REQUEST_PRESENTATION;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveChangeRequestPresentationForKind(
|
||||
kind: SourceControlProviderKind,
|
||||
): ChangeRequestPresentation {
|
||||
return resolveChangeRequestPresentation({ kind, name: "", baseUrl: "" });
|
||||
}
|
||||
|
||||
export function formatChangeRequestAction(
|
||||
verb: "View" | "Create",
|
||||
presentation: ChangeRequestPresentation,
|
||||
): string {
|
||||
return `${verb} ${presentation.shortName}`;
|
||||
}
|
||||
|
||||
export function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {
|
||||
return `create ${presentation.shortName}`;
|
||||
}
|
||||
|
||||
export function getChangeRequestTerminology(
|
||||
provider: SourceControlProviderInfo | null | undefined,
|
||||
): ChangeRequestTerminology {
|
||||
if (!provider) {
|
||||
return DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
}
|
||||
|
||||
const presentation = resolveChangeRequestPresentation(provider);
|
||||
return {
|
||||
shortLabel: presentation.shortName,
|
||||
singular: presentation.longName,
|
||||
};
|
||||
}
|
||||
|
||||
export function getChangeRequestTerminologyForKind(
|
||||
kind: SourceControlProviderKind,
|
||||
): ChangeRequestTerminology {
|
||||
const presentation = resolveChangeRequestPresentationForKind(kind);
|
||||
return {
|
||||
shortLabel: presentation.shortName,
|
||||
singular: presentation.longName,
|
||||
};
|
||||
}
|
||||
import type { SourceControlProviderInfo } from "@t3tools/contracts";
|
||||
|
||||
function parseRemoteHost(remoteUrl: string): string | null {
|
||||
const trimmed = remoteUrl.trim();
|
||||
|
||||
Reference in new issue
Block a user