Rename git APIs around refs
- Replace branch-centric git/VCS types and methods with ref-based names - Update server, web, and tests to use the new pluggable integration shape
This commit is contained in:
1 parent
506e0fc049
commit
e795698818
37 files changed
+1138
-1140
No files matched your search
@@ -331,9 +331,9 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
|
||||
@@ -3,27 +3,27 @@ import { Context, Effect, Layer } from "effect";
|
||||
import {
|
||||
GitManagerError,
|
||||
GitCommandError,
|
||||
type GitCheckoutInput,
|
||||
type GitCheckoutResult,
|
||||
type GitCreateBranchInput,
|
||||
type GitCreateBranchResult,
|
||||
type GitCreateWorktreeInput,
|
||||
type GitCreateWorktreeResult,
|
||||
type GitListBranchesInput,
|
||||
type GitListBranchesResult,
|
||||
type VcsSwitchRefInput,
|
||||
type VcsSwitchRefResult,
|
||||
type VcsCreateRefInput,
|
||||
type VcsCreateRefResult,
|
||||
type VcsCreateWorktreeInput,
|
||||
type VcsCreateWorktreeResult,
|
||||
type VcsListRefsInput,
|
||||
type VcsListRefsResult,
|
||||
type GitManagerServiceError,
|
||||
type GitPreparePullRequestThreadInput,
|
||||
type GitPreparePullRequestThreadResult,
|
||||
type GitPullRequestRefInput,
|
||||
type GitPullResult,
|
||||
type GitRemoveWorktreeInput,
|
||||
type VcsPullResult,
|
||||
type VcsRemoveWorktreeInput,
|
||||
type GitResolvePullRequestResult,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type GitStatusInput,
|
||||
type GitStatusLocalResult,
|
||||
type GitStatusRemoteResult,
|
||||
type GitStatusResult,
|
||||
type VcsStatusInput,
|
||||
type VcsStatusLocalResult,
|
||||
type VcsStatusRemoteResult,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitManager, type GitRunStackedActionOptions } from "./Services/GitManager.ts";
|
||||
@@ -32,18 +32,18 @@ import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
export interface GitWorkflowServiceShape {
|
||||
readonly status: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
@@ -54,25 +54,23 @@ export interface GitWorkflowServiceShape {
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly listBranches: (
|
||||
input: GitListBranchesInput,
|
||||
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
|
||||
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
||||
readonly createWorktree: (
|
||||
input: GitCreateWorktreeInput,
|
||||
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
|
||||
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createBranch: (
|
||||
input: GitCreateBranchInput,
|
||||
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
||||
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;
|
||||
readonly newBranch: string;
|
||||
}) => Effect.Effect<GitCreateBranchResult, GitManagerServiceError>;
|
||||
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitWorkflowService extends Context.Service<
|
||||
@@ -178,9 +176,9 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
"GitWorkflowService.preparePullRequestThread",
|
||||
gitManager.preparePullRequestThread,
|
||||
),
|
||||
listBranches: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.listBranches", input.cwd).pipe(
|
||||
Effect.andThen(git.listBranches(input)),
|
||||
listRefs: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.andThen(git.listRefs(input)),
|
||||
),
|
||||
createWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
@@ -190,13 +188,13 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.removeWorktree(input)),
|
||||
),
|
||||
createBranch: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createBranch", input.cwd).pipe(
|
||||
Effect.andThen(git.createBranch(input)),
|
||||
createRef: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
|
||||
Effect.andThen(git.createRef(input)),
|
||||
),
|
||||
checkoutBranch: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.checkoutBranch", input.cwd).pipe(
|
||||
Effect.andThen(Effect.scoped(git.checkoutBranch(input))),
|
||||
switchRef: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
|
||||
Effect.andThen(Effect.scoped(git.switchRef(input))),
|
||||
),
|
||||
initRepo: (input) => git.initRepo(input),
|
||||
renameBranch: (input) =>
|
||||
|
||||
@@ -717,15 +717,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.isRepo).toBe(true);
|
||||
expect(status.hasOriginRemote).toBe(true);
|
||||
expect(status.isDefaultBranch).toBe(false);
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.hasPrimaryRemote).toBe(true);
|
||||
expect(status.isDefaultRef).toBe(false);
|
||||
expect(status.refName).toBe("feature/status-open-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-open-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -762,8 +762,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
number: 14,
|
||||
title: "Existing PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-trimmed-pr",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-trimmed-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -813,8 +813,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
number: 15,
|
||||
title: "Valid PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-valid-pr-entry",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-valid-pr-entry",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -862,8 +862,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-lowercase-state",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
@@ -878,9 +878,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -907,9 +907,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -991,7 +991,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("main");
|
||||
expect(status.refName).toBe("main");
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -1045,13 +1045,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("t3code/pr-488/statemachine");
|
||||
expect(status.refName).toBe("t3code/pr-488/statemachine");
|
||||
expect(status.pr).toEqual({
|
||||
number: 488,
|
||||
title: "Rebase this PR on latest main",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
|
||||
baseBranch: "main",
|
||||
headBranch: "statemachine",
|
||||
baseRef: "main",
|
||||
headRef: "statemachine",
|
||||
state: "open",
|
||||
});
|
||||
expect(ghCalls).toContain(
|
||||
@@ -1145,13 +1145,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("upstream/effect-atom");
|
||||
expect(status.refName).toBe("upstream/effect-atom");
|
||||
expect(status.pr).toEqual({
|
||||
number: 1618,
|
||||
title: "Correct PR",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1618",
|
||||
baseBranch: "main",
|
||||
headBranch: "effect-atom",
|
||||
baseRef: "main",
|
||||
headRef: "effect-atom",
|
||||
state: "open",
|
||||
});
|
||||
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
|
||||
@@ -1195,13 +1195,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-merged-pr");
|
||||
expect(status.refName).toBe("feature/status-merged-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-merged-pr",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-merged-pr",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
@@ -1232,7 +1232,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("main");
|
||||
expect(status.refName).toBe("main");
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -1272,13 +1272,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||
expect(status.refName).toBe("feature/status-open-over-merged");
|
||||
expect(status.pr).toEqual({
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-over-merged",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-open-over-merged",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -1303,7 +1303,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.refName).toBe("feature/status-no-gh");
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -21,8 +21,8 @@ import {
|
||||
GitCommandError,
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
type GitStatusLocalResult,
|
||||
type GitStatusRemoteResult,
|
||||
type VcsStatusLocalResult,
|
||||
type VcsStatusRemoteResult,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -425,16 +425,16 @@ function toStatusPr(pr: PullRequestInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
baseRef: string;
|
||||
headRef: string;
|
||||
state: "open" | "closed" | "merged";
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
baseRef: pr.baseRefName,
|
||||
headRef: pr.headRefName,
|
||||
state: pr.state,
|
||||
};
|
||||
}
|
||||
@@ -666,12 +666,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
return {
|
||||
isRepo: details.isRepo,
|
||||
...(hostingProvider ? { hostingProvider } : {}),
|
||||
hasOriginRemote: details.hasOriginRemote,
|
||||
isDefaultBranch: details.isDefaultBranch,
|
||||
branch: details.branch,
|
||||
hasPrimaryRemote: details.hasOriginRemote,
|
||||
isDefaultRef: details.isDefaultBranch,
|
||||
refName: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
} satisfies GitStatusLocalResult;
|
||||
} satisfies VcsStatusLocalResult;
|
||||
});
|
||||
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
@@ -709,7 +709,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
pr,
|
||||
} satisfies GitStatusRemoteResult;
|
||||
} satisfies VcsStatusRemoteResult;
|
||||
});
|
||||
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
@@ -1390,9 +1390,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||
|
||||
const findLocalHeadBranch = (cwd: string) =>
|
||||
gitCore.listBranches({ cwd }).pipe(
|
||||
gitCore.listRefs({ cwd }).pipe(
|
||||
Effect.map((result) => {
|
||||
const localBranch = result.branches.find(
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
);
|
||||
if (localBranch) {
|
||||
@@ -1402,7 +1402,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
result.branches.find(
|
||||
result.refs.find(
|
||||
(branch) =>
|
||||
!branch.isRemote &&
|
||||
branch.name === pullRequest.headBranch &&
|
||||
@@ -1465,7 +1465,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const worktree = yield* gitCore.createWorktree({
|
||||
cwd: input.cwd,
|
||||
branch: localPullRequestBranch,
|
||||
refName: localPullRequestBranch,
|
||||
path: null,
|
||||
});
|
||||
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
|
||||
@@ -1473,7 +1473,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
return {
|
||||
pullRequest,
|
||||
branch: worktree.worktree.branch,
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath: worktree.worktree.path,
|
||||
};
|
||||
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
|
||||
@@ -1505,8 +1505,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||
|
||||
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||
yield* gitCore.createRef({ cwd, refName: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
|
||||
|
||||
return {
|
||||
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||
|
||||
@@ -14,10 +14,10 @@ import {
|
||||
GitResolvePullRequestResult,
|
||||
GitRunStackedActionInput,
|
||||
GitRunStackedActionResult,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusInput,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
@@ -40,22 +40,22 @@ export interface GitManagerShape {
|
||||
* Read current repository Git status plus open PR metadata when available.
|
||||
*/
|
||||
readonly status: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Read local repository status without remote hosting enrichment.
|
||||
*/
|
||||
readonly localStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Read remote tracking / PR status for a repository.
|
||||
*/
|
||||
readonly remoteStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Clear any cached local status snapshot for a repository.
|
||||
|
||||
@@ -291,9 +291,9 @@ describe("CheckpointReactor", () => {
|
||||
}).pipe(
|
||||
Effect.as({
|
||||
isRepo: true,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
|
||||
@@ -240,9 +240,9 @@ describe("ProviderCommandReactor", () => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "renamed-branch",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "renamed-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
|
||||
@@ -2362,9 +2362,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2378,9 +2378,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
status: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -2465,12 +2465,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
pullCurrentBranch: () =>
|
||||
Effect.succeed({
|
||||
status: "pulled",
|
||||
branch: "main",
|
||||
upstreamBranch: "origin/main",
|
||||
refName: "main",
|
||||
upstreamRef: "origin/main",
|
||||
}),
|
||||
listBranches: () =>
|
||||
listRefs: () =>
|
||||
Effect.succeed({
|
||||
branches: [
|
||||
refs: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
@@ -2479,17 +2479,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
],
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
hasPrimaryRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
}),
|
||||
createWorktree: () =>
|
||||
Effect.succeed({
|
||||
worktree: { path: "/tmp/wt", branch: "feature/demo" },
|
||||
worktree: { path: "/tmp/wt", refName: "feature/demo" },
|
||||
}),
|
||||
removeWorktree: () => Effect.void,
|
||||
createBranch: (input) => Effect.succeed({ branch: input.branch }),
|
||||
checkoutBranch: (input) => Effect.succeed({ branch: input.branch }),
|
||||
createRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
switchRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
initRepo: () => Effect.void,
|
||||
},
|
||||
},
|
||||
@@ -2548,23 +2548,21 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
assert.equal(prepared.branch, "feature/demo");
|
||||
|
||||
const branches = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsListBranches]({ cwd: "/tmp/repo" }),
|
||||
),
|
||||
const refs = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsListRefs]({ cwd: "/tmp/repo" })),
|
||||
);
|
||||
assert.equal(branches.branches[0]?.name, "main");
|
||||
assert.equal(refs.refs[0]?.name, "main");
|
||||
|
||||
const worktree = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsCreateWorktree]({
|
||||
cwd: "/tmp/repo",
|
||||
branch: "main",
|
||||
refName: "main",
|
||||
path: null,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(worktree.worktree.branch, "feature/demo");
|
||||
assert.equal(worktree.worktree.refName, "feature/demo");
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
@@ -2577,18 +2575,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsCreateBranch]({
|
||||
client[WS_METHODS.vcsCreateRef]({
|
||||
cwd: "/tmp/repo",
|
||||
branch: "feature/new",
|
||||
refName: "feature/new",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsCheckout]({
|
||||
client[WS_METHODS.vcsSwitchRef]({
|
||||
cwd: "/tmp/repo",
|
||||
branch: "main",
|
||||
refName: "main",
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -2634,9 +2632,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2655,9 +2653,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -2711,9 +2709,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2732,9 +2730,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -2773,8 +2771,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
pullCurrentBranch: () =>
|
||||
Effect.succeed({
|
||||
status: "pulled" as const,
|
||||
branch: "main",
|
||||
upstreamBranch: "origin/main",
|
||||
refName: "main",
|
||||
upstreamRef: "origin/main",
|
||||
}),
|
||||
},
|
||||
gitManager: {
|
||||
@@ -2783,9 +2781,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2826,9 +2824,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2902,9 +2900,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.andThen(
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -3568,9 +3566,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "t3code/bootstrap-branch",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "t3code/bootstrap-refName",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -3587,7 +3585,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
@@ -3656,7 +3654,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
@@ -3678,8 +3676,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
branch: "main",
|
||||
newBranch: "t3code/bootstrap-branch",
|
||||
refName: "main",
|
||||
newRefName: "t3code/bootstrap-refName",
|
||||
path: null,
|
||||
});
|
||||
assert.deepEqual(runForThread.mock.calls[0]?.[0], {
|
||||
@@ -3713,7 +3711,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
@@ -3773,7 +3771,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
@@ -3807,7 +3805,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
@@ -3890,7 +3888,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
@@ -3974,7 +3972,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
},
|
||||
runSetupScript: false,
|
||||
},
|
||||
|
||||
@@ -3,19 +3,19 @@ import { Context, DateTime, Effect, Layer, Option } from "effect";
|
||||
import {
|
||||
GitCommandError,
|
||||
VcsProcessExitError,
|
||||
type GitCheckoutInput,
|
||||
type GitCheckoutResult,
|
||||
type GitCreateBranchInput,
|
||||
type GitCreateBranchResult,
|
||||
type GitCreateWorktreeInput,
|
||||
type GitCreateWorktreeResult,
|
||||
type GitInitInput,
|
||||
type GitListBranchesInput,
|
||||
type GitListBranchesResult,
|
||||
type GitPullResult,
|
||||
type GitRemoveWorktreeInput,
|
||||
type GitStatusInput,
|
||||
type GitStatusResult,
|
||||
type VcsSwitchRefInput,
|
||||
type VcsSwitchRefResult,
|
||||
type VcsCreateRefInput,
|
||||
type VcsCreateRefResult,
|
||||
type VcsCreateWorktreeInput,
|
||||
type VcsCreateWorktreeResult,
|
||||
type VcsInitInput,
|
||||
type VcsListRefsInput,
|
||||
type VcsListRefsResult,
|
||||
type VcsPullResult,
|
||||
type VcsRemoveWorktreeInput,
|
||||
type VcsStatusInput,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
|
||||
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
|
||||
@@ -42,8 +42,18 @@ export interface ExecuteGitResult {
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
export interface GitStatusDetails {
|
||||
isRepo: boolean;
|
||||
hostingProvider?: VcsStatusResult["hostingProvider"];
|
||||
hasOriginRemote: boolean;
|
||||
isDefaultBranch: boolean;
|
||||
branch: string | null;
|
||||
upstreamRef: string | null;
|
||||
hasWorkingTreeChanges: boolean;
|
||||
workingTree: VcsStatusResult["workingTree"];
|
||||
hasUpstream: boolean;
|
||||
aheadCount: number;
|
||||
behindCount: number;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
@@ -131,7 +141,7 @@ export interface GitSetBranchUpstreamInput {
|
||||
|
||||
export interface GitVcsDriverShape {
|
||||
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;
|
||||
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
|
||||
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly prepareCommitContext: (
|
||||
@@ -150,19 +160,17 @@ export interface GitVcsDriverShape {
|
||||
) => Effect.Effect<GitPushResult, GitCommandError>;
|
||||
readonly readRangeContext: (
|
||||
cwd: string,
|
||||
baseBranch: string,
|
||||
baseRef: string,
|
||||
) => Effect.Effect<GitRangeContext, GitCommandError>;
|
||||
readonly readConfigValue: (
|
||||
cwd: string,
|
||||
key: string,
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
readonly listBranches: (
|
||||
input: GitListBranchesInput,
|
||||
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
|
||||
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
||||
readonly createWorktree: (
|
||||
input: GitCreateWorktreeInput,
|
||||
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly fetchPullRequestBranch: (
|
||||
input: GitFetchPullRequestBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
@@ -173,17 +181,17 @@ export interface GitVcsDriverShape {
|
||||
readonly setBranchUpstream: (
|
||||
input: GitSetBranchUpstreamInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly renameBranch: (
|
||||
input: GitRenameBranchInput,
|
||||
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
|
||||
readonly createBranch: (
|
||||
input: GitCreateBranchInput,
|
||||
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
|
||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
}
|
||||
|
||||
|
||||
@@ -79,13 +79,13 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const branches = yield* driver.listBranches({ cwd });
|
||||
assert.equal(branches.isRepo, false);
|
||||
assert.deepStrictEqual(branches.branches, []);
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
assert.equal(refs.isRepo, false);
|
||||
assert.deepStrictEqual(refs.refs, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports branch and dirty state for a repository", () =>
|
||||
it.effect("reports refName and dirty state for a repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
@@ -104,16 +104,16 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("branch operations", () => {
|
||||
it.effect("creates, checks out, renames, and lists branches", () =>
|
||||
describe("refName operations", () => {
|
||||
it.effect("creates, checks out, renames, and lists refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
yield* driver.createBranch({ cwd, branch: "feature/original" });
|
||||
const checkout = yield* driver.checkoutBranch({ cwd, branch: "feature/original" });
|
||||
assert.equal(checkout.branch, "feature/original");
|
||||
yield* driver.createRef({ cwd, refName: "feature/original" });
|
||||
const switchRef = yield* driver.switchRef({ cwd, refName: "feature/original" });
|
||||
assert.equal(switchRef.refName, "feature/original");
|
||||
|
||||
const renamed = yield* driver.renameBranch({
|
||||
cwd,
|
||||
@@ -123,15 +123,15 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
assert.equal(renamed.branch, "feature/renamed");
|
||||
assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/renamed");
|
||||
|
||||
const branches = yield* driver.listBranches({ cwd });
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
assert.equal(
|
||||
branches.branches.find((branch) => branch.name === "feature/renamed")?.current,
|
||||
refs.refs.find((refName) => refName.name === "feature/renamed")?.current,
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the existing branch when rename source and target match", () =>
|
||||
it.effect("returns the existing refName when rename source and target match", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
@@ -150,7 +150,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
});
|
||||
|
||||
describe("worktree operations", () => {
|
||||
it.effect("creates and removes a worktree for a new branch", () =>
|
||||
it.effect("creates and removes a worktree for a new refName", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
@@ -164,12 +164,12 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
const created = yield* driver.createWorktree({
|
||||
cwd,
|
||||
path: worktreePath,
|
||||
branch: initialBranch,
|
||||
newBranch: "feature/worktree",
|
||||
refName: initialBranch,
|
||||
newRefName: "feature/worktree",
|
||||
});
|
||||
|
||||
assert.equal(created.worktree.path, worktreePath);
|
||||
assert.equal(created.worktree.branch, "feature/worktree");
|
||||
assert.equal(created.worktree.refName, "feature/worktree");
|
||||
assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "feature/worktree");
|
||||
|
||||
yield* driver.removeWorktree({ cwd, path: worktreePath });
|
||||
@@ -212,13 +212,13 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).createBranch({
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).createRef({
|
||||
cwd,
|
||||
branch: "feature/push",
|
||||
refName: "feature/push",
|
||||
});
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).checkoutBranch({
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({
|
||||
cwd,
|
||||
branch: "feature/push",
|
||||
refName: "feature/push",
|
||||
});
|
||||
yield* writeTextFile(cwd, "feature.txt", "feature\n");
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).prepareCommitContext(cwd);
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError, type GitBranch } from "@t3tools/contracts";
|
||||
import { GitCommandError, type VcsRef } from "@t3tools/contracts";
|
||||
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
|
||||
import { compactTraceAttributes } from "../observability/Attributes.ts";
|
||||
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
|
||||
@@ -155,34 +155,34 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
|
||||
}
|
||||
|
||||
function filterBranchesForListQuery(
|
||||
branches: ReadonlyArray<GitBranch>,
|
||||
refs: ReadonlyArray<VcsRef>,
|
||||
query?: string,
|
||||
): ReadonlyArray<GitBranch> {
|
||||
): ReadonlyArray<VcsRef> {
|
||||
if (!query) {
|
||||
return branches;
|
||||
return refs;
|
||||
}
|
||||
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
|
||||
return refs.filter((refName) => refName.name.toLowerCase().includes(normalizedQuery));
|
||||
}
|
||||
|
||||
function paginateBranches(input: {
|
||||
branches: ReadonlyArray<GitBranch>;
|
||||
refs: ReadonlyArray<VcsRef>;
|
||||
cursor?: number | undefined;
|
||||
limit?: number | undefined;
|
||||
}): {
|
||||
branches: ReadonlyArray<GitBranch>;
|
||||
refs: ReadonlyArray<VcsRef>;
|
||||
nextCursor: number | null;
|
||||
totalCount: number;
|
||||
} {
|
||||
const cursor = input.cursor ?? 0;
|
||||
const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT;
|
||||
const totalCount = input.branches.length;
|
||||
const branches = input.branches.slice(cursor, cursor + limit);
|
||||
const nextCursor = cursor + branches.length < totalCount ? cursor + branches.length : null;
|
||||
const totalCount = input.refs.length;
|
||||
const refs = input.refs.slice(cursor, cursor + limit);
|
||||
const nextCursor = cursor + refs.length < totalCount ? cursor + refs.length : null;
|
||||
|
||||
return {
|
||||
branches,
|
||||
refs,
|
||||
nextCursor,
|
||||
totalCount,
|
||||
};
|
||||
@@ -223,7 +223,7 @@ function parseRemoteFetchUrls(stdout: string): Map<string, string> {
|
||||
function parseUpstreamRefWithRemoteNames(
|
||||
upstreamRef: string,
|
||||
remoteNames: ReadonlyArray<string>,
|
||||
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
|
||||
): { upstreamRef: string; remoteName: string; branchName: string } | null {
|
||||
const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
@@ -232,28 +232,28 @@ function parseUpstreamRefWithRemoteNames(
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName: parsed.remoteName,
|
||||
upstreamBranch: parsed.branchName,
|
||||
branchName: parsed.branchName,
|
||||
};
|
||||
}
|
||||
|
||||
function parseUpstreamRefByFirstSeparator(
|
||||
upstreamRef: string,
|
||||
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
|
||||
): { upstreamRef: string; remoteName: string; branchName: string } | null {
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex).trim();
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1).trim();
|
||||
if (remoteName.length === 0 || upstreamBranch.length === 0) {
|
||||
const branchName = upstreamRef.slice(separatorIndex + 1).trim();
|
||||
if (remoteName.length === 0 || branchName.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
branchName,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -265,11 +265,11 @@ function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string):
|
||||
}
|
||||
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
|
||||
const branchName = branchNameRaw?.trim() ?? "";
|
||||
const upstreamBranch = upstreamBranchRaw.trim();
|
||||
if (branchName.length === 0 || upstreamBranch.length === 0) {
|
||||
const candidateUpstreamRef = upstreamBranchRaw.trim();
|
||||
if (branchName.length === 0 || candidateUpstreamRef.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (upstreamBranch === upstreamRef) {
|
||||
if (candidateUpstreamRef === upstreamRef) {
|
||||
return branchName;
|
||||
}
|
||||
}
|
||||
@@ -296,8 +296,8 @@ function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string):
|
||||
if (!trimmed.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
const branch = trimmed.slice(prefix.length).trim();
|
||||
return branch.length > 0 ? branch : null;
|
||||
const refName = trimmed.slice(prefix.length).trim();
|
||||
return refName.length > 0 ? refName : null;
|
||||
}
|
||||
|
||||
function createGitCommandError(
|
||||
@@ -814,11 +814,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
),
|
||||
);
|
||||
|
||||
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
const branchExists = (cwd: string, refName: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit(
|
||||
"GitVcsDriver.branchExists",
|
||||
cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${refName}`],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
@@ -949,12 +949,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const remoteBranchExists = (
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
branch: string,
|
||||
refName: string,
|
||||
): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit(
|
||||
"GitVcsDriver.remoteBranchExists",
|
||||
cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`],
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${refName}`],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
@@ -989,12 +989,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
|
||||
const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
refName: string,
|
||||
) {
|
||||
const branchPushRemote = yield* runGitStdout(
|
||||
"GitVcsDriver.resolvePushRemoteName.branchPushRemote",
|
||||
cwd,
|
||||
["config", "--get", `branch.${branch}.pushRemote`],
|
||||
["config", "--get", `branch.${refName}.pushRemote`],
|
||||
true,
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
if (branchPushRemote.length > 0) {
|
||||
@@ -1049,12 +1049,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
|
||||
const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
refName: string,
|
||||
) {
|
||||
const configuredBaseBranch = yield* runGitStdout(
|
||||
"GitVcsDriver.resolveBaseBranchForNoUpstream.config",
|
||||
cwd,
|
||||
["config", "--get", `branch.${branch}.gh-merge-base`],
|
||||
["config", "--get", `branch.${refName}.gh-merge-base`],
|
||||
true,
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
@@ -1081,7 +1081,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
: remotePrefix && candidate.startsWith(remotePrefix)
|
||||
? candidate.slice(remotePrefix.length)
|
||||
: candidate;
|
||||
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
|
||||
if (normalizedCandidate.length === 0 || normalizedCandidate === refName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1102,17 +1102,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
|
||||
const computeAheadCountAgainstBase = Effect.fn("computeAheadCountAgainstBase")(function* (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
refName: string,
|
||||
) {
|
||||
const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch);
|
||||
if (!baseBranch) {
|
||||
const baseRef = yield* resolveBaseBranchForNoUpstream(cwd, refName);
|
||||
if (!baseRef) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = yield* executeGit(
|
||||
"GitVcsDriver.computeAheadCountAgainstBase",
|
||||
cwd,
|
||||
["rev-list", "--count", `${baseBranch}..HEAD`],
|
||||
["rev-list", "--count", `${baseRef}..HEAD`],
|
||||
{ allowNonZeroExit: true },
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
@@ -1183,7 +1183,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
);
|
||||
}
|
||||
|
||||
const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] =
|
||||
const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasPrimaryRemote] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
runGitStdout("GitVcsDriver.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
|
||||
@@ -1210,7 +1210,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
let branch: string | null = null;
|
||||
let refName: string | null = null;
|
||||
let upstreamRef: string | null = null;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
@@ -1220,7 +1220,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
for (const line of statusStdout.split(/\r?\n/g)) {
|
||||
if (line.startsWith("# branch.head ")) {
|
||||
const value = line.slice("# branch.head ".length).trim();
|
||||
branch = value.startsWith("(") ? null : value;
|
||||
refName = value.startsWith("(") ? null : value;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("# branch.upstream ")) {
|
||||
@@ -1242,8 +1242,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}
|
||||
}
|
||||
|
||||
if (!upstreamRef && branch) {
|
||||
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
|
||||
if (!upstreamRef && refName) {
|
||||
aheadCount = yield* computeAheadCountAgainstBase(cwd, refName).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
);
|
||||
behindCount = 0;
|
||||
@@ -1277,12 +1277,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote,
|
||||
hasOriginRemote: hasPrimaryRemote,
|
||||
isDefaultBranch:
|
||||
branch !== null &&
|
||||
(branch === defaultBranch ||
|
||||
(defaultBranch === null && (branch === "main" || branch === "master"))),
|
||||
branch,
|
||||
refName !== null &&
|
||||
(refName === defaultBranch ||
|
||||
(defaultBranch === null && (refName === "main" || refName === "master"))),
|
||||
branch: refName,
|
||||
upstreamRef,
|
||||
hasWorkingTreeChanges,
|
||||
workingTree: {
|
||||
@@ -1316,9 +1316,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
statusDetails(input.cwd).pipe(
|
||||
Effect.map((details) => ({
|
||||
isRepo: details.isRepo,
|
||||
hasOriginRemote: details.hasOriginRemote,
|
||||
isDefaultBranch: details.isDefaultBranch,
|
||||
branch: details.branch,
|
||||
hasPrimaryRemote: details.hasOriginRemote,
|
||||
isDefaultRef: details.isDefaultBranch,
|
||||
refName: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
hasUpstream: details.hasUpstream,
|
||||
@@ -1483,7 +1483,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
yield* runGit("GitVcsDriver.pushCurrentBranch.pushUpstream", cwd, [
|
||||
"push",
|
||||
currentUpstream.remoteName,
|
||||
`HEAD:${currentUpstream.upstreamBranch}`,
|
||||
`HEAD:${currentUpstream.upstreamRef}`,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
@@ -1506,8 +1506,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const pullCurrentBranch: GitVcsDriverShape["pullCurrentBranch"] = Effect.fn("pullCurrentBranch")(
|
||||
function* (cwd) {
|
||||
const details = yield* statusDetails(cwd);
|
||||
const branch = details.branch;
|
||||
if (!branch) {
|
||||
const refName = details.branch;
|
||||
if (!refName) {
|
||||
return yield* createGitCommandError(
|
||||
"GitVcsDriver.pullCurrentBranch",
|
||||
cwd,
|
||||
@@ -1543,15 +1543,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const refreshed = yield* statusDetails(cwd);
|
||||
return {
|
||||
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
|
||||
branch,
|
||||
upstreamBranch: refreshed.upstreamRef,
|
||||
refName,
|
||||
upstreamRef: refreshed.upstreamRef,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const readRangeContext: GitVcsDriverShape["readRangeContext"] = Effect.fn("readRangeContext")(
|
||||
function* (cwd, baseBranch) {
|
||||
const range = `${baseBranch}..HEAD`;
|
||||
function* (cwd, baseRef) {
|
||||
const range = `${baseRef}..HEAD`;
|
||||
const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(
|
||||
[
|
||||
runGitStdoutWithOptions(
|
||||
@@ -1599,232 +1599,230 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
|
||||
);
|
||||
|
||||
const listBranches: GitVcsDriverShape["listBranches"] = Effect.fn("listBranches")(
|
||||
function* (input) {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
);
|
||||
const localBranchResult = yield* executeGit(
|
||||
"GitVcsDriver.listBranches.branchNoColor",
|
||||
const listRefs: GitVcsDriverShape["listRefs"] = Effect.fn("listRefs")(function* (input) {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
);
|
||||
const localBranchResult = yield* executeGit(
|
||||
"GitVcsDriver.listRefs.branchNoColor",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--no-column"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () =>
|
||||
Effect.succeed({
|
||||
code: 128,
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
return yield* createGitCommandError(
|
||||
"GitVcsDriver.listRefs",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--no-column"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () =>
|
||||
Effect.succeed({
|
||||
code: 128,
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
stderr || "git branch failed",
|
||||
);
|
||||
}
|
||||
|
||||
const remoteBranchResultEffect = executeGit(
|
||||
"GitVcsDriver.listRefs.remoteBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--no-column", "--remotes"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitVcsDriver.listRefs: remote refName lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote refName list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
);
|
||||
|
||||
const remoteNamesResultEffect = executeGit(
|
||||
"GitVcsDriver.listRefs.remoteNames",
|
||||
input.cwd,
|
||||
["remote"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitVcsDriver.listRefs: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
);
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitVcsDriver.listRefs.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitVcsDriver.listRefs.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return {
|
||||
branches: [],
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
return yield* createGitCommandError(
|
||||
"GitVcsDriver.listBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--no-column"],
|
||||
stderr || "git branch failed",
|
||||
);
|
||||
}
|
||||
|
||||
const remoteBranchResultEffect = executeGit(
|
||||
"GitVcsDriver.listBranches.remoteBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--no-column", "--remotes"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitVcsDriver.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
const remoteNames =
|
||||
remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitVcsDriver.listRefs: remote refName lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote refName list.`,
|
||||
);
|
||||
|
||||
const remoteNamesResultEffect = executeGit(
|
||||
"GitVcsDriver.listBranches.remoteNames",
|
||||
input.cwd,
|
||||
["remote"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitVcsDriver.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
}
|
||||
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitVcsDriver.listRefs: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
|
||||
);
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitVcsDriver.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitVcsDriver.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
const remoteNames =
|
||||
remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitVcsDriver.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
|
||||
);
|
||||
}
|
||||
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitVcsDriver.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
|
||||
);
|
||||
}
|
||||
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
const worktreeMap = new Map<string, string>();
|
||||
if (worktreeList.code === 0) {
|
||||
let currentPath: string | null = null;
|
||||
for (const line of worktreeList.stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
const exists = yield* fileSystem.stat(candidatePath).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
currentPath = exists ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
|
||||
} else if (line === "") {
|
||||
currentPath = null;
|
||||
}
|
||||
const worktreeMap = new Map<string, string>();
|
||||
if (worktreeList.code === 0) {
|
||||
let currentPath: string | null = null;
|
||||
for (const line of worktreeList.stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
const exists = yield* fileSystem.stat(candidatePath).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
currentPath = exists ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
|
||||
} else if (line === "") {
|
||||
currentPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => ({
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((refName): refName is { name: string; current: boolean } => refName !== null)
|
||||
.map((refName) => ({
|
||||
name: refName.name,
|
||||
current: refName.current,
|
||||
isRemote: false,
|
||||
isDefault: refName.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(refName.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.code === 0
|
||||
? remoteBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => {
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: branch.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return remoteBranch;
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const branches = paginateBranches({
|
||||
branches: filterBranchesForListQuery(
|
||||
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
|
||||
input.query,
|
||||
),
|
||||
cursor: input.cursor,
|
||||
limit: input.limit,
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return {
|
||||
branches: [...branches.branches],
|
||||
isRepo: true,
|
||||
hasOriginRemote: remoteNames.includes("origin"),
|
||||
nextCursor: branches.nextCursor,
|
||||
totalCount: branches.totalCount,
|
||||
};
|
||||
},
|
||||
);
|
||||
const remoteBranches =
|
||||
remoteBranchResult.code === 0
|
||||
? remoteBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((refName): refName is { name: string; current: boolean } => refName !== null)
|
||||
.map((refName) => {
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(refName.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return remoteBranch;
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const refs = paginateBranches({
|
||||
refs: filterBranchesForListQuery(
|
||||
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
|
||||
input.query,
|
||||
),
|
||||
cursor: input.cursor,
|
||||
limit: input.limit,
|
||||
});
|
||||
|
||||
return {
|
||||
refs: [...refs.refs],
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: remoteNames.includes("origin"),
|
||||
nextCursor: refs.nextCursor,
|
||||
totalCount: refs.totalCount,
|
||||
};
|
||||
});
|
||||
|
||||
const createWorktree: GitVcsDriverShape["createWorktree"] = Effect.fn("createWorktree")(
|
||||
function* (input) {
|
||||
const targetBranch = input.newBranch ?? input.branch;
|
||||
const targetBranch = input.newRefName ?? input.refName;
|
||||
const sanitizedBranch = targetBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);
|
||||
const args = input.newBranch
|
||||
? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch]
|
||||
: ["worktree", "add", worktreePath, input.branch];
|
||||
const args = input.newRefName
|
||||
? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]
|
||||
: ["worktree", "add", worktreePath, input.refName];
|
||||
|
||||
yield* executeGit("GitVcsDriver.createWorktree", input.cwd, args, {
|
||||
fallbackErrorMessage: "git worktree add failed",
|
||||
@@ -1833,7 +1831,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return {
|
||||
worktree: {
|
||||
path: worktreePath,
|
||||
branch: targetBranch,
|
||||
refName: targetBranch,
|
||||
},
|
||||
};
|
||||
},
|
||||
@@ -1934,101 +1932,97 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
},
|
||||
);
|
||||
|
||||
const checkoutBranch: GitVcsDriverShape["checkoutBranch"] = Effect.fn("checkoutBranch")(
|
||||
function* (input) {
|
||||
const [localInputExists, remoteExists] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitVcsDriver.checkoutBranch.localInputExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
executeGit(
|
||||
"GitVcsDriver.checkoutBranch.remoteExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const switchRef: GitVcsDriverShape["switchRef"] = Effect.fn("switchRef")(function* (input) {
|
||||
const [localInputExists, remoteExists] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitVcsDriver.switchRef.localInputExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${input.refName}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
executeGit(
|
||||
"GitVcsDriver.switchRef.remoteExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/${input.refName}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const localTrackingBranch = remoteExists
|
||||
const localTrackingBranch = remoteExists
|
||||
? yield* executeGit(
|
||||
"GitVcsDriver.switchRef.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.refName)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
|
||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.refName);
|
||||
const localTrackedBranchTargetExists =
|
||||
remoteExists && localTrackedBranchCandidate
|
||||
? yield* executeGit(
|
||||
"GitVcsDriver.checkoutBranch.localTrackingBranch",
|
||||
"GitVcsDriver.switchRef.localTrackedBranchTargetExists",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
).pipe(Effect.map((result) => result.code === 0))
|
||||
: false;
|
||||
|
||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
||||
const localTrackedBranchTargetExists =
|
||||
remoteExists && localTrackedBranchCandidate
|
||||
? yield* executeGit(
|
||||
"GitVcsDriver.checkoutBranch.localTrackedBranchTargetExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0))
|
||||
: false;
|
||||
const checkoutArgs = localInputExists
|
||||
? ["checkout", input.refName]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
? ["checkout", input.refName]
|
||||
: remoteExists && !localTrackingBranch
|
||||
? ["checkout", "--track", input.refName]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.refName];
|
||||
|
||||
const checkoutArgs = localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
yield* executeGit("GitVcsDriver.switchRef.checkout", input.cwd, checkoutArgs, {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
|
||||
yield* executeGit("GitVcsDriver.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [
|
||||
"branch",
|
||||
"--show-current",
|
||||
]).pipe(Effect.map((stdout) => stdout.trim() || null));
|
||||
|
||||
const branch = yield* runGitStdout("GitVcsDriver.checkoutBranch.currentBranch", input.cwd, [
|
||||
"branch",
|
||||
"--show-current",
|
||||
]).pipe(Effect.map((stdout) => stdout.trim() || null));
|
||||
return { refName };
|
||||
});
|
||||
|
||||
return { branch };
|
||||
},
|
||||
);
|
||||
const createRef: GitVcsDriverShape["createRef"] = Effect.fn("createRef")(function* (input) {
|
||||
yield* executeGit("GitVcsDriver.createRef", input.cwd, ["branch", input.refName], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
});
|
||||
if (input.switchRef) {
|
||||
yield* switchRef({ cwd: input.cwd, refName: input.refName });
|
||||
}
|
||||
|
||||
const createBranch: GitVcsDriverShape["createBranch"] = Effect.fn("createBranch")(
|
||||
function* (input) {
|
||||
yield* executeGit("GitVcsDriver.createBranch", input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
});
|
||||
if (input.checkout) {
|
||||
yield* checkoutBranch({ cwd: input.cwd, branch: input.branch });
|
||||
}
|
||||
|
||||
return { branch: input.branch };
|
||||
},
|
||||
);
|
||||
return { refName: input.refName };
|
||||
});
|
||||
|
||||
const initRepo: GitVcsDriverShape["initRepo"] = (input) =>
|
||||
executeGit("GitVcsDriver.initRepo", input.cwd, ["init"], {
|
||||
@@ -2062,7 +2056,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
pullCurrentBranch,
|
||||
readRangeContext,
|
||||
readConfigValue,
|
||||
listBranches,
|
||||
listRefs,
|
||||
createWorktree,
|
||||
fetchPullRequestBranch,
|
||||
ensureRemote,
|
||||
@@ -2070,8 +2064,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
setBranchUpstream,
|
||||
removeWorktree,
|
||||
renameBranch,
|
||||
createBranch,
|
||||
checkoutBranch,
|
||||
createRef,
|
||||
switchRef,
|
||||
initRepo,
|
||||
listLocalBranchNames,
|
||||
} satisfies GitVcsDriverShape;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
|
||||
import type {
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe } from "vitest";
|
||||
|
||||
@@ -14,35 +14,35 @@ import {
|
||||
} from "./VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService, type GitWorkflowServiceShape } from "../git/GitWorkflowService.ts";
|
||||
|
||||
const baseLocalStatus: GitStatusLocalResult = {
|
||||
const baseLocalStatus: VcsStatusLocalResult = {
|
||||
isRepo: true,
|
||||
hostingProvider: {
|
||||
kind: "github",
|
||||
name: "GitHub",
|
||||
baseUrl: "https://github.com",
|
||||
},
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/status-broadcast",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/status-broadcast",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
};
|
||||
|
||||
const baseRemoteStatus: GitStatusRemoteResult = {
|
||||
const baseRemoteStatus: VcsStatusRemoteResult = {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const baseStatus: GitStatusResult = {
|
||||
const baseStatus: VcsStatusResult = {
|
||||
...baseLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
};
|
||||
|
||||
function makeTestLayer(state: {
|
||||
currentLocalStatus: GitStatusLocalResult;
|
||||
currentRemoteStatus: GitStatusRemoteResult | null;
|
||||
currentLocalStatus: VcsStatusLocalResult;
|
||||
currentRemoteStatus: VcsStatusRemoteResult | null;
|
||||
localStatusCalls: number;
|
||||
remoteStatusCalls: number;
|
||||
localInvalidationCalls: number;
|
||||
@@ -116,7 +116,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
branch: "feature/updated-status",
|
||||
refName: "feature/updated-status",
|
||||
};
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
@@ -157,7 +157,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
branch: "feature/local-only-refresh",
|
||||
refName: "feature/local-only-refresh",
|
||||
hasWorkingTreeChanges: true,
|
||||
};
|
||||
|
||||
@@ -189,8 +189,8 @@ describe("VcsStatusBroadcaster", () => {
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
|
||||
if (event._tag === "snapshot") {
|
||||
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
|
||||
@@ -209,11 +209,11 @@ describe("VcsStatusBroadcaster", () => {
|
||||
_tag: "snapshot",
|
||||
local: baseLocalStatus,
|
||||
remote: null,
|
||||
} satisfies GitStatusStreamEvent);
|
||||
} satisfies VcsStatusStreamEvent);
|
||||
assert.deepStrictEqual(remoteUpdated, {
|
||||
_tag: "remoteUpdated",
|
||||
remote: baseRemoteStatus,
|
||||
} satisfies GitStatusStreamEvent);
|
||||
} satisfies VcsStatusStreamEvent);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
@@ -245,7 +245,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
|
||||
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
|
||||
Effect.onInterrupt(() =>
|
||||
remoteInterruptedDeferred
|
||||
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||
@@ -271,8 +271,8 @@ describe("VcsStatusBroadcaster", () => {
|
||||
remoteStartedDeferred = remoteStarted;
|
||||
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const firstScope = yield* Scope.make();
|
||||
const secondScope = yield* Scope.make();
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
|
||||
|
||||
@@ -12,11 +12,11 @@ import {
|
||||
} from "effect";
|
||||
import type {
|
||||
GitManagerServiceError,
|
||||
GitStatusInput,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
VcsStatusInput,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
@@ -27,7 +27,7 @@ const VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
interface VcsStatusChange {
|
||||
readonly cwd: string;
|
||||
readonly event: GitStatusStreamEvent;
|
||||
readonly event: VcsStatusStreamEvent;
|
||||
}
|
||||
|
||||
interface CachedValue<T> {
|
||||
@@ -36,8 +36,8 @@ interface CachedValue<T> {
|
||||
}
|
||||
|
||||
interface CachedVcsStatus {
|
||||
readonly local: CachedValue<GitStatusLocalResult> | null;
|
||||
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
|
||||
readonly local: CachedValue<VcsStatusLocalResult> | null;
|
||||
readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;
|
||||
}
|
||||
|
||||
interface ActiveRemotePoller {
|
||||
@@ -47,15 +47,15 @@ interface ActiveRemotePoller {
|
||||
|
||||
export interface VcsStatusBroadcasterShape {
|
||||
readonly getStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly refreshLocalStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly streamStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
|
||||
input: VcsStatusInput,
|
||||
) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class VcsStatusBroadcaster extends Context.Service<
|
||||
@@ -88,11 +88,11 @@ export const layer = Layer.effect(
|
||||
});
|
||||
|
||||
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
|
||||
function* (cwd: string, local: GitStatusLocalResult, options?: { publish?: boolean }) {
|
||||
function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
|
||||
const nextLocal = {
|
||||
fingerprint: fingerprintStatusPart(local),
|
||||
value: local,
|
||||
} satisfies CachedValue<GitStatusLocalResult>;
|
||||
} satisfies CachedValue<VcsStatusLocalResult>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
@@ -120,13 +120,13 @@ export const layer = Layer.effect(
|
||||
const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
|
||||
function* (
|
||||
cwd: string,
|
||||
remote: GitStatusRemoteResult | null,
|
||||
remote: VcsStatusRemoteResult | null,
|
||||
options?: { publish?: boolean },
|
||||
) {
|
||||
const nextRemote = {
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
} satisfies CachedValue<GitStatusRemoteResult | null>;
|
||||
} satisfies CachedValue<VcsStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
|
||||
+11
-11
@@ -453,8 +453,8 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
if (bootstrap?.prepareWorktree) {
|
||||
const worktree = yield* gitWorkflow.createWorktree({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
branch: bootstrap.prepareWorktree.baseBranch,
|
||||
newBranch: bootstrap.prepareWorktree.branch,
|
||||
refName: bootstrap.prepareWorktree.baseBranch,
|
||||
newRefName: bootstrap.prepareWorktree.branch,
|
||||
path: null,
|
||||
});
|
||||
targetWorktreePath = worktree.worktree.path;
|
||||
@@ -462,7 +462,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("bootstrap-thread-meta-update"),
|
||||
threadId: command.threadId,
|
||||
branch: worktree.worktree.branch,
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath: targetWorktreePath,
|
||||
});
|
||||
yield* refreshGitStatus(targetWorktreePath);
|
||||
@@ -896,8 +896,8 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.vcsListBranches]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.vcsListBranches, gitWorkflow.listBranches(input), {
|
||||
[WS_METHODS.vcsListRefs]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.vcsListRefs, gitWorkflow.listRefs(input), {
|
||||
"rpc.aggregate": "vcs",
|
||||
}),
|
||||
[WS_METHODS.vcsCreateWorktree]: (input) =>
|
||||
@@ -912,16 +912,16 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.vcsCreateBranch]: (input) =>
|
||||
[WS_METHODS.vcsCreateRef]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsCreateBranch,
|
||||
gitWorkflow.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
WS_METHODS.vcsCreateRef,
|
||||
gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.vcsCheckout]: (input) =>
|
||||
[WS_METHODS.vcsSwitchRef]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsCheckout,
|
||||
gitWorkflow.checkoutBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
WS_METHODS.vcsSwitchRef,
|
||||
gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.vcsInit]: (input) =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentId, type GitBranch } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type VcsRef } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
@@ -28,7 +28,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
).toBe("local");
|
||||
});
|
||||
|
||||
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
|
||||
it("keeps new-worktree mode when selecting a base ref before worktree creation", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: null,
|
||||
@@ -38,7 +38,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
|
||||
it("uses worktree mode when selecting a ref already attached to a worktree", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
@@ -50,7 +50,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
});
|
||||
|
||||
describe("resolveBranchToolbarValue", () => {
|
||||
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
|
||||
it("defaults new-worktree mode to current git ref when no explicit base ref is set", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
@@ -61,7 +61,7 @@ describe("resolveBranchToolbarValue", () => {
|
||||
).toBe("main");
|
||||
});
|
||||
|
||||
it("keeps an explicitly selected worktree base branch", () => {
|
||||
it("keeps an explicitly selected worktree base ref", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
@@ -72,7 +72,7 @@ describe("resolveBranchToolbarValue", () => {
|
||||
).toBe("feature/base");
|
||||
});
|
||||
|
||||
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
|
||||
it("shows the actual checked-out ref when not selecting a new worktree base", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "local",
|
||||
@@ -120,7 +120,7 @@ describe("resolveEnvironmentOptionLabel", () => {
|
||||
});
|
||||
|
||||
describe("resolveEffectiveEnvMode", () => {
|
||||
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
|
||||
it("treats draft threads already attached to a worktree as current-switchRef mode", () => {
|
||||
expect(
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
@@ -143,24 +143,24 @@ describe("resolveEffectiveEnvMode", () => {
|
||||
|
||||
describe("resolveEnvModeLabel", () => {
|
||||
it("uses explicit workspace labels", () => {
|
||||
expect(resolveEnvModeLabel("local")).toBe("Current checkout");
|
||||
expect(resolveEnvModeLabel("local")).toBe("Current switchRef");
|
||||
expect(resolveEnvModeLabel("worktree")).toBe("New worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCurrentWorkspaceLabel", () => {
|
||||
it("describes the main repo checkout when no worktree path is active", () => {
|
||||
expect(resolveCurrentWorkspaceLabel(null)).toBe("Current checkout");
|
||||
it("describes the main repo switchRef when no worktree path is active", () => {
|
||||
expect(resolveCurrentWorkspaceLabel(null)).toBe("Current switchRef");
|
||||
});
|
||||
|
||||
it("describes the active checkout as a worktree when one is attached", () => {
|
||||
it("describes the active switchRef as a worktree when one is attached", () => {
|
||||
expect(resolveCurrentWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Current worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLockedWorkspaceLabel", () => {
|
||||
it("uses a shorter label for the main repo checkout", () => {
|
||||
expect(resolveLockedWorkspaceLabel(null)).toBe("Local checkout");
|
||||
it("uses a shorter label for the main repo switchRef", () => {
|
||||
expect(resolveLockedWorkspaceLabel(null)).toBe("Local switchRef");
|
||||
});
|
||||
|
||||
it("uses a shorter label for an attached worktree", () => {
|
||||
@@ -186,8 +186,8 @@ describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
});
|
||||
|
||||
describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
it("hides remote refs when the matching local branch exists", () => {
|
||||
const input: GitBranch[] = [
|
||||
it("hides remote refs when the matching local ref exists", () => {
|
||||
const input: VcsRef[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
@@ -212,14 +212,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps all entries when no local match exists for a remote ref", () => {
|
||||
const input: GitBranch[] = [
|
||||
const input: VcsRef[] = [
|
||||
{
|
||||
name: "feature/local",
|
||||
current: false,
|
||||
@@ -236,14 +236,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
"feature/local",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps non-origin remote refs visible even when a matching local branch exists", () => {
|
||||
const input: GitBranch[] = [
|
||||
it("keeps non-origin remote refs visible even when a matching local ref exists", () => {
|
||||
const input: VcsRef[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
@@ -260,14 +260,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
"feature/demo",
|
||||
"my-org/upstream/feature/demo",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps non-origin remote refs visible when git tracks with first-slash local naming", () => {
|
||||
const input: GitBranch[] = [
|
||||
const input: VcsRef[] = [
|
||||
{
|
||||
name: "upstream/feature",
|
||||
current: false,
|
||||
@@ -284,7 +284,7 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
"upstream/feature",
|
||||
"my-org/upstream/feature",
|
||||
]);
|
||||
@@ -292,12 +292,12 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
});
|
||||
|
||||
describe("resolveBranchSelectionTarget", () => {
|
||||
it("reuses an existing secondary worktree for the selected branch", () => {
|
||||
it("reuses an existing secondary worktree for the selected ref", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
branch: {
|
||||
refName: {
|
||||
isDefault: false,
|
||||
worktreePath: "/repo/.t3/worktrees/feature-b",
|
||||
},
|
||||
@@ -309,12 +309,12 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("switches back to the main repo when the branch already lives there", () => {
|
||||
it("switches back to the main repo when the ref already lives there", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
branch: {
|
||||
refName: {
|
||||
isDefault: true,
|
||||
worktreePath: "/repo",
|
||||
},
|
||||
@@ -326,12 +326,12 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("checks out the default branch in the main repo when leaving a secondary worktree", () => {
|
||||
it("checks out the default ref in the main repo when leaving a secondary worktree", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
branch: {
|
||||
refName: {
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
@@ -343,12 +343,12 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps checkout in the current worktree for non-default branches", () => {
|
||||
it("keeps switchRef in the current worktree for non-default refs", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
branch: {
|
||||
refName: {
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
@@ -362,18 +362,18 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
|
||||
describe("shouldIncludeBranchPickerItem", () => {
|
||||
it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => {
|
||||
it("keeps the synthetic switchRef PR item visible for gh pr switchRef input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__checkout_pull_request__:1359",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
normalizedQuery: "gh pr switchRef 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr switchRef 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the synthetic create-branch item visible for arbitrary branch input", () => {
|
||||
it("keeps the synthetic create-ref item visible for arbitrary ref input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__create_new_branch__:feature/demo",
|
||||
@@ -384,12 +384,12 @@ describe("shouldIncludeBranchPickerItem", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("still filters ordinary branch items by query text", () => {
|
||||
it("still filters ordinary ref items by query text", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "main",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
normalizedQuery: "gh pr switchRef 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr switchRef 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { EnvironmentId, GitBranch, ProjectId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
export {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
@@ -43,7 +43,7 @@ export function resolveEnvironmentOptionLabel(input: {
|
||||
}
|
||||
|
||||
export function resolveEnvModeLabel(mode: EnvMode): string {
|
||||
return mode === "worktree" ? "New worktree" : "Current checkout";
|
||||
return mode === "worktree" ? "New worktree" : "Current switchRef";
|
||||
}
|
||||
|
||||
export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string {
|
||||
@@ -51,7 +51,7 @@ export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null):
|
||||
}
|
||||
|
||||
export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
return activeWorktreePath ? "Worktree" : "Local switchRef";
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
@@ -100,24 +100,24 @@ export function resolveBranchToolbarValue(input: {
|
||||
export function resolveBranchSelectionTarget(input: {
|
||||
activeProjectCwd: string;
|
||||
activeWorktreePath: string | null;
|
||||
branch: Pick<GitBranch, "isDefault" | "worktreePath">;
|
||||
refName: Pick<VcsRef, "isDefault" | "worktreePath">;
|
||||
}): {
|
||||
checkoutCwd: string;
|
||||
nextWorktreePath: string | null;
|
||||
reuseExistingWorktree: boolean;
|
||||
} {
|
||||
const { activeProjectCwd, activeWorktreePath, branch } = input;
|
||||
const { activeProjectCwd, activeWorktreePath, refName } = input;
|
||||
|
||||
if (branch.worktreePath) {
|
||||
if (refName.worktreePath) {
|
||||
return {
|
||||
checkoutCwd: branch.worktreePath,
|
||||
nextWorktreePath: branch.worktreePath === activeProjectCwd ? null : branch.worktreePath,
|
||||
checkoutCwd: refName.worktreePath,
|
||||
nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
|
||||
reuseExistingWorktree: true,
|
||||
};
|
||||
}
|
||||
|
||||
const nextWorktreePath =
|
||||
activeWorktreePath !== null && branch.isDefault ? null : activeWorktreePath;
|
||||
activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
|
||||
|
||||
return {
|
||||
checkoutCwd: nextWorktreePath ?? activeProjectCwd,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
@@ -53,7 +53,7 @@ interface BranchToolbarBranchSelectorProps {
|
||||
envLocked: boolean;
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -69,7 +69,7 @@ function getBranchTriggerLabel(input: {
|
||||
}): string {
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return "Select branch";
|
||||
return "Select ref";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
return `From ${resolvedActiveBranch}`;
|
||||
@@ -193,7 +193,7 @@ export function BranchToolbarBranchSelector({
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Git branch queries
|
||||
// Git ref queries
|
||||
// ---------------------------------------------------------------------------
|
||||
const queryClient = useQueryClient();
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
@@ -224,22 +224,22 @@ export function BranchToolbarBranchSelector({
|
||||
query: deferredTrimmedBranchQuery,
|
||||
}),
|
||||
);
|
||||
const branches = useMemo(
|
||||
() => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [],
|
||||
const refs = useMemo(
|
||||
() => branchesSearchData?.pages.flatMap((page) => page.refs) ?? [],
|
||||
[branchesSearchData?.pages],
|
||||
);
|
||||
const currentGitBranch =
|
||||
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
|
||||
branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
|
||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||
envMode: effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
currentGitBranch,
|
||||
});
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
|
||||
const branchByName = useMemo(
|
||||
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
|
||||
[branches],
|
||||
() => new Map(refs.map((refName) => [refName.name, refName] as const)),
|
||||
[refs],
|
||||
);
|
||||
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
|
||||
const prReference = parsePullRequestReference(trimmedBranchQuery);
|
||||
@@ -289,11 +289,11 @@ export function BranchToolbarBranchSelector({
|
||||
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
||||
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
|
||||
const branchStatusText = isBranchesSearchPending
|
||||
? "Loading branches..."
|
||||
? "Loading refs..."
|
||||
: isFetchingNextPage
|
||||
? "Loading more branches..."
|
||||
? "Loading more refs..."
|
||||
: hasNextPage
|
||||
? `Showing ${branches.length} of ${totalBranchCount} branches`
|
||||
? `Showing ${refs.length} of ${totalBranchCount} refs`
|
||||
: null;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -303,17 +303,17 @@ export function BranchToolbarBranchSelector({
|
||||
startBranchActionTransition(async () => {
|
||||
await action().catch(() => undefined);
|
||||
await queryClient
|
||||
.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, branchCwd) })
|
||||
.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, branchCwd) })
|
||||
.catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const selectBranch = (refName: VcsRef) => {
|
||||
const api = readEnvironmentApi(environmentId);
|
||||
if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
|
||||
|
||||
if (isSelectingWorktreeBase) {
|
||||
setThreadBranch(branch.name, null);
|
||||
setThreadBranch(refName.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
@@ -322,19 +322,19 @@ export function BranchToolbarBranchSelector({
|
||||
const selectionTarget = resolveBranchSelectionTarget({
|
||||
activeProjectCwd,
|
||||
activeWorktreePath,
|
||||
branch,
|
||||
refName,
|
||||
});
|
||||
|
||||
if (selectionTarget.reuseExistingWorktree) {
|
||||
setThreadBranch(branch.name, selectionTarget.nextWorktreePath);
|
||||
setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedBranchName = branch.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
const selectedBranchName = refName.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(refName.name)
|
||||
: refName.name;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
@@ -343,12 +343,12 @@ export function BranchToolbarBranchSelector({
|
||||
const previousBranch = resolvedActiveBranch;
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
try {
|
||||
const checkoutResult = await api.vcs.checkout({
|
||||
const checkoutResult = await api.vcs.switchRef({
|
||||
cwd: selectionTarget.checkoutCwd,
|
||||
branch: branch.name,
|
||||
refName: refName.name,
|
||||
});
|
||||
const nextBranchName = branch.isRemote
|
||||
? (checkoutResult.branch ?? selectedBranchName)
|
||||
const nextBranchName = refName.isRemote
|
||||
? (checkoutResult.refName ?? selectedBranchName)
|
||||
: selectedBranchName;
|
||||
setOptimisticBranch(nextBranchName);
|
||||
setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
|
||||
@@ -357,7 +357,7 @@ export function BranchToolbarBranchSelector({
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
title: "Failed to switch ref.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
@@ -365,7 +365,7 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const createRef = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readEnvironmentApi(environmentId);
|
||||
if (!api || !branchCwd || !name || isBranchActionPending) return;
|
||||
@@ -377,19 +377,19 @@ export function BranchToolbarBranchSelector({
|
||||
const previousBranch = resolvedActiveBranch;
|
||||
setOptimisticBranch(name);
|
||||
try {
|
||||
const createBranchResult = await api.vcs.createBranch({
|
||||
const createBranchResult = await api.vcs.createRef({
|
||||
cwd: branchCwd,
|
||||
branch: name,
|
||||
checkout: true,
|
||||
refName: name,
|
||||
switchRef: true,
|
||||
});
|
||||
setOptimisticBranch(createBranchResult.branch);
|
||||
setThreadBranch(createBranchResult.branch, activeWorktreePath);
|
||||
setOptimisticBranch(createBranchResult.refName);
|
||||
setThreadBranch(createBranchResult.refName, activeWorktreePath);
|
||||
} catch (error) {
|
||||
setOptimisticBranch(previousBranch);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to create and checkout branch.",
|
||||
title: "Failed to create and switch ref.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
@@ -420,7 +420,7 @@ export function BranchToolbarBranchSelector({
|
||||
return;
|
||||
}
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: gitQueryKeys.branches(environmentId, branchCwd),
|
||||
queryKey: gitQueryKeys.refs(environmentId, branchCwd),
|
||||
});
|
||||
},
|
||||
[branchCwd, environmentId, queryClient],
|
||||
@@ -482,7 +482,7 @@ export function BranchToolbarBranchSelector({
|
||||
useEffect(() => {
|
||||
if (shouldVirtualizeBranchList) return;
|
||||
maybeFetchNextBranchPage();
|
||||
}, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
|
||||
}, [refs.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
@@ -522,25 +522,25 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
onClick={() => createRef(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
<span className="truncate">Create new ref "{trimmedBranchQuery}"</span>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
const branch = branchByName.get(itemValue);
|
||||
if (!branch) return null;
|
||||
const refName = branchByName.get(itemValue);
|
||||
if (!refName) return null;
|
||||
|
||||
const hasSecondaryWorktree =
|
||||
branch.worktreePath && activeProjectCwd && branch.worktreePath !== activeProjectCwd;
|
||||
const badge = branch.current
|
||||
refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
|
||||
const badge = refName.current
|
||||
? "current"
|
||||
: hasSecondaryWorktree
|
||||
? "worktree"
|
||||
: branch.isRemote
|
||||
: refName.isRemote
|
||||
? "remote"
|
||||
: branch.isDefault
|
||||
: refName.isDefault
|
||||
? "default"
|
||||
: null;
|
||||
return (
|
||||
@@ -549,7 +549,7 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
onClick={() => selectBranch(branch)}
|
||||
onClick={() => selectBranch(refName)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
@@ -581,7 +581,7 @@ export function BranchToolbarBranchSelector({
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className={cn("min-w-0 text-muted-foreground/70 hover:text-foreground/80", className)}
|
||||
disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending}
|
||||
disabled={(isBranchesSearchPending && refs.length === 0) || isBranchActionPending}
|
||||
>
|
||||
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon className="shrink-0" />
|
||||
@@ -591,14 +591,14 @@ export function BranchToolbarBranchSelector({
|
||||
<ComboboxInput
|
||||
className="[&_input]:font-sans rounded-md"
|
||||
inputClassName="ring-0"
|
||||
placeholder="Search branches..."
|
||||
placeholder="Search refs..."
|
||||
showTrigger={false}
|
||||
size="sm"
|
||||
value={branchQuery}
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
<ComboboxEmpty>No refs found.</ComboboxEmpty>
|
||||
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<ComboboxListVirtualized>
|
||||
|
||||
@@ -952,7 +952,7 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.vcsListBranches) {
|
||||
if (tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
@@ -2299,7 +2299,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
Array.from(document.querySelectorAll("span")).find(
|
||||
(element) => element.textContent?.trim() === "Checkout Pull Request",
|
||||
) as HTMLSpanElement | null,
|
||||
"Unable to find checkout pull request option.",
|
||||
"Unable to find switchRef pull request option.",
|
||||
);
|
||||
checkoutItem.click();
|
||||
|
||||
@@ -2573,7 +2573,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListBranches) {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
@@ -2599,7 +2599,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
(await waitForButtonByText("Current switchRef")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
@@ -2666,7 +2666,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListBranches) {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
@@ -2698,7 +2698,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
(await waitForButtonByText("Current switchRef")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
await page.getByText("From main", { exact: true }).click();
|
||||
await page.getByText("release/next", { exact: true }).click();
|
||||
@@ -2762,7 +2762,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: snapshotWithTwoThreads,
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListBranches) {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
@@ -2794,7 +2794,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
(await waitForButtonByText("Current switchRef")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
await page.getByText("From main", { exact: true }).click();
|
||||
await page.getByText("release/next", { exact: true }).click();
|
||||
@@ -2822,13 +2822,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(findButtonByText("Current checkout")).toBeTruthy();
|
||||
expect(findButtonByText("Current switchRef")).toBeTruthy();
|
||||
expect(findButtonByText("From release/next")).toBeNull();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
(await waitForButtonByText("Current switchRef")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
@@ -3022,7 +3022,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
initialPath: `/draft/${activeDraftId}`,
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListBranches) {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
@@ -3147,7 +3147,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
initialPath: `/draft/${draftId}`,
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListBranches) {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitStatusResult } from "@t3tools/contracts";
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "vitest";
|
||||
import {
|
||||
buildGitActionProgressStages,
|
||||
@@ -11,12 +11,12 @@ import {
|
||||
resolveThreadBranchUpdate,
|
||||
} from "./GitActionsControl.logic";
|
||||
|
||||
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/test",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/test",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -31,7 +31,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
||||
};
|
||||
}
|
||||
|
||||
describe("when: branch is clean and has an open PR", () => {
|
||||
describe("when: ref is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
@@ -39,8 +39,8 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
number: 10,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/10",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -56,8 +56,8 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
number: 11,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/11",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -150,7 +150,7 @@ describe("when: git status is unavailable", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
describe("when: ref is clean, ahead, and has an open PR", () => {
|
||||
it("resolveQuickAction prefers push", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
@@ -159,8 +159,8 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
number: 13,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -177,8 +177,8 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
number: 12,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -212,7 +212,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
describe("when: ref is clean, ahead, and has no open PR", () => {
|
||||
it("resolveQuickAction pushes and creates a PR", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepInclude(quick, {
|
||||
@@ -253,7 +253,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||
describe("when: ref is clean, up to date, and has no open PR", () => {
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||
@@ -293,7 +293,7 @@ describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: branch is behind upstream", () => {
|
||||
describe("when: ref is behind upstream", () => {
|
||||
it("resolveQuickAction returns pull", () => {
|
||||
const quick = resolveQuickAction(status({ behindCount: 2 }), false);
|
||||
assert.deepInclude(quick, { kind: "run_pull", label: "Pull", disabled: false });
|
||||
@@ -330,11 +330,11 @@ describe("when: branch is behind upstream", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: branch has diverged from upstream", () => {
|
||||
describe("when: ref has diverged from upstream", () => {
|
||||
it("resolveQuickAction returns a disabled sync hint", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, behindCount: 1 }), false);
|
||||
assert.deepEqual(quick, {
|
||||
label: "Sync branch",
|
||||
label: "Sync ref",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "Branch has diverged from upstream. Rebase/merge first.",
|
||||
@@ -375,8 +375,8 @@ describe("when: working tree has local changes", () => {
|
||||
number: 16,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/16",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -420,10 +420,10 @@ describe("when: working tree has local changes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: on default branch without open PR", () => {
|
||||
describe("when: on default ref without open PR", () => {
|
||||
it("resolveQuickAction returns commit and push when local changes exist", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ branch: "main", hasWorkingTreeChanges: true }),
|
||||
status({ refName: "main", hasWorkingTreeChanges: true }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -435,9 +435,9 @@ describe("when: on default branch without open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||
it("resolveQuickAction returns push when ref is ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||
status({ refName: "main", aheadCount: 2, pr: null }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -450,7 +450,7 @@ describe("when: on default branch without open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: working tree has local changes and branch is behind upstream", () => {
|
||||
describe("when: working tree has local changes and ref is behind upstream", () => {
|
||||
it("resolveQuickAction still prefers commit, push, and create PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasWorkingTreeChanges: true, behindCount: 1 }),
|
||||
@@ -497,14 +497,14 @@ describe("when: working tree has local changes and branch is behind upstream", (
|
||||
describe("when: HEAD is detached and there are no local changes", () => {
|
||||
it("resolveQuickAction shows detached head hint", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ branch: null, hasWorkingTreeChanges: false, hasUpstream: false }),
|
||||
status({ refName: null, hasWorkingTreeChanges: false, hasUpstream: false }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||
});
|
||||
|
||||
it("buildMenuItems keeps commit, push, and PR disabled", () => {
|
||||
const items = buildMenuItems(status({ branch: null, hasWorkingTreeChanges: false }), false);
|
||||
const items = buildMenuItems(status({ refName: null, hasWorkingTreeChanges: false }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -534,7 +534,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
describe("when: ref has no upstream configured", () => {
|
||||
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
@@ -557,8 +557,8 @@ describe("when: branch has no upstream configured", () => {
|
||||
number: 14,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -580,8 +580,8 @@ describe("when: branch has no upstream configured", () => {
|
||||
number: 15,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -725,10 +725,10 @@ describe("when: branch has no upstream configured", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
|
||||
it("resolveQuickAction is disabled on default ref when no upstream exists and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
branch: "main",
|
||||
refName: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
pr: null,
|
||||
@@ -744,10 +744,10 @@ describe("when: branch has no upstream configured", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
|
||||
it("resolveQuickAction uses push-only on default ref when no upstream exists and commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
branch: "main",
|
||||
refName: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
pr: null,
|
||||
@@ -763,7 +763,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("buildMenuItems still disables push and create PR when branch is behind", () => {
|
||||
it("buildMenuItems still disables push and create PR when ref is behind", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
@@ -803,7 +803,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
});
|
||||
|
||||
describe("requiresDefaultBranchConfirmation", () => {
|
||||
it("requires confirmation for push actions on default branch", () => {
|
||||
it("requires confirmation for push actions on default ref", () => {
|
||||
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("push", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("create_pr", true));
|
||||
@@ -823,9 +823,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push to default branch?",
|
||||
title: "Push to default ref?",
|
||||
description:
|
||||
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
'This action will push local commits on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
continueLabel: "Push to main",
|
||||
});
|
||||
});
|
||||
@@ -838,9 +838,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push & create PR from default branch?",
|
||||
title: "Push & create PR from default ref?",
|
||||
description:
|
||||
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch 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",
|
||||
});
|
||||
});
|
||||
@@ -853,9 +853,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
title: "Commit, push & create PR from default ref?",
|
||||
description:
|
||||
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch 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",
|
||||
});
|
||||
});
|
||||
@@ -944,7 +944,7 @@ describe("resolveThreadBranchUpdate", () => {
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
subject: "feat: add branch sync",
|
||||
subject: "feat: add ref sync",
|
||||
},
|
||||
push: { status: "pushed", branch: "feature/fix-toast-copy" },
|
||||
pr: { status: "skipped_not_requested" },
|
||||
@@ -968,7 +968,7 @@ describe("resolveThreadBranchUpdate", () => {
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
subject: "feat: add branch sync",
|
||||
subject: "feat: add ref sync",
|
||||
},
|
||||
push: { status: "pushed", branch: "feature/fix-toast-copy" },
|
||||
pr: { status: "skipped_not_requested" },
|
||||
@@ -985,8 +985,8 @@ describe("resolveThreadBranchUpdate", () => {
|
||||
describe("resolveLiveThreadBranchUpdate", () => {
|
||||
it("returns a branch update when live git status differs from stored thread metadata", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "feature/old-branch",
|
||||
gitStatus: status({ branch: "effect-atom" }),
|
||||
threadBranch: "feature/old-ref",
|
||||
gitStatus: status({ refName: "effect-atom" }),
|
||||
});
|
||||
|
||||
assert.deepEqual(update, {
|
||||
@@ -996,35 +996,35 @@ describe("resolveLiveThreadBranchUpdate", () => {
|
||||
|
||||
it("returns null when live git status is unavailable", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "feature/old-branch",
|
||||
threadBranch: "feature/old-ref",
|
||||
gitStatus: null,
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("returns null when the stored thread branch already matches git status", () => {
|
||||
it("returns null when the stored thread ref already matches git status", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "effect-atom",
|
||||
gitStatus: status({ branch: "effect-atom" }),
|
||||
gitStatus: status({ refName: "effect-atom" }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("returns null when git status is detached HEAD but the thread already has a branch", () => {
|
||||
it("returns null when git status is detached HEAD but the thread already has a ref", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "effect-atom",
|
||||
gitStatus: status({ branch: null }),
|
||||
gitStatus: status({ refName: null }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("does not regress a semantic thread branch back to a temporary worktree branch", () => {
|
||||
it("does not regress a semantic thread ref back to a temporary worktree ref", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "t3code/github-query-rate-limit",
|
||||
gitStatus: status({ branch: "t3code/bda76797" }),
|
||||
gitStatus: status({ refName: "t3code/bda76797" }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
@@ -1032,31 +1032,31 @@ describe("resolveLiveThreadBranchUpdate", () => {
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
it("uses semantic preferred branch names when available", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||
assert.equal(branch, "feature/fix-toast-copy");
|
||||
it("uses semantic preferred ref names when available", () => {
|
||||
const ref = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||
assert.equal(ref, "feature/fix-toast-copy");
|
||||
});
|
||||
|
||||
it("normalizes preferred names that already include a branch namespace", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
|
||||
assert.equal(branch, "feature/refine-toolbar-actions");
|
||||
it("normalizes preferred names that already include a ref namespace", () => {
|
||||
const ref = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
|
||||
assert.equal(ref, "feature/refine-toolbar-actions");
|
||||
});
|
||||
|
||||
it("increments suffix when the preferred branch name already exists", () => {
|
||||
const branch = resolveAutoFeatureBranchName(
|
||||
it("increments suffix when the preferred ref name already exists", () => {
|
||||
const ref = resolveAutoFeatureBranchName(
|
||||
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
|
||||
"fix toast copy",
|
||||
);
|
||||
assert.equal(branch, "feature/fix-toast-copy-3");
|
||||
assert.equal(ref, "feature/fix-toast-copy-3");
|
||||
});
|
||||
|
||||
it("treats existing branch names as case-insensitive for collision checks", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
|
||||
assert.equal(branch, "feature/ticket-1-2");
|
||||
it("treats existing ref names as case-insensitive for collision checks", () => {
|
||||
const ref = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
|
||||
assert.equal(ref, "feature/ticket-1-2");
|
||||
});
|
||||
|
||||
it("falls back to feature/update when no preferred name is provided", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main"]);
|
||||
assert.equal(branch, "feature/update");
|
||||
const ref = resolveAutoFeatureBranchName(["main"]);
|
||||
assert.equal(ref, "feature/update");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
@@ -46,7 +46,7 @@ export function buildGitActionProgressStages(input: {
|
||||
featureBranch?: boolean;
|
||||
shouldPushBeforePr?: boolean;
|
||||
}): string[] {
|
||||
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
|
||||
const branchStages = input.featureBranch ? ["Preparing feature ref..."] : [];
|
||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||
const prStages = [
|
||||
"Preparing PR...",
|
||||
@@ -77,17 +77,17 @@ export function buildGitActionProgressStages(input: {
|
||||
}
|
||||
|
||||
export function buildMenuItems(
|
||||
gitStatus: GitStatusResult | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
isBusy: boolean,
|
||||
hasOriginRemote = true,
|
||||
hasPrimaryRemote = true,
|
||||
): GitActionMenuItem[] {
|
||||
if (!gitStatus) return [];
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canPushWithoutUpstream = hasOriginRemote && !gitStatus.hasUpstream;
|
||||
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
const canPush =
|
||||
!isBusy &&
|
||||
@@ -143,10 +143,10 @@ export function buildMenuItems(
|
||||
}
|
||||
|
||||
export function resolveQuickAction(
|
||||
gitStatus: GitStatusResult | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
isBusy: boolean,
|
||||
isDefaultBranch = false,
|
||||
hasOriginRemote = true,
|
||||
isDefaultRef = false,
|
||||
hasPrimaryRemote = true,
|
||||
): GitQuickAction {
|
||||
if (isBusy) {
|
||||
return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." };
|
||||
@@ -161,7 +161,7 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
@@ -173,15 +173,15 @@ export function resolveQuickAction(
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "Create and checkout a branch before pushing or opening a PR.",
|
||||
hint: "Create and checkout a ref before pushing or opening a PR.",
|
||||
};
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
@@ -193,7 +193,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!hasOriginRemote) {
|
||||
if (!hasPrimaryRemote) {
|
||||
if (hasOpenPr && !isAhead) {
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
@@ -215,12 +215,12 @@ export function resolveQuickAction(
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: isDefaultBranch ? "commit_push" : "push",
|
||||
action: isDefaultRef ? "commit_push" : "push",
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -233,7 +233,7 @@ export function resolveQuickAction(
|
||||
|
||||
if (isDiverged) {
|
||||
return {
|
||||
label: "Sync branch",
|
||||
label: "Sync ref",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "Branch has diverged from upstream. Rebase/merge first.",
|
||||
@@ -249,12 +249,12 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (isAhead) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: isDefaultBranch ? "commit_push" : "push",
|
||||
action: isDefaultRef ? "commit_push" : "push",
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -279,9 +279,9 @@ export function resolveQuickAction(
|
||||
|
||||
export function requiresDefaultBranchConfirmation(
|
||||
action: GitStackedAction,
|
||||
isDefaultBranch: boolean,
|
||||
isDefaultRef: boolean,
|
||||
): boolean {
|
||||
if (!isDefaultBranch) return false;
|
||||
if (!isDefaultRef) return false;
|
||||
return (
|
||||
action === "push" ||
|
||||
action === "create_pr" ||
|
||||
@@ -296,18 +296,18 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
includesCommit: boolean;
|
||||
}): DefaultBranchActionDialogCopy {
|
||||
const branchLabel = input.branchName;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this ref or create a feature ref and run the same action there.`;
|
||||
|
||||
if (input.action === "push" || input.action === "commit_push") {
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit & push to default branch?",
|
||||
title: "Commit & push to default ref?",
|
||||
description: `This action will commit and push changes${suffix}`,
|
||||
continueLabel: `Commit & push to ${branchLabel}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push to default branch?",
|
||||
title: "Push to default ref?",
|
||||
description: `This action will push local commits${suffix}`,
|
||||
continueLabel: `Push to ${branchLabel}`,
|
||||
};
|
||||
@@ -315,13 +315,13 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
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 PR from default branch?",
|
||||
title: "Push & create PR from default ref?",
|
||||
description: `This action will push local commits and create a PR${suffix}`,
|
||||
continueLabel: "Push & create PR",
|
||||
};
|
||||
@@ -341,31 +341,31 @@ export function resolveThreadBranchUpdate(
|
||||
|
||||
export function resolveLiveThreadBranchUpdate(input: {
|
||||
threadBranch: string | null;
|
||||
gitStatus: GitStatusResult | null;
|
||||
gitStatus: VcsStatusResult | null;
|
||||
}): { branch: string | null } | null {
|
||||
if (!input.gitStatus) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (input.gitStatus.branch === null && input.threadBranch !== null) {
|
||||
if (input.gitStatus.refName === null && input.threadBranch !== null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (input.threadBranch === input.gitStatus.branch) {
|
||||
if (input.threadBranch === input.gitStatus.refName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
input.threadBranch !== null &&
|
||||
input.gitStatus.branch !== null &&
|
||||
input.gitStatus.refName !== null &&
|
||||
!isTemporaryWorktreeBranch(input.threadBranch) &&
|
||||
isTemporaryWorktreeBranch(input.gitStatus.branch)
|
||||
isTemporaryWorktreeBranch(input.gitStatus.refName)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
branch: input.gitStatus.branch,
|
||||
branch: input.gitStatus.refName,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import type {
|
||||
GitActionProgressEvent,
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
@@ -89,7 +89,7 @@ interface RunGitActionWithToastInput {
|
||||
commitMessage?: string;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
statusOverride?: VcsStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
filePaths?: string[];
|
||||
@@ -121,18 +121,18 @@ function getMenuActionDisabledReason({
|
||||
item,
|
||||
gitStatus,
|
||||
isBusy,
|
||||
hasOriginRemote,
|
||||
hasPrimaryRemote,
|
||||
}: {
|
||||
item: GitActionMenuItem;
|
||||
gitStatus: GitStatusResult | null;
|
||||
gitStatus: VcsStatusResult | null;
|
||||
isBusy: boolean;
|
||||
hasOriginRemote: boolean;
|
||||
hasPrimaryRemote: boolean;
|
||||
}): string | null {
|
||||
if (!item.disabled) return null;
|
||||
if (isBusy) return "Git action in progress.";
|
||||
if (!gitStatus) return "Git status is unavailable.";
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
@@ -147,7 +147,7 @@ function getMenuActionDisabledReason({
|
||||
|
||||
if (item.id === "push") {
|
||||
if (!hasBranch) {
|
||||
return "Detached HEAD: checkout a branch before pushing.";
|
||||
return "Detached HEAD: checkout a refName before pushing.";
|
||||
}
|
||||
if (hasChanges) {
|
||||
return "Commit or stash local changes before pushing.";
|
||||
@@ -155,7 +155,7 @@ function getMenuActionDisabledReason({
|
||||
if (isBehind) {
|
||||
return "Branch is behind upstream. Pull/rebase before pushing.";
|
||||
}
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
return 'Add an "origin" remote before pushing.';
|
||||
}
|
||||
if (!isAhead) {
|
||||
@@ -168,12 +168,12 @@ function getMenuActionDisabledReason({
|
||||
return "View PR is currently unavailable.";
|
||||
}
|
||||
if (!hasBranch) {
|
||||
return "Detached HEAD: checkout a branch before creating a PR.";
|
||||
return "Detached HEAD: checkout a refName before creating a PR.";
|
||||
}
|
||||
if (hasChanges) {
|
||||
return "Commit local changes before creating a PR.";
|
||||
}
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
return 'Add an "origin" remote before creating a PR.';
|
||||
}
|
||||
if (!isAhead) {
|
||||
@@ -324,7 +324,7 @@ export default function GitActionsControl({
|
||||
});
|
||||
// Default to true while loading so we don't flash init controls.
|
||||
const isRepo = gitStatus?.isRepo ?? true;
|
||||
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
|
||||
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
|
||||
const gitStatusForActions = gitStatus;
|
||||
|
||||
const allFiles = gitStatusForActions?.workingTree.files ?? [];
|
||||
@@ -382,18 +382,18 @@ export default function GitActionsControl({
|
||||
persistThreadBranchSync,
|
||||
]);
|
||||
|
||||
const isDefaultBranch = useMemo(() => {
|
||||
return gitStatusForActions?.isDefaultBranch ?? false;
|
||||
}, [gitStatusForActions?.isDefaultBranch]);
|
||||
const isDefaultRef = useMemo(() => {
|
||||
return gitStatusForActions?.isDefaultRef ?? false;
|
||||
}, [gitStatusForActions?.isDefaultRef]);
|
||||
|
||||
const gitActionMenuItems = useMemo(
|
||||
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
|
||||
[gitStatusForActions, hasOriginRemote, isGitActionRunning],
|
||||
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasPrimaryRemote),
|
||||
[gitStatusForActions, hasPrimaryRemote, isGitActionRunning],
|
||||
);
|
||||
const quickAction = useMemo(
|
||||
() =>
|
||||
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch, hasOriginRemote),
|
||||
[gitStatusForActions, hasOriginRemote, isDefaultBranch, isGitActionRunning],
|
||||
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultRef, hasPrimaryRemote),
|
||||
[gitStatusForActions, hasPrimaryRemote, isDefaultRef, isGitActionRunning],
|
||||
);
|
||||
const quickActionDisabledReason = quickAction.disabled
|
||||
? (quickAction.hint ?? "This action is currently unavailable.")
|
||||
@@ -497,8 +497,8 @@ export default function GitActionsControl({
|
||||
filePaths,
|
||||
}: RunGitActionWithToastInput) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
const actionIsDefaultBranch = featureBranch ? false : isDefaultBranch;
|
||||
const actionBranch = actionStatus?.refName ?? null;
|
||||
const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
|
||||
const actionCanCommit =
|
||||
action === "commit" || action === "commit_push" || action === "commit_push_pr";
|
||||
const includesCommit =
|
||||
@@ -775,8 +775,8 @@ export default function GitActionsControl({
|
||||
title: result.status === "pulled" ? "Pulled" : "Already up to date",
|
||||
description:
|
||||
result.status === "pulled"
|
||||
? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
|
||||
: `${result.branch} is already synchronized.`,
|
||||
? `Updated ${result.refName} from ${result.upstreamRef ?? "upstream"}`
|
||||
: `${result.refName} is already synchronized.`,
|
||||
data: threadToastData,
|
||||
}),
|
||||
error: (err) => ({
|
||||
@@ -934,7 +934,7 @@ export default function GitActionsControl({
|
||||
item,
|
||||
gitStatus: gitStatusForActions,
|
||||
isBusy: isGitActionRunning,
|
||||
hasOriginRemote,
|
||||
hasPrimaryRemote,
|
||||
});
|
||||
if (item.disabled && disabledReason) {
|
||||
return (
|
||||
@@ -969,13 +969,13 @@ export default function GitActionsControl({
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{gitStatusForActions?.branch === null && (
|
||||
{gitStatusForActions?.refName === null && (
|
||||
<p className="px-2 py-1.5 text-xs text-warning">
|
||||
Detached HEAD: create and checkout a branch to enable push and PR actions.
|
||||
Detached HEAD: create and checkout a refName to enable push and PR actions.
|
||||
</p>
|
||||
)}
|
||||
{gitStatusForActions &&
|
||||
gitStatusForActions.branch !== null &&
|
||||
gitStatusForActions.refName !== null &&
|
||||
!gitStatusForActions.hasWorkingTreeChanges &&
|
||||
gitStatusForActions.behindCount > 0 &&
|
||||
gitStatusForActions.aheadCount === 0 && (
|
||||
@@ -1013,10 +1013,12 @@ export default function GitActionsControl({
|
||||
<span className="text-muted-foreground">Branch</span>
|
||||
<span className="flex items-center justify-between gap-2">
|
||||
<span className="font-medium">
|
||||
{gitStatusForActions?.branch ?? "(detached HEAD)"}
|
||||
{gitStatusForActions?.refName ?? "(detached HEAD)"}
|
||||
</span>
|
||||
{isDefaultBranch && (
|
||||
<span className="text-right text-warning text-xs">Warning: default branch</span>
|
||||
{isDefaultRef && (
|
||||
<span className="text-right text-warning text-xs">
|
||||
Warning: default refName
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -1149,7 +1151,7 @@ export default function GitActionsControl({
|
||||
disabled={noneSelected}
|
||||
onClick={runDialogActionOnNewBranch}
|
||||
>
|
||||
Commit on new branch
|
||||
Commit on new refName
|
||||
</Button>
|
||||
<Button size="sm" disabled={noneSelected} onClick={runDialogAction}>
|
||||
Commit
|
||||
@@ -1169,7 +1171,7 @@ export default function GitActionsControl({
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
|
||||
{pendingDefaultBranchActionCopy?.title ?? "Run action on default refName?"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -256,7 +256,7 @@ function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.vcsListBranches) {
|
||||
if (tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopeProjectRef, scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { GitStatusResult } from "@t3tools/contracts";
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { CloudIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { usePrimaryEnvironmentId } from "../environments/primary";
|
||||
@@ -28,7 +28,7 @@ export interface TerminalStatusIndicator {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
export type ThreadPr = GitStatusResult["pr"];
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
if (!pr) return null;
|
||||
@@ -62,9 +62,9 @@ export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
|
||||
export function resolveThreadPr(
|
||||
threadBranch: string | null,
|
||||
gitStatus: GitStatusResult | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
): ThreadPr | null {
|
||||
if (threadBranch === null || gitStatus === null || gitStatus.branch !== threadBranch) {
|
||||
if (threadBranch === null || gitStatus === null || gitStatus.refName !== threadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,11 +27,11 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
|
||||
pull: rpcClient.vcs.pull,
|
||||
refreshStatus: rpcClient.vcs.refreshStatus,
|
||||
onStatus: (input, callback, options) => rpcClient.vcs.onStatus(input, callback, options),
|
||||
listBranches: rpcClient.vcs.listBranches,
|
||||
listRefs: rpcClient.vcs.listRefs,
|
||||
createWorktree: rpcClient.vcs.createWorktree,
|
||||
removeWorktree: rpcClient.vcs.removeWorktree,
|
||||
createBranch: rpcClient.vcs.createBranch,
|
||||
checkout: rpcClient.vcs.checkout,
|
||||
createRef: rpcClient.vcs.createRef,
|
||||
switchRef: rpcClient.vcs.switchRef,
|
||||
init: rpcClient.vcs.init,
|
||||
},
|
||||
git: {
|
||||
|
||||
@@ -11,7 +11,7 @@ vi.mock("../wsRpcClient", () => ({
|
||||
}));
|
||||
|
||||
import type { InfiniteData } from "@tanstack/react-query";
|
||||
import { EnvironmentId, type GitListBranchesResult } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
gitBranchSearchInfiniteQueryOptions,
|
||||
@@ -22,15 +22,15 @@ import {
|
||||
invalidateGitQueries,
|
||||
} from "./gitReactQuery";
|
||||
|
||||
const BRANCH_QUERY_RESULT: GitListBranchesResult = {
|
||||
branches: [],
|
||||
const BRANCH_QUERY_RESULT: VcsListRefsResult = {
|
||||
refs: [],
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
hasPrimaryRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
|
||||
const BRANCH_SEARCH_RESULT: InfiniteData<GitListBranchesResult, number> = {
|
||||
const BRANCH_SEARCH_RESULT: InfiniteData<VcsListRefsResult, number> = {
|
||||
pages: [BRANCH_QUERY_RESULT],
|
||||
pageParams: [0],
|
||||
};
|
||||
|
||||
@@ -19,17 +19,17 @@ const GIT_BRANCHES_PAGE_SIZE = 100;
|
||||
|
||||
export const gitQueryKeys = {
|
||||
all: ["git"] as const,
|
||||
branches: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "branches", environmentId ?? null, cwd] as const,
|
||||
refs: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "refs", environmentId ?? null, cwd] as const,
|
||||
branchSearch: (environmentId: EnvironmentId | null, cwd: string | null, query: string) =>
|
||||
["git", "branches", environmentId ?? null, cwd, "search", query] as const,
|
||||
["git", "refs", environmentId ?? null, cwd, "search", query] as const,
|
||||
};
|
||||
|
||||
export const gitMutationKeys = {
|
||||
init: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "init", environmentId ?? null, cwd] as const,
|
||||
checkout: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "checkout", environmentId ?? null, cwd] as const,
|
||||
switchRef: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "switchRef", environmentId ?? null, cwd] as const,
|
||||
runStackedAction: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "run-stacked-action", environmentId ?? null, cwd] as const,
|
||||
pull: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
@@ -45,7 +45,7 @@ export function invalidateGitQueries(
|
||||
const environmentId = input?.environmentId ?? null;
|
||||
const cwd = input?.cwd ?? null;
|
||||
if (cwd !== null) {
|
||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, cwd) });
|
||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) });
|
||||
}
|
||||
|
||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
|
||||
@@ -60,7 +60,7 @@ function invalidateGitBranchQueries(
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, cwd) });
|
||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,10 +78,10 @@ export function gitBranchSearchInfiniteQueryOptions(input: {
|
||||
queryKey: gitQueryKeys.branchSearch(input.environmentId, input.cwd, normalizedQuery),
|
||||
initialPageParam: 0,
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (!input.cwd) throw new Error("Git branches are unavailable.");
|
||||
if (!input.environmentId) throw new Error("Git branches are unavailable.");
|
||||
if (!input.cwd) throw new Error("Git refs are unavailable.");
|
||||
if (!input.environmentId) throw new Error("Git refs are unavailable.");
|
||||
const api = ensureEnvironmentApi(input.environmentId);
|
||||
return api.vcs.listBranches({
|
||||
return api.vcs.listRefs({
|
||||
cwd: input.cwd,
|
||||
...(normalizedQuery.length > 0 ? { query: normalizedQuery } : {}),
|
||||
cursor: pageParam,
|
||||
@@ -154,11 +154,11 @@ export function gitCheckoutMutationOptions(input: {
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.checkout(input.environmentId, input.cwd),
|
||||
mutationFn: async (branch: string) => {
|
||||
if (!input.cwd || !input.environmentId) throw new Error("Git checkout is unavailable.");
|
||||
mutationKey: gitMutationKeys.switchRef(input.environmentId, input.cwd),
|
||||
mutationFn: async (refName: string) => {
|
||||
if (!input.cwd || !input.environmentId) throw new Error("Git switchRef is unavailable.");
|
||||
const api = ensureEnvironmentApi(input.environmentId);
|
||||
return api.vcs.checkout({ cwd: input.cwd, branch });
|
||||
return api.vcs.switchRef({ cwd: input.cwd, refName });
|
||||
},
|
||||
onSettled: async () => {
|
||||
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentId, type GitStatusResult } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type VcsStatusResult } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { WsRpcClient } from "../rpc/wsRpcClient";
|
||||
@@ -33,17 +33,17 @@ function registerListener<T>(listeners: Set<(event: T) => void>, listener: (even
|
||||
};
|
||||
}
|
||||
|
||||
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
|
||||
const gitStatusListeners = new Set<(event: VcsStatusResult) => void>();
|
||||
const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const OTHER_ENVIRONMENT_ID = EnvironmentId.make("environment-remote");
|
||||
const TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/repo" } as const;
|
||||
const FRESH_TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/fresh" } as const;
|
||||
|
||||
const BASE_STATUS: GitStatusResult = {
|
||||
const BASE_STATUS: VcsStatusResult = {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/push-status",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/push-status",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -55,21 +55,21 @@ const BASE_STATUS: GitStatusResult = {
|
||||
const gitClient = {
|
||||
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
|
||||
...BASE_STATUS,
|
||||
branch: `${input.cwd}-refreshed`,
|
||||
refName: `${input.cwd}-refreshed`,
|
||||
})),
|
||||
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
|
||||
onStatus: vi.fn((input: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
|
||||
registerListener(gitStatusListeners, listener),
|
||||
),
|
||||
};
|
||||
|
||||
function emitGitStatus(event: GitStatusResult) {
|
||||
function emitGitStatus(event: VcsStatusResult) {
|
||||
for (const listener of gitStatusListeners) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
|
||||
const listeners = new Set<(event: GitStatusResult) => void>();
|
||||
const listeners = new Set<(event: VcsStatusResult) => void>();
|
||||
const client = {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
@@ -93,16 +93,16 @@ function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
|
||||
pull: vi.fn(async () => undefined),
|
||||
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
|
||||
...BASE_STATUS,
|
||||
branch: `${input.cwd}-refreshed`,
|
||||
refName: `${input.cwd}-refreshed`,
|
||||
})),
|
||||
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
|
||||
onStatus: vi.fn((_: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
|
||||
registerListener(listeners, listener),
|
||||
),
|
||||
listBranches: vi.fn(async () => []),
|
||||
listRefs: vi.fn(async () => []),
|
||||
createWorktree: vi.fn(async () => undefined),
|
||||
removeWorktree: vi.fn(async () => undefined),
|
||||
createBranch: vi.fn(async () => undefined),
|
||||
checkout: vi.fn(async () => undefined),
|
||||
createRef: vi.fn(async () => undefined),
|
||||
switchRef: vi.fn(async () => undefined),
|
||||
init: vi.fn(async () => undefined),
|
||||
},
|
||||
git: {
|
||||
@@ -157,7 +157,7 @@ function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
|
||||
|
||||
return {
|
||||
client,
|
||||
emit: (event: GitStatusResult) => {
|
||||
emit: (event: VcsStatusResult) => {
|
||||
for (const listener of listeners) {
|
||||
listener(event);
|
||||
}
|
||||
@@ -221,7 +221,7 @@ describe("gitStatusState", () => {
|
||||
|
||||
expect(gitClient.onStatus).toHaveBeenCalledOnce();
|
||||
expect(gitClient.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
|
||||
expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
|
||||
expect(refreshed).toEqual({ ...BASE_STATUS, refName: "/repo-refreshed" });
|
||||
expect(getGitStatusSnapshot(TARGET)).toEqual({
|
||||
data: BASE_STATUS,
|
||||
error: null,
|
||||
@@ -233,17 +233,17 @@ describe("gitStatusState", () => {
|
||||
});
|
||||
|
||||
it("keeps git status subscriptions isolated by environment when cwds match", () => {
|
||||
const localListeners = new Set<(event: GitStatusResult) => void>();
|
||||
const remoteListeners = new Set<(event: GitStatusResult) => void>();
|
||||
const localListeners = new Set<(event: VcsStatusResult) => void>();
|
||||
const remoteListeners = new Set<(event: VcsStatusResult) => void>();
|
||||
const localClient = {
|
||||
refreshStatus: vi.fn(),
|
||||
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
|
||||
onStatus: vi.fn((_: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
|
||||
registerListener(localListeners, listener),
|
||||
),
|
||||
};
|
||||
const remoteClient = {
|
||||
refreshStatus: vi.fn(),
|
||||
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
|
||||
onStatus: vi.fn((_: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
|
||||
registerListener(remoteListeners, listener),
|
||||
),
|
||||
};
|
||||
@@ -256,11 +256,11 @@ describe("gitStatusState", () => {
|
||||
listener(BASE_STATUS);
|
||||
}
|
||||
for (const listener of remoteListeners) {
|
||||
listener({ ...BASE_STATUS, branch: "remote-branch" });
|
||||
listener({ ...BASE_STATUS, refName: "remote-refName" });
|
||||
}
|
||||
|
||||
expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
|
||||
expect(getGitStatusSnapshot(remoteTarget).data?.branch).toBe("remote-branch");
|
||||
expect(getGitStatusSnapshot(TARGET).data?.refName).toBe("feature/push-status");
|
||||
expect(getGitStatusSnapshot(remoteTarget).data?.refName).toBe("remote-refName");
|
||||
|
||||
releaseLocal();
|
||||
releaseRemote();
|
||||
@@ -294,7 +294,7 @@ describe("gitStatusState", () => {
|
||||
const release = watchGitStatus(TARGET);
|
||||
|
||||
firstClient.emit(BASE_STATUS);
|
||||
expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
|
||||
expect(getGitStatusSnapshot(TARGET).data?.refName).toBe("feature/push-status");
|
||||
|
||||
serviceHarness.connections.delete(ENVIRONMENT_ID);
|
||||
for (const listener of serviceHarness.listeners) {
|
||||
@@ -309,10 +309,10 @@ describe("gitStatusState", () => {
|
||||
});
|
||||
|
||||
const secondClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
|
||||
secondClient.emit({ ...BASE_STATUS, branch: "reconnected-branch" });
|
||||
secondClient.emit({ ...BASE_STATUS, refName: "reconnected-refName" });
|
||||
|
||||
expect(getGitStatusSnapshot(TARGET)).toEqual({
|
||||
data: { ...BASE_STATUS, branch: "reconnected-branch" },
|
||||
data: { ...BASE_STATUS, refName: "reconnected-refName" },
|
||||
error: null,
|
||||
cause: null,
|
||||
isPending: false,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
type GitManagerServiceError,
|
||||
type GitStatusResult,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause } from "effect";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import type { WsRpcClient } from "~/rpc/wsRpcClient";
|
||||
|
||||
interface GitStatusState {
|
||||
readonly data: GitStatusResult | null;
|
||||
readonly data: VcsStatusResult | null;
|
||||
readonly error: GitManagerServiceError | null;
|
||||
readonly cause: Cause.Cause<GitManagerServiceError> | null;
|
||||
readonly isPending: boolean;
|
||||
@@ -56,7 +56,7 @@ const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
|
||||
const NOOP: () => void = () => undefined;
|
||||
const watchedGitStatuses = new Map<string, WatchedGitStatus>();
|
||||
const knownGitStatusKeys = new Set<string>();
|
||||
const gitStatusRefreshInFlight = new Map<string, Promise<GitStatusResult>>();
|
||||
const gitStatusRefreshInFlight = new Map<string, Promise<VcsStatusResult>>();
|
||||
const gitStatusLastRefreshAtByKey = new Map<string, number>();
|
||||
|
||||
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
|
||||
@@ -119,7 +119,7 @@ export function watchGitStatus(target: GitStatusTarget, client?: GitStatusClient
|
||||
export function refreshGitStatus(
|
||||
target: GitStatusTarget,
|
||||
client?: GitStatusClient,
|
||||
): Promise<GitStatusResult | null> {
|
||||
): Promise<VcsStatusResult | null> {
|
||||
const targetKey = getGitStatusTargetKey(target);
|
||||
if (targetKey === null || target.cwd === null) {
|
||||
return Promise.resolve(null);
|
||||
@@ -245,7 +245,7 @@ function subscribeToGitStatus(targetKey: string, cwd: string, client: GitStatusC
|
||||
markGitStatusPending(targetKey);
|
||||
return client.onStatus(
|
||||
{ cwd },
|
||||
(status: GitStatusResult) => {
|
||||
(status: VcsStatusResult) => {
|
||||
appAtomRegistry.set(gitStatusStateAtom(targetKey), {
|
||||
data: status,
|
||||
error: null,
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
type DesktopBridge,
|
||||
EnvironmentId,
|
||||
type GitStatusResult,
|
||||
type VcsStatusResult,
|
||||
ProjectId,
|
||||
type OrchestrationShellStreamItem,
|
||||
ProviderDriverKind,
|
||||
@@ -34,7 +34,7 @@ function registerListener<T>(listeners: Set<(event: T) => void>, listener: (even
|
||||
|
||||
const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
|
||||
const shellStreamListeners = new Set<(event: OrchestrationShellStreamItem) => void>();
|
||||
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
|
||||
const gitStatusListeners = new Set<(event: VcsStatusResult) => void>();
|
||||
|
||||
const rpcClientMock = {
|
||||
dispose: vi.fn(),
|
||||
@@ -62,14 +62,14 @@ const rpcClientMock = {
|
||||
vcs: {
|
||||
pull: vi.fn(),
|
||||
refreshStatus: vi.fn(),
|
||||
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
|
||||
onStatus: vi.fn((input: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
|
||||
registerListener(gitStatusListeners, listener),
|
||||
),
|
||||
listBranches: vi.fn(),
|
||||
listRefs: vi.fn(),
|
||||
createWorktree: vi.fn(),
|
||||
removeWorktree: vi.fn(),
|
||||
createBranch: vi.fn(),
|
||||
checkout: vi.fn(),
|
||||
createRef: vi.fn(),
|
||||
switchRef: vi.fn(),
|
||||
init: vi.fn(),
|
||||
},
|
||||
git: {
|
||||
@@ -261,11 +261,11 @@ const baseServerConfig: ServerConfig = {
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
};
|
||||
|
||||
const baseGitStatus: GitStatusResult = {
|
||||
const baseGitStatus: VcsStatusResult = {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/streamed",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/streamed",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusStreamEvent,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -18,16 +18,16 @@ vi.mock("./wsTransport", () => ({
|
||||
import { createWsRpcClient } from "./wsRpcClient";
|
||||
import { type WsTransport } from "./wsTransport";
|
||||
|
||||
const baseLocalStatus: GitStatusLocalResult = {
|
||||
const baseLocalStatus: VcsStatusLocalResult = {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
};
|
||||
|
||||
const baseRemoteStatus: GitStatusRemoteResult = {
|
||||
const baseRemoteStatus: VcsStatusRemoteResult = {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
@@ -54,7 +54,7 @@ describe("wsRpcClient", () => {
|
||||
hasWorkingTreeChanges: true,
|
||||
},
|
||||
},
|
||||
] satisfies GitStatusStreamEvent[]) {
|
||||
] satisfies VcsStatusStreamEvent[]) {
|
||||
listener(event as TValue);
|
||||
}
|
||||
return () => undefined;
|
||||
|
||||
@@ -2,8 +2,8 @@ import {
|
||||
type GitActionProgressEvent,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type GitStatusResult,
|
||||
type GitStatusStreamEvent,
|
||||
type VcsStatusResult,
|
||||
type VcsStatusStreamEvent,
|
||||
type LocalApi,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ServerSettingsPatch,
|
||||
@@ -82,14 +82,14 @@ export interface WsRpcClient {
|
||||
readonly refreshStatus: RpcUnaryMethod<typeof WS_METHODS.vcsRefreshStatus>;
|
||||
readonly onStatus: (
|
||||
input: RpcInput<typeof WS_METHODS.subscribeVcsStatus>,
|
||||
listener: (status: GitStatusResult) => void,
|
||||
listener: (status: VcsStatusResult) => void,
|
||||
options?: StreamSubscriptionOptions,
|
||||
) => () => void;
|
||||
readonly listBranches: RpcUnaryMethod<typeof WS_METHODS.vcsListBranches>;
|
||||
readonly listRefs: RpcUnaryMethod<typeof WS_METHODS.vcsListRefs>;
|
||||
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.vcsCreateWorktree>;
|
||||
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.vcsRemoveWorktree>;
|
||||
readonly createBranch: RpcUnaryMethod<typeof WS_METHODS.vcsCreateBranch>;
|
||||
readonly checkout: RpcUnaryMethod<typeof WS_METHODS.vcsCheckout>;
|
||||
readonly createRef: RpcUnaryMethod<typeof WS_METHODS.vcsCreateRef>;
|
||||
readonly switchRef: RpcUnaryMethod<typeof WS_METHODS.vcsSwitchRef>;
|
||||
readonly init: RpcUnaryMethod<typeof WS_METHODS.vcsInit>;
|
||||
};
|
||||
/**
|
||||
@@ -171,25 +171,23 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
refreshStatus: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.vcsRefreshStatus](input)),
|
||||
onStatus: (input, listener, options) => {
|
||||
let current: GitStatusResult | null = null;
|
||||
let current: VcsStatusResult | null = null;
|
||||
return transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeVcsStatus](input),
|
||||
(event: GitStatusStreamEvent) => {
|
||||
(event: VcsStatusStreamEvent) => {
|
||||
current = applyGitStatusStreamEvent(current, event);
|
||||
listener(current);
|
||||
},
|
||||
options,
|
||||
);
|
||||
},
|
||||
listBranches: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.vcsListBranches](input)),
|
||||
listRefs: (input) => transport.request((client) => client[WS_METHODS.vcsListRefs](input)),
|
||||
createWorktree: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.vcsCreateWorktree](input)),
|
||||
removeWorktree: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.vcsRemoveWorktree](input)),
|
||||
createBranch: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.vcsCreateBranch](input)),
|
||||
checkout: (input) => transport.request((client) => client[WS_METHODS.vcsCheckout](input)),
|
||||
createRef: (input) => transport.request((client) => client[WS_METHODS.vcsCreateRef](input)),
|
||||
switchRef: (input) => transport.request((client) => client[WS_METHODS.vcsSwitchRef](input)),
|
||||
init: (input) => transport.request((client) => client[WS_METHODS.vcsInit](input)),
|
||||
},
|
||||
git: {
|
||||
|
||||
@@ -2,14 +2,14 @@ import { describe, expect, it } from "vitest";
|
||||
import { Schema } from "effect";
|
||||
|
||||
import {
|
||||
GitCreateWorktreeInput,
|
||||
VcsCreateWorktreeInput,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitRunStackedActionResult,
|
||||
GitRunStackedActionInput,
|
||||
GitResolvePullRequestResult,
|
||||
} from "./git.ts";
|
||||
|
||||
const decodeCreateWorktreeInput = Schema.decodeUnknownSync(GitCreateWorktreeInput);
|
||||
const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput);
|
||||
const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(
|
||||
GitPreparePullRequestThreadInput,
|
||||
);
|
||||
@@ -17,16 +17,16 @@ const decodeRunStackedActionInput = Schema.decodeUnknownSync(GitRunStackedAction
|
||||
const decodeRunStackedActionResult = Schema.decodeUnknownSync(GitRunStackedActionResult);
|
||||
const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);
|
||||
|
||||
describe("GitCreateWorktreeInput", () => {
|
||||
it("accepts omitted newBranch for existing-branch worktrees", () => {
|
||||
describe("VcsCreateWorktreeInput", () => {
|
||||
it("accepts omitted newRefName for existing-refName worktrees", () => {
|
||||
const parsed = decodeCreateWorktreeInput({
|
||||
cwd: "/repo",
|
||||
branch: "feature/existing",
|
||||
refName: "feature/existing",
|
||||
path: "/tmp/worktree",
|
||||
});
|
||||
|
||||
expect(parsed.newBranch).toBeUndefined();
|
||||
expect(parsed.branch).toBe("feature/existing");
|
||||
expect(parsed.newRefName).toBeUndefined();
|
||||
expect(parsed.refName).toBe("feature/existing");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("GitRunStackedActionResult", () => {
|
||||
it("decodes a server-authored completion toast", () => {
|
||||
const parsed = decodeRunStackedActionResult({
|
||||
action: "commit_push",
|
||||
branch: {
|
||||
refName: {
|
||||
status: "created",
|
||||
name: "feature/server-owned-toast",
|
||||
},
|
||||
@@ -89,8 +89,8 @@ describe("GitRunStackedActionResult", () => {
|
||||
},
|
||||
push: {
|
||||
status: "pushed",
|
||||
branch: "feature/server-owned-toast",
|
||||
upstreamBranch: "origin/feature/server-owned-toast",
|
||||
refName: "feature/server-owned-toast",
|
||||
upstreamRef: "origin/feature/server-owned-toast",
|
||||
},
|
||||
pr: {
|
||||
status: "skipped_not_requested",
|
||||
|
||||
@@ -41,7 +41,7 @@ const GitPushStepStatus = Schema.Literals([
|
||||
]);
|
||||
const GitBranchStepStatus = Schema.Literals(["created", "skipped_not_requested"]);
|
||||
const GitPrStepStatus = Schema.Literals(["created", "opened_existing", "skipped_not_requested"]);
|
||||
const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
|
||||
const VcsStatusChangeRequestState = Schema.Literals(["open", "closed", "merged"]);
|
||||
const GitPullRequestReference = TrimmedNonEmptyStringSchema;
|
||||
const GitPullRequestState = Schema.Literals(["open", "closed", "merged"]);
|
||||
const GitPreparePullRequestThreadMode = Schema.Literals(["local", "worktree"]);
|
||||
@@ -85,7 +85,7 @@ const GitRunStackedActionToast = Schema.Struct({
|
||||
});
|
||||
export type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type;
|
||||
|
||||
export const GitBranch = Schema.Struct({
|
||||
export const VcsRef = Schema.Struct({
|
||||
name: TrimmedNonEmptyStringSchema,
|
||||
isRemote: Schema.optional(Schema.Boolean),
|
||||
remoteName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
@@ -93,11 +93,11 @@ export const GitBranch = Schema.Struct({
|
||||
isDefault: Schema.Boolean,
|
||||
worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
});
|
||||
export type GitBranch = typeof GitBranch.Type;
|
||||
export type VcsRef = typeof VcsRef.Type;
|
||||
|
||||
const GitWorktree = Schema.Struct({
|
||||
const VcsWorktree = Schema.Struct({
|
||||
path: TrimmedNonEmptyStringSchema,
|
||||
branch: TrimmedNonEmptyStringSchema,
|
||||
refName: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
const GitResolvedPullRequest = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
@@ -111,15 +111,15 @@ export type GitResolvedPullRequest = typeof GitResolvedPullRequest.Type;
|
||||
|
||||
// RPC Inputs
|
||||
|
||||
export const GitStatusInput = Schema.Struct({
|
||||
export const VcsStatusInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type GitStatusInput = typeof GitStatusInput.Type;
|
||||
export type VcsStatusInput = typeof VcsStatusInput.Type;
|
||||
|
||||
export const GitPullInput = Schema.Struct({
|
||||
export const VcsPullInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type GitPullInput = typeof GitPullInput.Type;
|
||||
export type VcsPullInput = typeof VcsPullInput.Type;
|
||||
|
||||
export const GitRunStackedActionInput = Schema.Struct({
|
||||
actionId: TrimmedNonEmptyStringSchema,
|
||||
@@ -133,7 +133,7 @@ export const GitRunStackedActionInput = Schema.Struct({
|
||||
});
|
||||
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
|
||||
|
||||
export const GitListBranchesInput = Schema.Struct({
|
||||
export const VcsListRefsInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
query: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(256))),
|
||||
cursor: Schema.optional(NonNegativeInt),
|
||||
@@ -141,15 +141,15 @@ export const GitListBranchesInput = Schema.Struct({
|
||||
PositiveInt.check(Schema.isLessThanOrEqualTo(GIT_LIST_BRANCHES_MAX_LIMIT)),
|
||||
),
|
||||
});
|
||||
export type GitListBranchesInput = typeof GitListBranchesInput.Type;
|
||||
export type VcsListRefsInput = typeof VcsListRefsInput.Type;
|
||||
|
||||
export const GitCreateWorktreeInput = Schema.Struct({
|
||||
export const VcsCreateWorktreeInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
branch: TrimmedNonEmptyStringSchema,
|
||||
newBranch: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
refName: TrimmedNonEmptyStringSchema,
|
||||
newRefName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
path: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type GitCreateWorktreeInput = typeof GitCreateWorktreeInput.Type;
|
||||
export type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type;
|
||||
|
||||
export const GitPullRequestRefInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
@@ -165,53 +165,53 @@ export const GitPreparePullRequestThreadInput = Schema.Struct({
|
||||
});
|
||||
export type GitPreparePullRequestThreadInput = typeof GitPreparePullRequestThreadInput.Type;
|
||||
|
||||
export const GitRemoveWorktreeInput = Schema.Struct({
|
||||
export const VcsRemoveWorktreeInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
path: TrimmedNonEmptyStringSchema,
|
||||
force: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type GitRemoveWorktreeInput = typeof GitRemoveWorktreeInput.Type;
|
||||
export type VcsRemoveWorktreeInput = typeof VcsRemoveWorktreeInput.Type;
|
||||
|
||||
export const GitCreateBranchInput = Schema.Struct({
|
||||
export const VcsCreateRefInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
branch: TrimmedNonEmptyStringSchema,
|
||||
checkout: Schema.optional(Schema.Boolean),
|
||||
refName: TrimmedNonEmptyStringSchema,
|
||||
switchRef: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type GitCreateBranchInput = typeof GitCreateBranchInput.Type;
|
||||
export type VcsCreateRefInput = typeof VcsCreateRefInput.Type;
|
||||
|
||||
export const GitCreateBranchResult = Schema.Struct({
|
||||
branch: TrimmedNonEmptyStringSchema,
|
||||
export const VcsCreateRefResult = Schema.Struct({
|
||||
refName: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type GitCreateBranchResult = typeof GitCreateBranchResult.Type;
|
||||
export type VcsCreateRefResult = typeof VcsCreateRefResult.Type;
|
||||
|
||||
export const GitCheckoutInput = Schema.Struct({
|
||||
export const VcsSwitchRefInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
branch: TrimmedNonEmptyStringSchema,
|
||||
refName: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type GitCheckoutInput = typeof GitCheckoutInput.Type;
|
||||
export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type;
|
||||
|
||||
export const GitInitInput = Schema.Struct({
|
||||
export const VcsInitInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type GitInitInput = typeof GitInitInput.Type;
|
||||
export type VcsInitInput = typeof VcsInitInput.Type;
|
||||
|
||||
// RPC Results
|
||||
|
||||
const GitStatusPr = Schema.Struct({
|
||||
const VcsStatusChangeRequest = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
state: GitStatusPrState,
|
||||
baseRef: TrimmedNonEmptyStringSchema,
|
||||
headRef: TrimmedNonEmptyStringSchema,
|
||||
state: VcsStatusChangeRequestState,
|
||||
});
|
||||
|
||||
const GitStatusLocalShape = {
|
||||
const VcsStatusLocalShape = {
|
||||
isRepo: Schema.Boolean,
|
||||
hostingProvider: Schema.optional(GitHostingProvider),
|
||||
hasOriginRemote: Schema.Boolean,
|
||||
isDefaultBranch: Schema.Boolean,
|
||||
branch: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
hasPrimaryRemote: Schema.Boolean,
|
||||
isDefaultRef: Schema.Boolean,
|
||||
refName: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
hasWorkingTreeChanges: Schema.Boolean,
|
||||
workingTree: Schema.Struct({
|
||||
files: Schema.Array(
|
||||
@@ -226,52 +226,52 @@ const GitStatusLocalShape = {
|
||||
}),
|
||||
};
|
||||
|
||||
const GitStatusRemoteShape = {
|
||||
const VcsStatusRemoteShape = {
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
pr: Schema.NullOr(GitStatusPr),
|
||||
pr: Schema.NullOr(VcsStatusChangeRequest),
|
||||
};
|
||||
|
||||
export const GitStatusLocalResult = Schema.Struct(GitStatusLocalShape);
|
||||
export type GitStatusLocalResult = typeof GitStatusLocalResult.Type;
|
||||
export const VcsStatusLocalResult = Schema.Struct(VcsStatusLocalShape);
|
||||
export type VcsStatusLocalResult = typeof VcsStatusLocalResult.Type;
|
||||
|
||||
export const GitStatusRemoteResult = Schema.Struct(GitStatusRemoteShape);
|
||||
export type GitStatusRemoteResult = typeof GitStatusRemoteResult.Type;
|
||||
export const VcsStatusRemoteResult = Schema.Struct(VcsStatusRemoteShape);
|
||||
export type VcsStatusRemoteResult = typeof VcsStatusRemoteResult.Type;
|
||||
|
||||
export const GitStatusResult = Schema.Struct({
|
||||
...GitStatusLocalShape,
|
||||
...GitStatusRemoteShape,
|
||||
export const VcsStatusResult = Schema.Struct({
|
||||
...VcsStatusLocalShape,
|
||||
...VcsStatusRemoteShape,
|
||||
});
|
||||
export type GitStatusResult = typeof GitStatusResult.Type;
|
||||
export type VcsStatusResult = typeof VcsStatusResult.Type;
|
||||
|
||||
export const GitStatusStreamEvent = Schema.Union([
|
||||
export const VcsStatusStreamEvent = Schema.Union([
|
||||
Schema.TaggedStruct("snapshot", {
|
||||
local: GitStatusLocalResult,
|
||||
remote: Schema.NullOr(GitStatusRemoteResult),
|
||||
local: VcsStatusLocalResult,
|
||||
remote: Schema.NullOr(VcsStatusRemoteResult),
|
||||
}),
|
||||
Schema.TaggedStruct("localUpdated", {
|
||||
local: GitStatusLocalResult,
|
||||
local: VcsStatusLocalResult,
|
||||
}),
|
||||
Schema.TaggedStruct("remoteUpdated", {
|
||||
remote: Schema.NullOr(GitStatusRemoteResult),
|
||||
remote: Schema.NullOr(VcsStatusRemoteResult),
|
||||
}),
|
||||
]);
|
||||
export type GitStatusStreamEvent = typeof GitStatusStreamEvent.Type;
|
||||
export type VcsStatusStreamEvent = typeof VcsStatusStreamEvent.Type;
|
||||
|
||||
export const GitListBranchesResult = Schema.Struct({
|
||||
branches: Schema.Array(GitBranch),
|
||||
export const VcsListRefsResult = Schema.Struct({
|
||||
refs: Schema.Array(VcsRef),
|
||||
isRepo: Schema.Boolean,
|
||||
hasOriginRemote: Schema.Boolean,
|
||||
hasPrimaryRemote: Schema.Boolean,
|
||||
nextCursor: NonNegativeInt.pipe(Schema.NullOr),
|
||||
totalCount: NonNegativeInt,
|
||||
});
|
||||
export type GitListBranchesResult = typeof GitListBranchesResult.Type;
|
||||
export type VcsListRefsResult = typeof VcsListRefsResult.Type;
|
||||
|
||||
export const GitCreateWorktreeResult = Schema.Struct({
|
||||
worktree: GitWorktree,
|
||||
export const VcsCreateWorktreeResult = Schema.Struct({
|
||||
worktree: VcsWorktree,
|
||||
});
|
||||
export type GitCreateWorktreeResult = typeof GitCreateWorktreeResult.Type;
|
||||
export type VcsCreateWorktreeResult = typeof VcsCreateWorktreeResult.Type;
|
||||
|
||||
export const GitResolvePullRequestResult = Schema.Struct({
|
||||
pullRequest: GitResolvedPullRequest,
|
||||
@@ -285,10 +285,10 @@ export const GitPreparePullRequestThreadResult = Schema.Struct({
|
||||
});
|
||||
export type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type;
|
||||
|
||||
export const GitCheckoutResult = Schema.Struct({
|
||||
branch: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
export const VcsSwitchRefResult = Schema.Struct({
|
||||
refName: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type GitCheckoutResult = typeof GitCheckoutResult.Type;
|
||||
export type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type;
|
||||
|
||||
export const GitRunStackedActionResult = Schema.Struct({
|
||||
action: GitStackedAction,
|
||||
@@ -319,12 +319,12 @@ export const GitRunStackedActionResult = Schema.Struct({
|
||||
});
|
||||
export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type;
|
||||
|
||||
export const GitPullResult = Schema.Struct({
|
||||
export const VcsPullResult = Schema.Struct({
|
||||
status: Schema.Literals(["pulled", "skipped_up_to_date"]),
|
||||
branch: TrimmedNonEmptyStringSchema,
|
||||
upstreamBranch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
refName: TrimmedNonEmptyStringSchema,
|
||||
upstreamRef: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
});
|
||||
export type GitPullResult = typeof GitPullResult.Type;
|
||||
export type VcsPullResult = typeof VcsPullResult.Type;
|
||||
|
||||
// RPC / domain errors
|
||||
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCheckoutResult,
|
||||
GitCreateBranchInput,
|
||||
VcsSwitchRefInput,
|
||||
VcsSwitchRefResult,
|
||||
VcsCreateRefInput,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullRequestRefInput,
|
||||
GitCreateWorktreeInput,
|
||||
GitCreateWorktreeResult,
|
||||
GitInitInput,
|
||||
GitListBranchesInput,
|
||||
GitListBranchesResult,
|
||||
GitPullInput,
|
||||
GitPullResult,
|
||||
GitRemoveWorktreeInput,
|
||||
VcsCreateWorktreeInput,
|
||||
VcsCreateWorktreeResult,
|
||||
VcsInitInput,
|
||||
VcsListRefsInput,
|
||||
VcsListRefsResult,
|
||||
VcsPullInput,
|
||||
VcsPullResult,
|
||||
VcsRemoveWorktreeInput,
|
||||
GitResolvePullRequestResult,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
GitCreateBranchResult,
|
||||
VcsStatusInput,
|
||||
VcsStatusResult,
|
||||
VcsCreateRefResult,
|
||||
} from "./git.ts";
|
||||
import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts";
|
||||
import type {
|
||||
@@ -257,17 +257,17 @@ export interface EnvironmentApi {
|
||||
browse: (input: FilesystemBrowseInput) => Promise<FilesystemBrowseResult>;
|
||||
};
|
||||
vcs: {
|
||||
listBranches: (input: GitListBranchesInput) => Promise<GitListBranchesResult>;
|
||||
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
|
||||
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
|
||||
createBranch: (input: GitCreateBranchInput) => Promise<GitCreateBranchResult>;
|
||||
checkout: (input: GitCheckoutInput) => Promise<GitCheckoutResult>;
|
||||
init: (input: GitInitInput) => Promise<void>;
|
||||
pull: (input: GitPullInput) => Promise<GitPullResult>;
|
||||
refreshStatus: (input: GitStatusInput) => Promise<GitStatusResult>;
|
||||
listRefs: (input: VcsListRefsInput) => Promise<VcsListRefsResult>;
|
||||
createWorktree: (input: VcsCreateWorktreeInput) => Promise<VcsCreateWorktreeResult>;
|
||||
removeWorktree: (input: VcsRemoveWorktreeInput) => Promise<void>;
|
||||
createRef: (input: VcsCreateRefInput) => Promise<VcsCreateRefResult>;
|
||||
switchRef: (input: VcsSwitchRefInput) => Promise<VcsSwitchRefResult>;
|
||||
init: (input: VcsInitInput) => Promise<void>;
|
||||
pull: (input: VcsPullInput) => Promise<VcsPullResult>;
|
||||
refreshStatus: (input: VcsStatusInput) => Promise<VcsStatusResult>;
|
||||
onStatus: (
|
||||
input: GitStatusInput,
|
||||
callback: (status: GitStatusResult) => void,
|
||||
input: VcsStatusInput,
|
||||
callback: (status: VcsStatusResult) => void,
|
||||
options?: {
|
||||
onResubscribe?: () => void;
|
||||
},
|
||||
|
||||
@@ -11,28 +11,28 @@ import {
|
||||
} from "./filesystem.ts";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitCheckoutInput,
|
||||
GitCheckoutResult,
|
||||
VcsSwitchRefInput,
|
||||
VcsSwitchRefResult,
|
||||
GitCommandError,
|
||||
GitCreateBranchInput,
|
||||
GitCreateBranchResult,
|
||||
GitCreateWorktreeInput,
|
||||
GitCreateWorktreeResult,
|
||||
GitInitInput,
|
||||
GitListBranchesInput,
|
||||
GitListBranchesResult,
|
||||
VcsCreateRefInput,
|
||||
VcsCreateRefResult,
|
||||
VcsCreateWorktreeInput,
|
||||
VcsCreateWorktreeResult,
|
||||
VcsInitInput,
|
||||
VcsListRefsInput,
|
||||
VcsListRefsResult,
|
||||
GitManagerServiceError,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullInput,
|
||||
VcsPullInput,
|
||||
GitPullRequestRefInput,
|
||||
GitPullResult,
|
||||
GitRemoveWorktreeInput,
|
||||
VcsPullResult,
|
||||
VcsRemoveWorktreeInput,
|
||||
GitResolvePullRequestResult,
|
||||
GitRunStackedActionInput,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
VcsStatusInput,
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "./git.ts";
|
||||
import { KeybindingsConfigError } from "./keybindings.ts";
|
||||
import {
|
||||
@@ -95,11 +95,11 @@ export const WS_METHODS = {
|
||||
// VCS methods
|
||||
vcsPull: "vcs.pull",
|
||||
vcsRefreshStatus: "vcs.refreshStatus",
|
||||
vcsListBranches: "vcs.listBranches",
|
||||
vcsListRefs: "vcs.listRefs",
|
||||
vcsCreateWorktree: "vcs.createWorktree",
|
||||
vcsRemoveWorktree: "vcs.removeWorktree",
|
||||
vcsCreateBranch: "vcs.createBranch",
|
||||
vcsCheckout: "vcs.checkout",
|
||||
vcsCreateRef: "vcs.createRef",
|
||||
vcsSwitchRef: "vcs.switchRef",
|
||||
vcsInit: "vcs.init",
|
||||
|
||||
// Git workflow methods
|
||||
@@ -191,21 +191,21 @@ export const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {
|
||||
});
|
||||
|
||||
export const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, {
|
||||
payload: GitStatusInput,
|
||||
success: GitStatusStreamEvent,
|
||||
payload: VcsStatusInput,
|
||||
success: VcsStatusStreamEvent,
|
||||
error: GitManagerServiceError,
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsVcsPullRpc = Rpc.make(WS_METHODS.vcsPull, {
|
||||
payload: GitPullInput,
|
||||
success: GitPullResult,
|
||||
payload: VcsPullInput,
|
||||
success: VcsPullResult,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
export const WsVcsRefreshStatusRpc = Rpc.make(WS_METHODS.vcsRefreshStatus, {
|
||||
payload: GitStatusInput,
|
||||
success: GitStatusResult,
|
||||
payload: VcsStatusInput,
|
||||
success: VcsStatusResult,
|
||||
error: GitManagerServiceError,
|
||||
});
|
||||
|
||||
@@ -228,37 +228,37 @@ export const WsGitPreparePullRequestThreadRpc = Rpc.make(WS_METHODS.gitPreparePu
|
||||
error: GitManagerServiceError,
|
||||
});
|
||||
|
||||
export const WsVcsListBranchesRpc = Rpc.make(WS_METHODS.vcsListBranches, {
|
||||
payload: GitListBranchesInput,
|
||||
success: GitListBranchesResult,
|
||||
export const WsVcsListRefsRpc = Rpc.make(WS_METHODS.vcsListRefs, {
|
||||
payload: VcsListRefsInput,
|
||||
success: VcsListRefsResult,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
export const WsVcsCreateWorktreeRpc = Rpc.make(WS_METHODS.vcsCreateWorktree, {
|
||||
payload: GitCreateWorktreeInput,
|
||||
success: GitCreateWorktreeResult,
|
||||
payload: VcsCreateWorktreeInput,
|
||||
success: VcsCreateWorktreeResult,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
export const WsVcsRemoveWorktreeRpc = Rpc.make(WS_METHODS.vcsRemoveWorktree, {
|
||||
payload: GitRemoveWorktreeInput,
|
||||
payload: VcsRemoveWorktreeInput,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
export const WsVcsCreateBranchRpc = Rpc.make(WS_METHODS.vcsCreateBranch, {
|
||||
payload: GitCreateBranchInput,
|
||||
success: GitCreateBranchResult,
|
||||
export const WsVcsCreateRefRpc = Rpc.make(WS_METHODS.vcsCreateRef, {
|
||||
payload: VcsCreateRefInput,
|
||||
success: VcsCreateRefResult,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
export const WsVcsCheckoutRpc = Rpc.make(WS_METHODS.vcsCheckout, {
|
||||
payload: GitCheckoutInput,
|
||||
success: GitCheckoutResult,
|
||||
export const WsVcsSwitchRefRpc = Rpc.make(WS_METHODS.vcsSwitchRef, {
|
||||
payload: VcsSwitchRefInput,
|
||||
success: VcsSwitchRefResult,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {
|
||||
payload: GitInitInput,
|
||||
payload: VcsInitInput,
|
||||
error: GitCommandError,
|
||||
});
|
||||
|
||||
@@ -382,11 +382,11 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsGitRunStackedActionRpc,
|
||||
WsGitResolvePullRequestRpc,
|
||||
WsGitPreparePullRequestThreadRpc,
|
||||
WsVcsListBranchesRpc,
|
||||
WsVcsListRefsRpc,
|
||||
WsVcsCreateWorktreeRpc,
|
||||
WsVcsRemoveWorktreeRpc,
|
||||
WsVcsCreateBranchRpc,
|
||||
WsVcsCheckoutRpc,
|
||||
WsVcsCreateRefRpc,
|
||||
WsVcsSwitchRefRpc,
|
||||
WsVcsInitRpc,
|
||||
WsTerminalOpenRpc,
|
||||
WsTerminalWriteRpc,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitStatusRemoteResult, GitStatusResult } from "@t3tools/contracts";
|
||||
import type { VcsStatusRemoteResult, VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -54,17 +54,17 @@ describe("parseGitHubRepositoryNameWithOwnerFromRemoteUrl", () => {
|
||||
});
|
||||
|
||||
describe("isTemporaryWorktreeBranch", () => {
|
||||
it("matches the generated temporary worktree branch format", () => {
|
||||
it("matches the generated temporary worktree refName format", () => {
|
||||
expect(isTemporaryWorktreeBranch(buildTemporaryWorktreeBranchName())).toBe(true);
|
||||
});
|
||||
|
||||
it("matches generated temporary worktree branches", () => {
|
||||
it("matches generated temporary worktree refs", () => {
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef`)).toBe(true);
|
||||
expect(isTemporaryWorktreeBranch(` ${WORKTREE_BRANCH_PREFIX}/deadbeef `)).toBe(true);
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/DEADBEEF`)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects non-temporary branch names", () => {
|
||||
it("rejects non-temporary refName names", () => {
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/feature/demo`)).toBe(false);
|
||||
expect(isTemporaryWorktreeBranch("main")).toBe(false);
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-extra`)).toBe(false);
|
||||
@@ -73,7 +73,7 @@ describe("isTemporaryWorktreeBranch", () => {
|
||||
|
||||
describe("applyGitStatusStreamEvent", () => {
|
||||
it("treats a remote-only update as a repository when local state is missing", () => {
|
||||
const remote: GitStatusRemoteResult = {
|
||||
const remote: VcsStatusRemoteResult = {
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
@@ -82,9 +82,9 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
|
||||
expect(applyGitStatusStreamEvent(null, { _tag: "remoteUpdated", remote })).toEqual({
|
||||
isRepo: true,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -95,16 +95,16 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
});
|
||||
|
||||
it("preserves local-only fields when applying a remote update", () => {
|
||||
const current: GitStatusResult = {
|
||||
const current: VcsStatusResult = {
|
||||
isRepo: true,
|
||||
hostingProvider: {
|
||||
kind: "github",
|
||||
name: "GitHub",
|
||||
baseUrl: "https://github.com",
|
||||
},
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: {
|
||||
files: [{ path: "src/demo.ts", insertions: 1, deletions: 0 }],
|
||||
@@ -117,7 +117,7 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const remote: GitStatusRemoteResult = {
|
||||
const remote: VcsStatusRemoteResult = {
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
|
||||
+36
-36
@@ -1,10 +1,10 @@
|
||||
import type {
|
||||
GitBranch,
|
||||
VcsRef,
|
||||
GitHostingProvider,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Random from "effect/Random";
|
||||
@@ -13,7 +13,7 @@ export const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
|
||||
/**
|
||||
* Sanitize an arbitrary string into a valid, lowercase git branch fragment.
|
||||
* Sanitize an arbitrary string into a valid, lowercase git refName fragment.
|
||||
* Strips quotes, collapses separators, limits to 64 chars.
|
||||
*/
|
||||
export function sanitizeBranchFragment(raw: string): string {
|
||||
@@ -35,7 +35,7 @@ export function sanitizeBranchFragment(raw: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a string into a `feature/…` branch name.
|
||||
* Sanitize a string into a `feature/…` refName name.
|
||||
* Preserves an existing `feature/` prefix or slash-separated namespace.
|
||||
*/
|
||||
export function sanitizeFeatureBranchName(raw: string): string {
|
||||
@@ -49,8 +49,8 @@ export function sanitizeFeatureBranchName(raw: string): string {
|
||||
const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
|
||||
|
||||
/**
|
||||
* Resolve a unique `feature/…` branch name that doesn't collide with
|
||||
* any existing branch. Appends a numeric suffix when needed.
|
||||
* Resolve a unique `feature/…` refName name that doesn't collide with
|
||||
* any existing refName. Appends a numeric suffix when needed.
|
||||
*/
|
||||
export function resolveAutoFeatureBranchName(
|
||||
existingBranchNames: readonly string[],
|
||||
@@ -60,7 +60,7 @@ export function resolveAutoFeatureBranchName(
|
||||
const resolvedBase = sanitizeFeatureBranchName(
|
||||
preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
|
||||
);
|
||||
const existingNames = new Set(existingBranchNames.map((branch) => branch.toLowerCase()));
|
||||
const existingNames = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));
|
||||
|
||||
if (!existingNames.has(resolvedBase)) {
|
||||
return resolvedBase;
|
||||
@@ -90,8 +90,8 @@ export function buildTemporaryWorktreeBranchName(): string {
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
export function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
export function isTemporaryWorktreeBranch(refName: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -165,27 +165,27 @@ function deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide `origin/*` remote refs when a matching local branch already exists.
|
||||
* Hide `origin/*` remote refs when a matching local refName already exists.
|
||||
*/
|
||||
export function dedupeRemoteBranchesWithLocalMatches(
|
||||
branches: ReadonlyArray<GitBranch>,
|
||||
): ReadonlyArray<GitBranch> {
|
||||
refs: ReadonlyArray<VcsRef>,
|
||||
): ReadonlyArray<VcsRef> {
|
||||
const localBranchNames = new Set(
|
||||
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
|
||||
refs.filter((refName) => !refName.isRemote).map((refName) => refName.name),
|
||||
);
|
||||
|
||||
return branches.filter((branch) => {
|
||||
if (!branch.isRemote) {
|
||||
return refs.filter((refName) => {
|
||||
if (!refName.isRemote) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (branch.remoteName !== "origin") {
|
||||
if (refName.remoteName !== "origin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
branch.name,
|
||||
branch.remoteName,
|
||||
refName.name,
|
||||
refName.remoteName,
|
||||
);
|
||||
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
||||
});
|
||||
@@ -268,7 +268,7 @@ export function detectGitHostingProviderFromRemoteUrl(
|
||||
};
|
||||
}
|
||||
|
||||
const EMPTY_GIT_STATUS_REMOTE: GitStatusRemoteResult = {
|
||||
const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
@@ -276,16 +276,16 @@ const EMPTY_GIT_STATUS_REMOTE: GitStatusRemoteResult = {
|
||||
};
|
||||
|
||||
export function mergeGitStatusParts(
|
||||
local: GitStatusLocalResult,
|
||||
remote: GitStatusRemoteResult | null,
|
||||
): GitStatusResult {
|
||||
local: VcsStatusLocalResult,
|
||||
remote: VcsStatusRemoteResult | null,
|
||||
): VcsStatusResult {
|
||||
return {
|
||||
...local,
|
||||
...(remote ?? EMPTY_GIT_STATUS_REMOTE),
|
||||
};
|
||||
}
|
||||
|
||||
function toRemoteStatusPart(status: GitStatusResult): GitStatusRemoteResult {
|
||||
function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
|
||||
return {
|
||||
hasUpstream: status.hasUpstream,
|
||||
aheadCount: status.aheadCount,
|
||||
@@ -294,22 +294,22 @@ function toRemoteStatusPart(status: GitStatusResult): GitStatusRemoteResult {
|
||||
};
|
||||
}
|
||||
|
||||
function toLocalStatusPart(status: GitStatusResult): GitStatusLocalResult {
|
||||
function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
|
||||
return {
|
||||
isRepo: status.isRepo,
|
||||
...(status.hostingProvider ? { hostingProvider: status.hostingProvider } : {}),
|
||||
hasOriginRemote: status.hasOriginRemote,
|
||||
isDefaultBranch: status.isDefaultBranch,
|
||||
branch: status.branch,
|
||||
hasPrimaryRemote: status.hasPrimaryRemote,
|
||||
isDefaultRef: status.isDefaultRef,
|
||||
refName: status.refName,
|
||||
hasWorkingTreeChanges: status.hasWorkingTreeChanges,
|
||||
workingTree: status.workingTree,
|
||||
};
|
||||
}
|
||||
|
||||
export function applyGitStatusStreamEvent(
|
||||
current: GitStatusResult | null,
|
||||
event: GitStatusStreamEvent,
|
||||
): GitStatusResult {
|
||||
current: VcsStatusResult | null,
|
||||
event: VcsStatusStreamEvent,
|
||||
): VcsStatusResult {
|
||||
switch (event._tag) {
|
||||
case "snapshot":
|
||||
return mergeGitStatusParts(event.local, event.remote);
|
||||
@@ -320,9 +320,9 @@ export function applyGitStatusStreamEvent(
|
||||
return mergeGitStatusParts(
|
||||
{
|
||||
isRepo: true,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user