Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f485be5715 | ||
|
|
df59af7222 | ||
|
|
4b30c82fd9 | ||
|
|
153bb29c80 | ||
|
|
22470229a9 | ||
|
|
98a7847022 | ||
|
|
27697abbad | ||
|
|
92e2845b7c | ||
|
|
f7748a0d65 | ||
|
|
0ce7e56e43 | ||
|
|
350d76ee14 | ||
|
|
6d7fe2eeb7 |
No files matched your search
@@ -1,49 +0,0 @@
|
||||
name: Setup Jujutsu
|
||||
description: Install the jj CLI from the official jj-vcs release artifacts.
|
||||
|
||||
inputs:
|
||||
version:
|
||||
description: Jujutsu release tag to install.
|
||||
required: false
|
||||
default: v0.40.0
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install jj
|
||||
shell: bash
|
||||
env:
|
||||
JJ_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
case "${RUNNER_OS}-${RUNNER_ARCH}" in
|
||||
Linux-X64)
|
||||
asset="jj-${JJ_VERSION}-x86_64-unknown-linux-musl.tar.gz"
|
||||
;;
|
||||
Linux-ARM64)
|
||||
asset="jj-${JJ_VERSION}-aarch64-unknown-linux-musl.tar.gz"
|
||||
;;
|
||||
macOS-X64)
|
||||
asset="jj-${JJ_VERSION}-x86_64-apple-darwin.tar.gz"
|
||||
;;
|
||||
macOS-ARM64)
|
||||
asset="jj-${JJ_VERSION}-aarch64-apple-darwin.tar.gz"
|
||||
;;
|
||||
*)
|
||||
echo "Unsupported runner for jj install: ${RUNNER_OS}-${RUNNER_ARCH}" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
install_dir="${RUNNER_TEMP}/jj-${JJ_VERSION}"
|
||||
mkdir -p "$install_dir"
|
||||
|
||||
curl -fsSL \
|
||||
"https://github.com/jj-vcs/jj/releases/download/${JJ_VERSION}/${asset}" \
|
||||
-o "${RUNNER_TEMP}/${asset}"
|
||||
tar -xzf "${RUNNER_TEMP}/${asset}" -C "$install_dir"
|
||||
|
||||
chmod +x "${install_dir}/jj"
|
||||
echo "$install_dir" >> "$GITHUB_PATH"
|
||||
"${install_dir}/jj" --version
|
||||
@@ -25,9 +25,6 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Setup Jujutsu
|
||||
uses: ./.github/actions/setup-jj
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
|
||||
@@ -95,9 +95,6 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Setup Jujutsu
|
||||
uses: ./.github/actions/setup-jj
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
|
||||
@@ -331,7 +331,6 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
|
||||
@@ -506,6 +506,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(incrementalDiff.includes("README.md"), true);
|
||||
|
||||
@@ -514,6 +515,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(fullDiff.includes("README.md"), true);
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
@@ -68,9 +69,14 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
@@ -102,6 +108,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
@@ -113,6 +120,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
@@ -123,6 +131,67 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults to hide whitespace changes", async () => {
|
||||
const projectId = ProjectId.make("project-default-whitespace");
|
||||
const threadId = ThreadId.make("thread-default-whitespace");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ ignoreWhitespace });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ const make = Effect.gen(function* () {
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -131,6 +132,7 @@ const make = Effect.gen(function* () {
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
|
||||
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -157,6 +159,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace ?? true,
|
||||
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
||||
|
||||
return {
|
||||
|
||||
@@ -114,6 +114,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git");
|
||||
@@ -121,5 +122,80 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
expect(diff).toContain("+line 04999");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("can hide indentation churn when changes wrap existing lines", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
const componentPath = path.join(tmp, "Component.tsx");
|
||||
yield* writeTextFile(
|
||||
componentPath,
|
||||
[
|
||||
"export function View() {",
|
||||
" return (",
|
||||
" <section>",
|
||||
" <h1>Title</h1>",
|
||||
" <p>Body</p>",
|
||||
" </section>",
|
||||
" );",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
});
|
||||
yield* writeTextFile(
|
||||
componentPath,
|
||||
[
|
||||
"export function View() {",
|
||||
" return (",
|
||||
" <section>",
|
||||
" {isReady ? (",
|
||||
" <div>",
|
||||
" <h1>Title</h1>",
|
||||
" <p>Body</p>",
|
||||
" </div>",
|
||||
" ) : null}",
|
||||
" </section>",
|
||||
" );",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const normalDiff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
|
||||
expect(normalDiff).toContain("diff --git");
|
||||
expect(normalDiff).toContain("- <h1>Title</h1>");
|
||||
expect(normalDiff).toContain("+ <h1>Title</h1>");
|
||||
expect(whitespaceIgnoredDiff).toContain("diff --git");
|
||||
expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
|
||||
expect(whitespaceIgnoredDiff).toContain("+ <div>");
|
||||
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
|
||||
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -259,10 +259,20 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
];
|
||||
|
||||
const result = yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
args: diffArgs,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface DiffCheckpointsInput {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteCheckpointRefsInput {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { spawnSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { expect } from "vitest";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
@@ -13,9 +14,10 @@ import type {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { type GitManagerShape } from "./GitManager.ts";
|
||||
import {
|
||||
GitHubCliError,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
GitHubCli,
|
||||
@@ -55,6 +57,16 @@ interface FakeGhScenario {
|
||||
failWith?: GitHubCliError;
|
||||
}
|
||||
|
||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
@@ -390,24 +402,15 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
? scenario.prListByHeadSelector?.[headSelector]
|
||||
: undefined;
|
||||
const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
|
||||
return Effect.succeed({
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
return Effect.succeed(fakeGhOutput(stdout));
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "create") {
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "view") {
|
||||
@@ -419,8 +422,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
headRefName: "feature/pull-request",
|
||||
state: "open",
|
||||
};
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
JSON.stringify({
|
||||
...pullRequest,
|
||||
...(pullRequest.headRepositoryNameWithOwner
|
||||
@@ -438,11 +441,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
: {}),
|
||||
}) + "\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "checkout") {
|
||||
@@ -464,13 +464,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
|
||||
}
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
return fakeGhOutput("");
|
||||
},
|
||||
catch: (error) =>
|
||||
isGitHubCliError(error)
|
||||
@@ -497,26 +491,17 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
JSON.stringify({
|
||||
nameWithOwner: repository,
|
||||
url: cloneUrls.url,
|
||||
sshUrl: cloneUrls.sshUrl,
|
||||
}) + "\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
),
|
||||
);
|
||||
}
|
||||
return Effect.succeed({
|
||||
stdout: `${scenario.defaultBranch ?? "main"}\n`,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
return Effect.succeed(fakeGhOutput(`${scenario.defaultBranch ?? "main"}\n`));
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
@@ -595,6 +580,13 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "createRepository",
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
@@ -660,6 +652,7 @@ function makeManager(input?: {
|
||||
GitHubSourceControlProvider.make().pipe(
|
||||
Effect.map((provider) =>
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
|
||||
get: () => Effect.succeed(provider),
|
||||
resolveHandle: () => Effect.succeed({ provider, context: null }),
|
||||
resolve: () => Effect.succeed(provider),
|
||||
}),
|
||||
@@ -883,7 +876,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
kind: "unknown",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
@@ -896,6 +888,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
@@ -913,7 +906,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
kind: "unknown",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
@@ -926,6 +918,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
@@ -1688,6 +1681,41 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes existing commits without committing dirty worktree changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/push-dirty"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "push-dirty.txt"), "push dirty\n");
|
||||
yield* runGit(repoDir, ["add", "push-dirty.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Push dirty branch"]);
|
||||
fs.mkdirSync(path.join(repoDir, ".vercel"));
|
||||
fs.writeFileSync(path.join(repoDir, ".vercel", "project.json"), "{}\n");
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "push",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("skipped_not_requested");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["status", "--porcelain"]).pipe(
|
||||
Effect.map((output) => output.stdout.trim()),
|
||||
),
|
||||
).toContain("?? .vercel/");
|
||||
expect(
|
||||
yield* runGit(remoteDir, ["log", "-1", "--pretty=%s", "feature/push-dirty"]).pipe(
|
||||
Effect.map((output) => output.stdout.trim()),
|
||||
),
|
||||
).toBe("Push dirty branch");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -2434,6 +2462,113 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"restores same-repository upstream tracking after local PR checkout without a remote ref",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-upstream"]);
|
||||
fs.writeFileSync(path.join(repoDir, "upstream.txt"), "upstream\n");
|
||||
yield* runGit(repoDir, ["add", "upstream.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Local upstream PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-upstream"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-upstream"]);
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"-d",
|
||||
"refs/remotes/origin/feature/pr-local-upstream",
|
||||
]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 65,
|
||||
title: "Local upstream PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/65",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-local-upstream",
|
||||
state: "open",
|
||||
isCrossRepository: false,
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
},
|
||||
repositoryCloneUrls: {
|
||||
"pingdotgg/codething-mvp": {
|
||||
url: remoteDir,
|
||||
sshUrl: remoteDir,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "65",
|
||||
mode: "local",
|
||||
});
|
||||
|
||||
expect(result.worktreePath).toBeNull();
|
||||
expect(result.branch).toBe("feature/pr-local-upstream");
|
||||
expect(
|
||||
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
|
||||
).toBe("origin/feature/pr-local-upstream");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"restores same-repository upstream tracking when provider omits head repository metadata",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-no-head-repo"]);
|
||||
fs.writeFileSync(path.join(repoDir, "no-head-repo.txt"), "upstream\n");
|
||||
yield* runGit(repoDir, ["add", "no-head-repo.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Local PR branch without repo metadata"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-no-head-repo"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-no-head-repo"]);
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"-d",
|
||||
"refs/remotes/origin/feature/pr-local-no-head-repo",
|
||||
]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 66,
|
||||
title: "Local upstream PR without repo metadata",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/66",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-local-no-head-repo",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "66",
|
||||
mode: "local",
|
||||
});
|
||||
|
||||
expect(result.worktreePath).toBeNull();
|
||||
expect(result.branch).toBe("feature/pr-local-no-head-repo");
|
||||
expect(
|
||||
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
|
||||
).toBe("origin/feature/pr-local-no-head-repo");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -3058,7 +3193,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect.objectContaining({
|
||||
kind: "hook_finished",
|
||||
hookName: "pre-commit",
|
||||
exitCode: 0,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "action_finished",
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Array as Arr,
|
||||
@@ -40,6 +39,10 @@ import {
|
||||
sanitizeBranchFragment,
|
||||
sanitizeFeatureBranchName,
|
||||
} from "@t3tools/shared/git";
|
||||
import {
|
||||
getChangeRequestTerminologyForKind,
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
|
||||
@@ -354,13 +357,14 @@ function withDescription(title: string, description: string | undefined) {
|
||||
|
||||
function summarizeGitActionResult(
|
||||
result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
|
||||
terms: ChangeRequestTerminology,
|
||||
): {
|
||||
title: string;
|
||||
description?: string;
|
||||
} {
|
||||
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
||||
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
|
||||
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
|
||||
const title = `${result.pr.status === "created" ? "Created" : "Opened"} ${terms.shortLabel}${prNumber}`;
|
||||
return withDescription(title, truncateText(result.pr.title));
|
||||
}
|
||||
|
||||
@@ -485,14 +489,6 @@ function normalizePullRequestReference(reference: string): string {
|
||||
return hashNumber?.[1] ?? trimmed;
|
||||
}
|
||||
|
||||
function canonicalizeExistingPath(value: string): string {
|
||||
try {
|
||||
return realpathSync.native(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function toResolvedPullRequest(pr: {
|
||||
number: number;
|
||||
title: string;
|
||||
@@ -572,6 +568,22 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
localBranch = pullRequest.headBranch,
|
||||
) {
|
||||
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
|
||||
if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {
|
||||
const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
|
||||
yield* gitCore.fetchRemoteTrackingBranch({
|
||||
cwd,
|
||||
remoteName,
|
||||
remoteBranch: pullRequest.headBranch,
|
||||
});
|
||||
yield* gitCore.setBranchUpstream({
|
||||
cwd,
|
||||
branch: localBranch,
|
||||
remoteName,
|
||||
remoteBranch: pullRequest.headBranch,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (repositoryNameWithOwner.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -592,6 +604,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
url: remoteUrl,
|
||||
});
|
||||
|
||||
yield* gitCore.fetchRemoteTrackingBranch({
|
||||
cwd,
|
||||
remoteName,
|
||||
remoteBranch: pullRequest.headBranch,
|
||||
});
|
||||
yield* gitCore.setBranchUpstream({
|
||||
cwd,
|
||||
branch: localBranch,
|
||||
@@ -680,7 +697,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
|
||||
const canonicalizeExistingPath = (value: string) =>
|
||||
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(value)));
|
||||
const normalizeStatusCacheKey = canonicalizeExistingPath;
|
||||
const nonRepositoryStatusDetails = {
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
@@ -692,6 +711,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
} satisfies GitStatusDetails;
|
||||
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
@@ -704,7 +724,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
: null;
|
||||
|
||||
return {
|
||||
kind: details.isRepo ? ("git" as const) : ("unknown" as const),
|
||||
isRepo: details.isRepo,
|
||||
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
|
||||
hasPrimaryRemote: details.hasOriginRemote,
|
||||
@@ -719,7 +738,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateLocalStatusResultCache = (cwd: string) =>
|
||||
Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
|
||||
);
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
.statusDetails(cwd)
|
||||
@@ -749,6 +770,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
||||
pr,
|
||||
} satisfies VcsStatusRemoteResult;
|
||||
});
|
||||
@@ -757,7 +779,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateRemoteStatusResultCache = (cwd: string) =>
|
||||
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),
|
||||
);
|
||||
|
||||
const readConfigValueNullable = (cwd: string, key: string) =>
|
||||
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
@@ -942,7 +966,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
cwd: string,
|
||||
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
||||
) {
|
||||
const summary = summarizeGitActionResult(result);
|
||||
const terms = yield* sourceControlProvider(cwd).pipe(
|
||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
||||
);
|
||||
const summary = summarizeGitActionResult(result, terms);
|
||||
let latestOpenPr: PullRequestInfo | null = null;
|
||||
let currentBranchIsDefault = false;
|
||||
let finalBranchContext: {
|
||||
@@ -1007,7 +1035,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
result.pr.status === "opened_existing")
|
||||
? {
|
||||
kind: "open_pr" as const,
|
||||
label: "View PR",
|
||||
label: `View ${terms.shortLabel}`,
|
||||
url: openPr.url,
|
||||
}
|
||||
: (result.action === "push" || result.action === "commit_push") &&
|
||||
@@ -1015,7 +1043,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
!currentBranchIsDefault
|
||||
? {
|
||||
kind: "run_action" as const,
|
||||
label: "Create PR",
|
||||
label: `Create ${terms.shortLabel}`,
|
||||
action: { kind: "create_pr" as const },
|
||||
}
|
||||
: {
|
||||
@@ -1223,6 +1251,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
fallbackBranch: string | null,
|
||||
emit: GitActionProgressEmitter,
|
||||
) {
|
||||
const provider = yield* sourceControlProvider(cwd);
|
||||
const terms = getChangeRequestTerminologyForKind(provider.kind);
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
@@ -1259,7 +1289,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: "Generating PR content...",
|
||||
label: `Generating ${terms.shortLabel} content...`,
|
||||
});
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
|
||||
|
||||
@@ -1284,9 +1314,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: "Creating pull request...",
|
||||
label: `Creating ${terms.singular}...`,
|
||||
});
|
||||
yield* (yield* sourceControlProvider(cwd))
|
||||
yield* provider
|
||||
.createChangeRequest({
|
||||
cwd,
|
||||
baseRefName: baseBranch,
|
||||
@@ -1317,11 +1347,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
});
|
||||
|
||||
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
|
||||
return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(localStatusResultCache, cacheKey);
|
||||
});
|
||||
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
|
||||
function* (input) {
|
||||
return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(remoteStatusResultCache, cacheKey);
|
||||
},
|
||||
);
|
||||
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
|
||||
@@ -1381,7 +1413,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
};
|
||||
return yield* Effect.gen(function* () {
|
||||
const normalizedReference = normalizePullRequestReference(input.reference);
|
||||
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
|
||||
const rootWorktreePath = yield* canonicalizeExistingPath(input.cwd);
|
||||
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizedReference,
|
||||
@@ -1431,33 +1463,35 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const localPullRequestBranch =
|
||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||
|
||||
const findLocalHeadBranch = (cwd: string) =>
|
||||
gitCore.listRefs({ cwd }).pipe(
|
||||
Effect.map((result) => {
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
);
|
||||
if (localBranch) {
|
||||
return localBranch;
|
||||
}
|
||||
if (localPullRequestBranch === pullRequest.headBranch) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
result.refs.find(
|
||||
(branch) =>
|
||||
!branch.isRemote &&
|
||||
branch.name === pullRequest.headBranch &&
|
||||
branch.worktreePath !== null &&
|
||||
canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath,
|
||||
) ?? null
|
||||
);
|
||||
}),
|
||||
const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
|
||||
const result = yield* gitCore.listRefs({ cwd });
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
);
|
||||
if (localBranch) {
|
||||
return localBranch;
|
||||
}
|
||||
if (localPullRequestBranch === pullRequest.headBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const branch of result.refs) {
|
||||
if (branch.isRemote || branch.name !== pullRequest.headBranch || !branch.worktreePath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const worktreePath = yield* canonicalizeExistingPath(branch.worktreePath);
|
||||
if (worktreePath !== rootWorktreePath) {
|
||||
return branch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
|
||||
const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
|
||||
? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
||||
? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
||||
: null;
|
||||
if (
|
||||
existingBranchBeforeFetch?.worktreePath &&
|
||||
@@ -1485,7 +1519,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
|
||||
const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
|
||||
? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
||||
? yield* canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
||||
: null;
|
||||
if (
|
||||
existingBranchAfterFetch?.worktreePath &&
|
||||
@@ -1582,12 +1616,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
"Feature-branch checkout is only supported for commit actions.",
|
||||
);
|
||||
}
|
||||
if (input.action === "push" && initialStatus.hasWorkingTreeChanges) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Commit or stash local changes before pushing.",
|
||||
);
|
||||
}
|
||||
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
@@ -1651,6 +1679,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
const commitAction = isCommitAction(input.action) ? input.action : null;
|
||||
const changeRequestTerms = wantsPr
|
||||
? yield* sourceControlProvider(input.cwd).pipe(
|
||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
||||
)
|
||||
: null;
|
||||
|
||||
const commit = commitAction
|
||||
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
||||
@@ -1688,7 +1722,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
.emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: "Preparing PR...",
|
||||
label: `Preparing ${changeRequestTerms?.shortLabel ?? "PR"}...`,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { describe, vi } from "vitest";
|
||||
|
||||
import { GitManager } from "./GitManager.ts";
|
||||
import { GitWorkflowService, layer as GitWorkflowServiceLayer } from "./GitWorkflowService.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { VcsDriverRegistry, type VcsDriverRegistryShape } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
function makeLayer(input: { readonly detect: VcsDriverRegistryShape["detect"] }) {
|
||||
return GitWorkflowServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
detect: input.detect,
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver)({})),
|
||||
Layer.provide(Layer.mock(GitManager)({})),
|
||||
);
|
||||
}
|
||||
|
||||
describe("GitWorkflowService", () => {
|
||||
it.effect("returns an empty local status when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const status = yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(status, {
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an empty full status when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const status = yield* workflow.status({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(status, {
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not call GitManager status methods when no VCS repository is detected", () => {
|
||||
const localStatus = vi.fn();
|
||||
const remoteStatus = vi.fn();
|
||||
const status = vi.fn();
|
||||
|
||||
const testLayer = GitWorkflowServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver)({})),
|
||||
Layer.provide(
|
||||
Layer.mock(GitManager)({
|
||||
localStatus,
|
||||
remoteStatus,
|
||||
status,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
||||
yield* workflow.remoteStatus({ cwd: "/not-a-repo" });
|
||||
yield* workflow.status({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.equal(localStatus.mock.calls.length, 0);
|
||||
assert.equal(remoteStatus.mock.calls.length, 0);
|
||||
assert.equal(status.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("returns an empty ref list when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const refs = yield* workflow.listRefs({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(refs, {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import { Context, Effect, Layer } from "effect";
|
||||
import {
|
||||
GitManagerError,
|
||||
GitCommandError,
|
||||
type VcsDriverKind,
|
||||
type VcsSwitchRefInput,
|
||||
type VcsSwitchRefResult,
|
||||
type VcsCreateRefInput,
|
||||
@@ -30,7 +29,6 @@ import {
|
||||
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
export interface GitWorkflowServiceShape {
|
||||
readonly status: (
|
||||
@@ -67,7 +65,6 @@ export interface GitWorkflowServiceShape {
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly initRepo: (input: { readonly cwd: string }) => Effect.Effect<void, GitCommandError>;
|
||||
readonly renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
@@ -94,17 +91,41 @@ const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =
|
||||
detail,
|
||||
});
|
||||
|
||||
const emptyWorkingTree = { files: [], insertions: 0, deletions: 0 } as const;
|
||||
function nonRepositoryLocalStatus(): VcsStatusLocalResult {
|
||||
return {
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const nonGitLocalStatus = (kind: VcsDriverKind, isRepo: boolean): VcsStatusLocalResult => ({
|
||||
kind,
|
||||
isRepo,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: emptyWorkingTree,
|
||||
});
|
||||
function nonRepositoryStatus(): VcsStatusResult {
|
||||
return {
|
||||
...nonRepositoryLocalStatus(),
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
}
|
||||
|
||||
function nonRepositoryListRefs(): VcsListRefsResult {
|
||||
return {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
@@ -159,6 +180,60 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
|
||||
function* (operation: string, cwd: string) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return false;
|
||||
}
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
const detectGitRepositoryForCommand = Effect.fn(
|
||||
"GitWorkflowService.detectGitRepositoryForCommand",
|
||||
)(function* (operation: string, cwd: string) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return false;
|
||||
}
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const routeGitManager =
|
||||
<Input extends { readonly cwd: string }, Output>(
|
||||
operation: string,
|
||||
@@ -167,60 +242,27 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
(input: Input) =>
|
||||
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
|
||||
|
||||
const localStatus: GitWorkflowServiceShape["localStatus"] = Effect.fn(
|
||||
"GitWorkflowService.localStatus",
|
||||
)(function* (input) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd: input.cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
"GitWorkflowService.localStatus",
|
||||
input.cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return nonGitLocalStatus("unknown", false);
|
||||
}
|
||||
if (handle.kind === "git") {
|
||||
return yield* gitManager.localStatus(input);
|
||||
}
|
||||
return nonGitLocalStatus(handle.kind, true);
|
||||
});
|
||||
|
||||
const remoteStatus: GitWorkflowServiceShape["remoteStatus"] = Effect.fn(
|
||||
"GitWorkflowService.remoteStatus",
|
||||
)(function* (input) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd: input.cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
"GitWorkflowService.remoteStatus",
|
||||
input.cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (handle?.kind === "git") {
|
||||
return yield* gitManager.remoteStatus(input);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const status: GitWorkflowServiceShape["status"] = Effect.fn("GitWorkflowService.status")(
|
||||
function* (input) {
|
||||
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
},
|
||||
);
|
||||
|
||||
return GitWorkflowService.of({
|
||||
status,
|
||||
localStatus,
|
||||
remoteStatus,
|
||||
status: (input) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
|
||||
),
|
||||
),
|
||||
localStatus: (input) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository
|
||||
? gitManager.localStatus(input)
|
||||
: Effect.succeed(nonRepositoryLocalStatus()),
|
||||
),
|
||||
),
|
||||
remoteStatus: (input) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? gitManager.remoteStatus(input) : Effect.succeed(null),
|
||||
),
|
||||
),
|
||||
invalidateLocalStatus: gitManager.invalidateLocalStatus,
|
||||
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
|
||||
invalidateStatus: gitManager.invalidateStatus,
|
||||
@@ -241,8 +283,10 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
gitManager.preparePullRequestThread,
|
||||
),
|
||||
listRefs: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.andThen(git.listRefs(input)),
|
||||
detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
|
||||
),
|
||||
),
|
||||
createWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
@@ -260,7 +304,6 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
|
||||
Effect.andThen(Effect.scoped(git.switchRef(input))),
|
||||
),
|
||||
initRepo: (input) => git.initRepo(input),
|
||||
renameBranch: (input) =>
|
||||
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
|
||||
Effect.andThen(git.renameBranch(input)),
|
||||
|
||||
@@ -291,7 +291,6 @@ describe("CheckpointReactor", () => {
|
||||
}).pipe(
|
||||
Effect.as({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
|
||||
@@ -237,6 +237,7 @@ const make = Effect.gen(function* () {
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
|
||||
@@ -240,7 +240,6 @@ describe("ProviderCommandReactor", () => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "renamed-branch",
|
||||
|
||||
@@ -54,17 +54,6 @@ import { vi } from "vitest";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const testGitRepository = (rootPath: string) => ({
|
||||
kind: "git" as const,
|
||||
rootPath,
|
||||
metadataPath: null,
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
});
|
||||
|
||||
import type { ServerConfigShape } from "./config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "./config.ts";
|
||||
import { makeRoutesLayer } from "./server.ts";
|
||||
@@ -126,7 +115,12 @@ import {
|
||||
type VcsDriverRegistryShape,
|
||||
type VcsDriverHandle,
|
||||
} from "./vcs/VcsDriverRegistry.ts";
|
||||
import { layer as VcsProvisioningServiceLayer } from "./vcs/VcsProvisioningService.ts";
|
||||
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
|
||||
import {
|
||||
SourceControlRepositoryService,
|
||||
type SourceControlRepositoryServiceShape,
|
||||
} from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
|
||||
@@ -340,6 +334,7 @@ const buildAppUnderTest = (options?: {
|
||||
vcsDriverRegistry?: Partial<VcsDriverRegistryShape>;
|
||||
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
sourceControlRepositoryService?: Partial<SourceControlRepositoryServiceShape>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
@@ -425,9 +420,11 @@ const buildAppUnderTest = (options?: {
|
||||
},
|
||||
}),
|
||||
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
|
||||
initRepository: () => Effect.void,
|
||||
...options?.layers?.vcsDriver,
|
||||
};
|
||||
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry)({
|
||||
get: () => Effect.succeed(defaultVcsDriver),
|
||||
detect: (input) =>
|
||||
defaultVcsDriver.detectRepository(input.cwd).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
@@ -503,6 +500,9 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provideMerge(gitManagerLayer),
|
||||
);
|
||||
const vcsProvisioningLayer = VcsProvisioningServiceLayer.pipe(
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster)({
|
||||
...options.layers.vcsStatusBroadcaster,
|
||||
@@ -549,6 +549,12 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlRepositoryService)({
|
||||
...options?.layers?.sourceControlRepositoryService,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectSetupScriptRunner)({
|
||||
@@ -2377,9 +2383,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
|
||||
},
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
@@ -2387,7 +2390,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2404,7 +2406,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
status: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2517,7 +2518,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
removeWorktree: () => Effect.void,
|
||||
createRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
switchRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
initRepo: () => Effect.void,
|
||||
},
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2659,7 +2662,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2681,7 +2683,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2738,7 +2739,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -2760,7 +2760,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -2798,9 +2797,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
|
||||
},
|
||||
gitVcsDriver: {
|
||||
pullCurrentBranch: () =>
|
||||
Effect.succeed({
|
||||
@@ -2815,7 +2811,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2854,7 +2849,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
},
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
@@ -2862,7 +2857,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -2931,7 +2925,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
},
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
@@ -2942,7 +2936,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.andThen(
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -3609,7 +3602,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "t3code/bootstrap-refName",
|
||||
|
||||
@@ -26,6 +26,7 @@ import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
|
||||
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
|
||||
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
|
||||
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
|
||||
@@ -49,9 +50,11 @@ import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
|
||||
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
|
||||
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
|
||||
@@ -159,15 +162,15 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProjectConfig.layer),
|
||||
);
|
||||
|
||||
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
);
|
||||
|
||||
const GitManagerLayerLive = GitManager.layer.pipe(
|
||||
Layer.provideMerge(ProjectSetupScriptRunnerLive),
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(
|
||||
SourceControlProviderRegistry.layer.pipe(
|
||||
Layer.provide(GitHubCli.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(TextGeneration.layer),
|
||||
);
|
||||
|
||||
@@ -181,10 +184,17 @@ const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
);
|
||||
|
||||
const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(VcsProjectConfig.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,53 +1,64 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError, type VcsError } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
|
||||
const mockedRunProcess = vi.mocked(runProcess);
|
||||
const layer = it.layer(GitHubCli.layer);
|
||||
|
||||
afterEach(() => {
|
||||
mockedRunProcess.mockReset();
|
||||
const processOutput = (stdout: string): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
layer("GitHubCli.layer", (it) => {
|
||||
const mockRun = vi.fn<(input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>>();
|
||||
|
||||
const layer = GitHubCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: mockRun,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
mockRun.mockReset();
|
||||
});
|
||||
|
||||
describe("GitHubCli.layer", () => {
|
||||
it.effect("parses pull request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: "octocat",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: "octocat",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -61,51 +72,51 @@ layer("GitHubCli.layer", (it) => {
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"gh",
|
||||
[
|
||||
expect(mockRun).toHaveBeenCalledWith({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: [
|
||||
"pr",
|
||||
"view",
|
||||
"#42",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
expect.objectContaining({ cwd: "/repo" }),
|
||||
);
|
||||
}),
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -119,46 +130,44 @@ layer("GitHubCli.layer", (it) => {
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}),
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
@@ -171,29 +180,27 @@ layer("GitHubCli.layer", (it) => {
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
});
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -201,26 +208,85 @@ layer("GitHubCli.layer", (it) => {
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
}),
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("creates repositories and parses clone URLs from create output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
"✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
expect(mockRun).toHaveBeenCalledTimes(1);
|
||||
expect(mockRun).toHaveBeenNthCalledWith(1, {
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: ["repo", "create", "octocat/codething-mvp", "--private"],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("falls back to constructed URLs when create output omits a URL", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the pull request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockRejectedValueOnce(
|
||||
new Error(
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh pr view",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail:
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const error = yield* gh
|
||||
.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "4888",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Pull request not found"), true);
|
||||
}),
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,17 +1,30 @@
|
||||
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
|
||||
import { GitHubCliError, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { ProcessRunResult } from "../processRunner.ts";
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../git/githubPullRequests.ts";
|
||||
} from "./gitHubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
@@ -35,7 +48,7 @@ export interface GitHubCliShape {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
|
||||
}) => Effect.Effect<VcsProcessOutput, GitHubCliError>;
|
||||
|
||||
readonly listOpenPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
@@ -53,6 +66,12 @@ export interface GitHubCliShape {
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
@@ -76,53 +95,61 @@ export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/source-control/GitHubCli",
|
||||
) {}
|
||||
|
||||
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: gh")) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
function normalizeGitHubCliError(
|
||||
operation: "execute" | "stdout",
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const text = errorText(error);
|
||||
const lower = text.toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: `GitHub CLI command failed: ${error.message}`,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI command failed.",
|
||||
detail: text,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -143,6 +170,43 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `gh repo create` prints the canonical URL of the new repository on stdout
|
||||
* (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
|
||||
* follow-up `gh repo view`, which can race GitHub's GraphQL eventual
|
||||
* consistency window and falsely report the just-created repo as missing.
|
||||
*/
|
||||
function deriveRepositoryCloneUrlsFromCreateOutput(
|
||||
stdout: string,
|
||||
repository: string,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
const fallbackHost = "github.com";
|
||||
const match = stdout.match(/https?:\/\/[^\s]+/);
|
||||
if (match) {
|
||||
const cleaned = match[0].replace(/\.git$/, "");
|
||||
try {
|
||||
const parsed = new URL(cleaned);
|
||||
const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
|
||||
const segments = pathname.split("/").filter(Boolean);
|
||||
if (segments.length === 2) {
|
||||
const nameWithOwner = `${segments[0]}/${segments[1]}`;
|
||||
return {
|
||||
nameWithOwner,
|
||||
url: `${parsed.origin}/${nameWithOwner}`,
|
||||
sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the input-derived defaults below.
|
||||
}
|
||||
}
|
||||
return {
|
||||
nameWithOwner: repository,
|
||||
url: `https://${fallbackHost}/${repository}`,
|
||||
sshUrl: `git@${fallbackHost}:${repository}.git`,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitHubJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
@@ -161,16 +225,19 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.sync(() => {
|
||||
export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
|
||||
const execute: GitHubCliShape["execute"] = (input) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("gh", input.args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
});
|
||||
process
|
||||
.run({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitHubCliError("execute", error)));
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
@@ -261,6 +328,15 @@ export const make = Effect.sync(() => {
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "create", input.repository, `--${input.visibility}`],
|
||||
}).pipe(
|
||||
Effect.map((result) =>
|
||||
deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
|
||||
),
|
||||
),
|
||||
createPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
@@ -295,4 +371,4 @@ export const make = Effect.sync(() => {
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitHubCli, make);
|
||||
export const layer = Layer.effect(GitHubCli, make());
|
||||
@@ -1,15 +1,17 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitHubCli, type GitHubCliShape } from "./GitHubCli.ts";
|
||||
import type { VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
|
||||
const processResult = (stdout: string) => ({
|
||||
const processResult = (stdout: string): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
function makeProvider(github: Partial<GitHubCliShape>) {
|
||||
|
||||
@@ -3,11 +3,10 @@ import {
|
||||
SourceControlProviderError,
|
||||
type ChangeRequest,
|
||||
type ChangeRequestState,
|
||||
type GitHubCliError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitHubCli, type GitHubPullRequestSummary } from "./GitHubCli.ts";
|
||||
import { decodeGitHubPullRequestListJson } from "../git/githubPullRequests.ts";
|
||||
import { GitHubCli, type GitHubCliError, type GitHubPullRequestSummary } from "./GitHubCli.ts";
|
||||
import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
|
||||
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
|
||||
|
||||
function providerError(operation: string, cause: GitHubCliError): SourceControlProviderError {
|
||||
@@ -131,6 +130,10 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
|
||||
github
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
github
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
github
|
||||
.getDefaultBranch(input)
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import { VcsProcess, type VcsProcessOutput, type VcsProcessShape } from "../vcs/VcsProcess.ts";
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
|
||||
const mockedRun = vi.fn<VcsProcessShape["run"]>();
|
||||
const layer = it.layer(
|
||||
GitLabCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: mockedRun,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function processOutput(stdout: string): VcsProcessOutput {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
mockedRun.mockReset();
|
||||
});
|
||||
|
||||
layer("GitLabCli.layer", (it) => {
|
||||
it.effect("parses merge request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
iid: 42,
|
||||
title: "Add MR thread creation",
|
||||
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
target_branch: "main",
|
||||
source_branch: "feature/mr-threads",
|
||||
state: "opened",
|
||||
source_project_id: 101,
|
||||
target_project_id: 100,
|
||||
source_project: {
|
||||
path_with_namespace: "octocat/t3code",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add MR thread creation",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/mr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/t3code",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["mr", "view", "42", "--output", "json"],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing MR lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify([
|
||||
{
|
||||
iid: 0,
|
||||
title: "invalid",
|
||||
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
|
||||
target_branch: "main",
|
||||
source_branch: "feature/invalid",
|
||||
},
|
||||
{
|
||||
iid: 43,
|
||||
title: " Valid MR ",
|
||||
web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
|
||||
target_branch: " main ",
|
||||
source_branch: " feature/mr-list ",
|
||||
state: "merged",
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.listMergeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/mr-list",
|
||||
state: "all",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid MR",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/mr-list",
|
||||
state: "merged",
|
||||
},
|
||||
]);
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"mr",
|
||||
"list",
|
||||
"--source-branch",
|
||||
"feature/mr-list",
|
||||
"--all",
|
||||
"--per-page",
|
||||
"20",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
path_with_namespace: "octocat/t3code",
|
||||
web_url: "https://gitlab.com/octocat/t3code",
|
||||
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
|
||||
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/t3code",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates merge requests through the GitLab API without placing the body in argv", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
yield* glab.createMergeRequest({
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/t3-mr-body.md",
|
||||
});
|
||||
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects/:fullpath/merge_requests",
|
||||
"--raw-field",
|
||||
"source_branch=feature/provider",
|
||||
"--raw-field",
|
||||
"target_branch=main",
|
||||
"--raw-field",
|
||||
"title=Provider MR",
|
||||
"--field",
|
||||
"description=@/tmp/t3-mr-body.md",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates repositories under an explicit namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun
|
||||
.mockReturnValueOnce(Effect.succeed(processOutput(JSON.stringify({ id: 1234 }))))
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
path_with_namespace: "octocat/t3code",
|
||||
web_url: "https://gitlab.com/octocat/t3code",
|
||||
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
|
||||
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
const result = yield* glab.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "public",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["api", "namespaces/octocat"],
|
||||
}),
|
||||
);
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
"path=t3code",
|
||||
"--raw-field",
|
||||
"name=t3code",
|
||||
"--raw-field",
|
||||
"visibility=public",
|
||||
"--raw-field",
|
||||
"namespace_id=1234",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not pass unsupported force flags when checking out merge requests", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
yield* glab.checkoutMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
force: true,
|
||||
});
|
||||
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["mr", "checkout", "42"],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the merge request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab mr view 4888",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "4888",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,444 @@
|
||||
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
|
||||
|
||||
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
decodeGitLabMergeRequestJson,
|
||||
decodeGitLabMergeRequestListJson,
|
||||
formatGitLabJsonDecodeError,
|
||||
} from "./gitLabMergeRequests.ts";
|
||||
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import type { SourceControlRefSelector } from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state?: "open" | "closed" | "merged";
|
||||
readonly updatedAt?: Option.Option<DateTime.Utc>;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
export interface GitLabRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
export interface GitLabCliShape {
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<VcsProcessOutput, GitLabCliError>;
|
||||
|
||||
readonly listMergeRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
readonly state: "open" | "closed" | "merged" | "all";
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
|
||||
|
||||
readonly getMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
|
||||
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
readonly target?: SourceControlRefSelector;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, GitLabCliError>;
|
||||
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string | null, GitLabCliError>;
|
||||
|
||||
readonly checkoutMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly force?: boolean;
|
||||
}) => Effect.Effect<void, GitLabCliError>;
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<GitLabCli, GitLabCliShape>()(
|
||||
"t3/source-control/GitLabCli",
|
||||
) {}
|
||||
|
||||
function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "VcsProcessSpawnError"
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGitLabCliError(operation: "execute" | "stdout", error: unknown): GitLabCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: `GitLab CLI command failed: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
path_with_namespace: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
http_url_to_repo: TrimmedNonEmptyString,
|
||||
ssh_url_to_repo: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const RawGitLabDefaultBranchSchema = Schema.Struct({
|
||||
default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
});
|
||||
|
||||
const RawGitLabNamespaceSchema = Schema.Struct({
|
||||
id: Schema.Number,
|
||||
});
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
return {
|
||||
nameWithOwner: raw.path_with_namespace,
|
||||
url: raw.web_url,
|
||||
sshUrl: raw.ssh_url_to_repo,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitLabJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitLabCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return [];
|
||||
case "closed":
|
||||
return ["--closed"];
|
||||
case "merged":
|
||||
return ["--merged"];
|
||||
case "all":
|
||||
return ["--all"];
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHeadSelector(headSelector: string): string {
|
||||
const trimmed = headSelector.trim();
|
||||
const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
|
||||
return ownerBranch?.[1]?.trim() || trimmed;
|
||||
}
|
||||
|
||||
function sourceRefName(input: {
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
}): string {
|
||||
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
|
||||
}
|
||||
|
||||
function sourceProjectIdentifier(source: SourceControlRefSelector | undefined): string | null {
|
||||
return source?.repository ?? source?.owner ?? null;
|
||||
}
|
||||
|
||||
function toSummaryWithOptionalUpdatedAt(
|
||||
record: GitLabMergeRequestSummary & {
|
||||
readonly updatedAt: Option.Option<DateTime.Utc>;
|
||||
},
|
||||
): GitLabMergeRequestSummary {
|
||||
const { updatedAt, ...summary } = record;
|
||||
return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
|
||||
}
|
||||
|
||||
function parseRepositoryPath(repository: string): {
|
||||
readonly namespacePath: string | null;
|
||||
readonly projectPath: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const projectPath = parts.at(-1) ?? repository.trim();
|
||||
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
|
||||
return { namespacePath, projectPath };
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitLabCli")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
|
||||
const execute: GitLabCliShape["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
listMergeRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"mr",
|
||||
"list",
|
||||
"--source-branch",
|
||||
sourceRefName(input),
|
||||
...stateArgs(input.state),
|
||||
"--per-page",
|
||||
String(input.limit ?? 20),
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "listMergeRequests",
|
||||
detail: `GitLab CLI returned invalid MR list JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["mr", "view", input.reference, "--output", "json"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "getMergeRequest",
|
||||
detail: `GitLab CLI returned invalid merge request JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", `projects/${encodeURIComponent(input.repository)}`],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) => {
|
||||
const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
|
||||
const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
|
||||
? execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
)
|
||||
: Effect.succeed(null);
|
||||
|
||||
return namespaceId.pipe(
|
||||
Effect.flatMap((resolvedNamespaceId) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
`path=${projectPath}`,
|
||||
"--raw-field",
|
||||
`name=${projectPath}`,
|
||||
"--raw-field",
|
||||
`visibility=${input.visibility}`,
|
||||
...(resolvedNamespaceId === null
|
||||
? []
|
||||
: ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
|
||||
],
|
||||
}),
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
},
|
||||
createMergeRequest: (input) => {
|
||||
const sourceProject = sourceProjectIdentifier(input.source);
|
||||
return execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects/:fullpath/merge_requests",
|
||||
"--raw-field",
|
||||
`source_branch=${sourceRefName(input)}`,
|
||||
"--raw-field",
|
||||
`target_branch=${input.target?.refName ?? input.baseBranch}`,
|
||||
...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
|
||||
"--raw-field",
|
||||
`title=${input.title}`,
|
||||
"--field",
|
||||
`description=@${input.bodyFile}`,
|
||||
],
|
||||
}).pipe(Effect.asVoid);
|
||||
},
|
||||
getDefaultBranch: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", "projects/:fullpath"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitLabCli, make());
|
||||
@@ -0,0 +1,105 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import { GitLabCli, type GitLabCliShape } from "./GitLabCli.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
|
||||
function makeProvider(gitlab: Partial<GitLabCliShape>) {
|
||||
return GitLabSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitLabCli)(gitlab)));
|
||||
}
|
||||
|
||||
it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
getMergeRequest: () =>
|
||||
Effect.succeed({
|
||||
number: 42,
|
||||
title: "Add GitLab provider",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
}),
|
||||
});
|
||||
|
||||
const changeRequest = yield* provider.getChangeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequest, {
|
||||
provider: "gitlab",
|
||||
number: 42,
|
||||
title: "Add GitLab provider",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let listInput: Parameters<GitLabCliShape["listMergeRequests"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
listMergeRequests: (input) => {
|
||||
listInput = input;
|
||||
return Effect.succeed([]);
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(listInput, {
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<GitLabCliShape["createMergeRequest"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
createMergeRequest: (input) => {
|
||||
createInput = input;
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.createChangeRequest({
|
||||
cwd: "/repo",
|
||||
baseRefName: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(createInput, {
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
source: {
|
||||
owner: "owner",
|
||||
refName: "feature/provider",
|
||||
},
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
import { GitLabCli, type GitLabCliError, type GitLabMergeRequestSummary } from "./GitLabCli.ts";
|
||||
import { SourceControlProvider, type SourceControlRefSelector } from "./SourceControlProvider.ts";
|
||||
|
||||
function providerError(operation: string, cause: GitLabCliError): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: GitLabMergeRequestSummary): ChangeRequest {
|
||||
return {
|
||||
provider: "gitlab",
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
url: summary.url,
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state ?? "open",
|
||||
updatedAt: summary.updatedAt ?? Option.none(),
|
||||
...(summary.isCrossRepository !== undefined
|
||||
? { isCrossRepository: summary.isCrossRepository }
|
||||
: {}),
|
||||
...(summary.headRepositoryNameWithOwner !== undefined
|
||||
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
|
||||
: {}),
|
||||
...(summary.headRepositoryOwnerLogin !== undefined
|
||||
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function sourceFromInput(input: {
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
}): SourceControlRefSelector | undefined {
|
||||
if (input.source) {
|
||||
return input.source;
|
||||
}
|
||||
|
||||
const match = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
|
||||
const owner = match?.[1]?.trim();
|
||||
const refName = match?.[2]?.trim();
|
||||
return owner && refName ? { owner, refName } : undefined;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
|
||||
const gitlab = yield* GitLabCli;
|
||||
|
||||
return SourceControlProvider.of({
|
||||
kind: "gitlab",
|
||||
listChangeRequests: (input) => {
|
||||
const source = sourceFromInput(input);
|
||||
return gitlab
|
||||
.listMergeRequests({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
state: input.state,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
gitlab.getMergeRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = sourceFromInput(input);
|
||||
return gitlab
|
||||
.createMergeRequest({
|
||||
cwd: input.cwd,
|
||||
baseBranch: input.baseRefName,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
...(input.target ? { target: input.target } : {}),
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
gitlab
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
gitlab
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
gitlab
|
||||
.getDefaultBranch(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
checkoutChangeRequest: (input) =>
|
||||
gitlab
|
||||
.checkoutMergeRequest(input)
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProvider, make());
|
||||
@@ -73,7 +73,7 @@ Logged in to github.com account juliusmarminge (keyring)
|
||||
})),
|
||||
[
|
||||
{ kind: "git", implemented: true, status: "available" },
|
||||
{ kind: "jj", implemented: true, status: "missing" },
|
||||
{ kind: "jj", implemented: false, status: "missing" },
|
||||
],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
@@ -94,7 +94,7 @@ Logged in to github.com account juliusmarminge (keyring)
|
||||
},
|
||||
{
|
||||
kind: "gitlab",
|
||||
implemented: false,
|
||||
implemented: true,
|
||||
status: "missing",
|
||||
auth: "unknown",
|
||||
account: Option.none(),
|
||||
@@ -115,6 +115,9 @@ Logged in to github.com account juliusmarminge (keyring)
|
||||
},
|
||||
],
|
||||
);
|
||||
const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");
|
||||
assert.ok(bitbucket);
|
||||
assert.strictEqual("executable" in bitbucket, false);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
@@ -204,9 +207,9 @@ Logged in as bitbucket-user
|
||||
},
|
||||
{
|
||||
kind: "bitbucket",
|
||||
auth: "authenticated",
|
||||
account: Option.some("bitbucket-user"),
|
||||
detail: Option.none(),
|
||||
auth: "unknown",
|
||||
account: Option.none(),
|
||||
detail: Option.some("Bitbucket provider support is not available yet."),
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
@@ -13,20 +13,22 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
|
||||
interface DiscoveryProbe {
|
||||
readonly label: string;
|
||||
readonly executable: string;
|
||||
readonly versionArgs: ReadonlyArray<string>;
|
||||
readonly executable?: string;
|
||||
readonly versionArgs?: ReadonlyArray<string>;
|
||||
readonly implemented: boolean;
|
||||
readonly installHint: string;
|
||||
}
|
||||
|
||||
type VcsProbe = DiscoveryProbe & {
|
||||
readonly kind: VcsDriverKind;
|
||||
readonly executable: string;
|
||||
readonly versionArgs: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
type ProviderProbe = DiscoveryProbe & {
|
||||
readonly kind: SourceControlProviderKind;
|
||||
readonly authArgs: ReadonlyArray<string>;
|
||||
readonly parseAuth: (input: AuthProbeInput) => SourceControlProviderAuth;
|
||||
readonly authArgs?: ReadonlyArray<string>;
|
||||
readonly parseAuth?: (input: AuthProbeInput) => SourceControlProviderAuth;
|
||||
};
|
||||
|
||||
interface AuthProbeInput {
|
||||
@@ -38,7 +40,7 @@ interface AuthProbeInput {
|
||||
interface DiscoveryProbeResult<Kind extends string> {
|
||||
readonly kind: Kind;
|
||||
readonly label: string;
|
||||
readonly executable: string;
|
||||
readonly executable?: string;
|
||||
readonly implemented: boolean;
|
||||
readonly status: "available" | "missing";
|
||||
readonly version: Option.Option<string>;
|
||||
@@ -60,7 +62,7 @@ const VCS_PROBES: ReadonlyArray<VcsProbe> = [
|
||||
label: "Jujutsu",
|
||||
executable: "jj",
|
||||
versionArgs: ["--version"],
|
||||
implemented: true,
|
||||
implemented: false,
|
||||
installHint: "Install Jujutsu with `brew install jj` or from https://github.com/jj-vcs/jj.",
|
||||
},
|
||||
];
|
||||
@@ -83,7 +85,7 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["auth", "status"],
|
||||
parseAuth: parseGitLabAuth,
|
||||
implemented: false,
|
||||
implemented: true,
|
||||
installHint:
|
||||
"Install GitLab CLI with `brew install glab` or from https://gitlab.com/gitlab-org/cli.",
|
||||
},
|
||||
@@ -101,12 +103,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
|
||||
{
|
||||
kind: "bitbucket",
|
||||
label: "Bitbucket",
|
||||
executable: "bb",
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["auth", "status"],
|
||||
parseAuth: parseBitbucketAuth,
|
||||
implemented: false,
|
||||
installHint: "Install a Bitbucket CLI (`bb`) and authenticate it for your Bitbucket workspace.",
|
||||
installHint: "Bitbucket provider support is not available yet.",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -266,37 +264,6 @@ function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth {
|
||||
});
|
||||
}
|
||||
|
||||
function parseBitbucketAuth(input: AuthProbeInput): SourceControlProviderAuth {
|
||||
const output = combinedAuthOutput(input);
|
||||
const account = matchFirst(output, [
|
||||
/Logged in to .* as\s+([^\s(]+)/iu,
|
||||
/Logged in as\s+([^\s(]+)/iu,
|
||||
/account:\s*([^\s(]+)/iu,
|
||||
/user:\s*([^\s(]+)/iu,
|
||||
/username:\s*([^\s(]+)/iu,
|
||||
]);
|
||||
const host = parseCliHost(output) ?? "bitbucket.org";
|
||||
|
||||
if (input.exitCode !== 0) {
|
||||
return providerAuth({
|
||||
status: "unauthenticated",
|
||||
host,
|
||||
detail:
|
||||
firstSafeAuthLine(output) ?? "Authenticate the Bitbucket CLI before enabling Bitbucket.",
|
||||
});
|
||||
}
|
||||
|
||||
if (account) {
|
||||
return providerAuth({ status: "authenticated", account, host });
|
||||
}
|
||||
|
||||
return providerAuth({
|
||||
status: "unknown",
|
||||
host,
|
||||
detail: firstSafeAuthLine(output) ?? "Bitbucket CLI auth status could not be parsed.",
|
||||
});
|
||||
}
|
||||
|
||||
export interface SourceControlDiscoveryShape {
|
||||
readonly discover: Effect.Effect<SourceControlDiscoveryResult>;
|
||||
}
|
||||
@@ -314,12 +281,27 @@ export const layer = Layer.effect(
|
||||
|
||||
const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
|
||||
input: DiscoveryProbe & { readonly kind: Kind },
|
||||
): Effect.Effect<DiscoveryProbeResult<Kind>> =>
|
||||
process
|
||||
): Effect.Effect<DiscoveryProbeResult<Kind>> => {
|
||||
const executable = input.executable;
|
||||
const versionArgs = input.versionArgs;
|
||||
|
||||
if (!executable || !versionArgs) {
|
||||
return Effect.succeed({
|
||||
kind: input.kind,
|
||||
label: input.label,
|
||||
implemented: input.implemented,
|
||||
status: "missing" as const,
|
||||
version: Option.none<string>(),
|
||||
installHint: input.installHint,
|
||||
detail: Option.some(input.installHint),
|
||||
} satisfies DiscoveryProbeResult<Kind>);
|
||||
}
|
||||
|
||||
return process
|
||||
.run({
|
||||
operation: "source-control.discovery.probe",
|
||||
command: input.executable,
|
||||
args: input.versionArgs,
|
||||
command: executable,
|
||||
args: versionArgs,
|
||||
cwd: config.cwd,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 8_000,
|
||||
@@ -331,7 +313,7 @@ export const layer = Layer.effect(
|
||||
({
|
||||
kind: input.kind,
|
||||
label: input.label,
|
||||
executable: input.executable,
|
||||
executable,
|
||||
implemented: input.implemented,
|
||||
status: "available" as const,
|
||||
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
|
||||
@@ -345,7 +327,7 @@ export const layer = Layer.effect(
|
||||
Effect.succeed({
|
||||
kind: input.kind,
|
||||
label: input.label,
|
||||
executable: input.executable,
|
||||
executable,
|
||||
implemented: input.implemented,
|
||||
status: "missing" as const,
|
||||
version: Option.none<string>(),
|
||||
@@ -354,10 +336,22 @@ export const layer = Layer.effect(
|
||||
} satisfies DiscoveryProbeResult<Kind>),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const probeProvider = (input: ProviderProbe) =>
|
||||
probe(input).pipe(
|
||||
Effect.flatMap((item) => {
|
||||
const executable = input.executable;
|
||||
const authArgs = input.authArgs;
|
||||
const parseAuth = input.parseAuth;
|
||||
|
||||
if (!executable || !authArgs || !parseAuth) {
|
||||
return Effect.succeed({
|
||||
...item,
|
||||
auth: unknownAuth(input.installHint),
|
||||
} satisfies SourceControlProviderDiscoveryItem);
|
||||
}
|
||||
|
||||
if (item.status !== "available") {
|
||||
return Effect.succeed({
|
||||
...item,
|
||||
@@ -368,8 +362,8 @@ export const layer = Layer.effect(
|
||||
return process
|
||||
.run({
|
||||
operation: "source-control.discovery.auth",
|
||||
command: input.executable,
|
||||
args: input.authArgs,
|
||||
command: executable,
|
||||
args: authArgs,
|
||||
cwd: config.cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
@@ -381,7 +375,7 @@ export const layer = Layer.effect(
|
||||
(result) =>
|
||||
({
|
||||
...item,
|
||||
auth: input.parseAuth(result),
|
||||
auth: parseAuth(result),
|
||||
}) satisfies SourceControlProviderDiscoveryItem,
|
||||
),
|
||||
Effect.catch((cause) =>
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
SourceControlProviderInfo,
|
||||
SourceControlProviderKind,
|
||||
SourceControlRepositoryCloneUrls,
|
||||
SourceControlRepositoryVisibility,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface SourceControlProviderContext {
|
||||
@@ -50,6 +51,11 @@ export interface SourceControlProviderShape {
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
|
||||
import { GitHubCli } from "./GitHubCli.ts";
|
||||
import { GitLabCli } from "./GitLabCli.ts";
|
||||
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
|
||||
@@ -31,6 +32,7 @@ function makeRegistry(input: {
|
||||
} satisfies Partial<VcsDriverShape>;
|
||||
|
||||
const registryLayer = Layer.mock(VcsDriverRegistry)({
|
||||
get: () => Effect.succeed(driver as unknown as VcsDriverShape),
|
||||
resolve: () =>
|
||||
Effect.succeed({
|
||||
kind: "git",
|
||||
@@ -49,7 +51,9 @@ function makeRegistry(input: {
|
||||
});
|
||||
|
||||
return SourceControlProviderRegistry.make().pipe(
|
||||
Effect.provide(Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}))),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}), Layer.mock(GitLabCli)({})),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -65,27 +69,28 @@ it.effect("routes GitHub remotes to the GitHub provider", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"detects GitLab remotes and returns an unsupported provider until one is registered",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
|
||||
});
|
||||
it.effect("routes directly by provider kind for remote-first workflows", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [],
|
||||
});
|
||||
|
||||
const provider = yield* registry.resolve({ cwd: "/repo" });
|
||||
const provider = yield* registry.get("github");
|
||||
|
||||
assert.strictEqual(provider.kind, "gitlab");
|
||||
const error = yield* Effect.flip(
|
||||
provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/source-control",
|
||||
state: "open",
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(provider.kind, "github");
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error.provider, "gitlab");
|
||||
}),
|
||||
it.effect("routes GitLab remotes to the GitLab provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
|
||||
});
|
||||
|
||||
const provider = yield* registry.resolve({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(provider.kind, "gitlab");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to a non-origin remote when origin is not configured", () =>
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type SourceControlProviderShape,
|
||||
} from "./SourceControlProvider.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
|
||||
@@ -25,6 +26,9 @@ export interface SourceControlProviderHandle {
|
||||
}
|
||||
|
||||
export interface SourceControlProviderRegistryShape {
|
||||
readonly get: (
|
||||
kind: SourceControlProviderKind,
|
||||
) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
|
||||
readonly resolveHandle: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
|
||||
@@ -54,6 +58,7 @@ function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProv
|
||||
getChangeRequest: () => unsupported("getChangeRequest"),
|
||||
createChangeRequest: () => unsupported("createChangeRequest"),
|
||||
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
|
||||
createRepository: () => unsupported("createRepository"),
|
||||
getDefaultBranch: () => unsupported("getDefaultBranch"),
|
||||
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
|
||||
});
|
||||
@@ -102,6 +107,9 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
registrations.map((registration) => [registration.kind, registration.provider]),
|
||||
);
|
||||
|
||||
const get: SourceControlProviderRegistryShape["get"] = (kind) =>
|
||||
Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
|
||||
|
||||
const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
|
||||
function* (cwd: string) {
|
||||
const handle = yield* vcsRegistry
|
||||
@@ -136,6 +144,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
);
|
||||
|
||||
return SourceControlProviderRegistry.of({
|
||||
get,
|
||||
resolveHandle,
|
||||
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
|
||||
});
|
||||
@@ -144,11 +153,16 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
|
||||
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
|
||||
const github = yield* GitHubSourceControlProvider.make();
|
||||
const gitlab = yield* GitLabSourceControlProvider.make();
|
||||
return yield* makeWithProviders([
|
||||
{
|
||||
kind: "github",
|
||||
provider: github,
|
||||
},
|
||||
{
|
||||
kind: "gitlab",
|
||||
provider: gitlab,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError, type SourceControlProviderError } from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import {
|
||||
GitVcsDriver,
|
||||
type ExecuteGitResult,
|
||||
type GitVcsDriverShape,
|
||||
} from "../vcs/GitVcsDriver.ts";
|
||||
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
|
||||
import type { SourceControlProviderShape } from "./SourceControlProvider.ts";
|
||||
import { SourceControlRepositoryService, layer } from "./SourceControlRepositoryService.ts";
|
||||
|
||||
const CLONE_URLS = {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://github.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
};
|
||||
|
||||
function makeProvider(
|
||||
overrides: Partial<SourceControlProviderShape> = {},
|
||||
): SourceControlProviderShape {
|
||||
const unsupported = (operation: string) =>
|
||||
Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
|
||||
never,
|
||||
SourceControlProviderError
|
||||
>;
|
||||
|
||||
return {
|
||||
kind: "github",
|
||||
listChangeRequests: () => unsupported("listChangeRequests"),
|
||||
getChangeRequest: () => unsupported("getChangeRequest"),
|
||||
createChangeRequest: () => unsupported("createChangeRequest"),
|
||||
getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
|
||||
createRepository: () => Effect.succeed(CLONE_URLS),
|
||||
getDefaultBranch: () => Effect.succeed(null),
|
||||
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function processOutput(): ExecuteGitResult {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly provider?: SourceControlProviderShape;
|
||||
readonly git?: Partial<GitVcsDriverShape>;
|
||||
}) {
|
||||
return layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlProviderRegistry)({
|
||||
get: () => Effect.succeed(input.provider ?? makeProvider()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(GitVcsDriver)({
|
||||
execute: () => Effect.succeed(processOutput()),
|
||||
ensureRemote: () => Effect.succeed("origin"),
|
||||
pushCurrentBranch: () =>
|
||||
Effect.succeed({
|
||||
status: "pushed" as const,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: "origin/feature/remote-v1",
|
||||
setUpstream: true,
|
||||
}),
|
||||
...input.git,
|
||||
}),
|
||||
),
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-repos-" })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("looks up repositories through the requested provider without search", () => {
|
||||
const calls: Array<{ cwd: string; repository: string }> = [];
|
||||
const provider = makeProvider({
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push({ cwd: input.cwd, repository: input.repository });
|
||||
return CLONE_URLS;
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.lookupRepository({
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
cwd: "/workspace",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
|
||||
assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
|
||||
}).pipe(Effect.provide(makeLayer({ provider })));
|
||||
});
|
||||
|
||||
it.effect("clones a looked-up repository into the requested destination", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const parent = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3-source-control-clone-parent-",
|
||||
});
|
||||
const destinationPath = `${parent}/t3code`;
|
||||
const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.cloneRepository({
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
destinationPath,
|
||||
protocol: "https",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
cwd: destinationPath,
|
||||
remoteUrl: CLONE_URLS.url,
|
||||
repository: { provider: "github", ...CLONE_URLS },
|
||||
});
|
||||
assert.deepStrictEqual(cloneCalls, [
|
||||
{
|
||||
cwd: parent,
|
||||
args: ["clone", CLONE_URLS.url, "t3code"],
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
git: {
|
||||
execute: (input) =>
|
||||
Effect.sync(() => {
|
||||
cloneCalls.push({ cwd: input.cwd, args: input.args });
|
||||
return processOutput();
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
|
||||
const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
|
||||
const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
|
||||
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
|
||||
const provider = makeProvider({
|
||||
createRepository: (input) =>
|
||||
Effect.sync(() => {
|
||||
createCalls.push({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
visibility: input.visibility,
|
||||
});
|
||||
return CLONE_URLS;
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.publishRepository({
|
||||
cwd: "/workspace",
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "private",
|
||||
remoteName: "origin",
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
repository: { provider: "github", ...CLONE_URLS },
|
||||
remoteName: "origin",
|
||||
remoteUrl: CLONE_URLS.sshUrl,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: "origin/feature/remote-v1",
|
||||
status: "pushed",
|
||||
});
|
||||
assert.deepStrictEqual(createCalls, [
|
||||
{ cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
|
||||
]);
|
||||
assert.deepStrictEqual(remoteCalls, [
|
||||
{ cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
|
||||
]);
|
||||
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
provider,
|
||||
git: {
|
||||
ensureRemote: (input) =>
|
||||
Effect.sync(() => {
|
||||
remoteCalls.push(input);
|
||||
return "origin";
|
||||
}),
|
||||
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
|
||||
Effect.sync(() => {
|
||||
pushCalls.push({ cwd, remoteName: options?.remoteName });
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: "origin/feature/remote-v1",
|
||||
setUpstream: true,
|
||||
};
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("publishes to the remote name returned by ensureRemote", () => {
|
||||
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.publishRepository({
|
||||
cwd: "/workspace",
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "private",
|
||||
remoteName: "origin",
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
assert.equal(result.remoteName, "origin-1");
|
||||
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
git: {
|
||||
ensureRemote: () => Effect.succeed("origin-1"),
|
||||
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
|
||||
Effect.sync(() => {
|
||||
pushCalls.push({ cwd, remoteName: options?.remoteName });
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
|
||||
let pushCalls = 0;
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.publishRepository({
|
||||
cwd: "/workspace",
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "private",
|
||||
remoteName: "origin",
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
repository: { provider: "github", ...CLONE_URLS },
|
||||
remoteName: "origin",
|
||||
remoteUrl: CLONE_URLS.sshUrl,
|
||||
branch: "main",
|
||||
status: "remote_added",
|
||||
});
|
||||
assert.strictEqual(pushCalls, 0);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
git: {
|
||||
execute: (input) =>
|
||||
input.args[0] === "rev-parse"
|
||||
? Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: "git rev-parse --verify HEAD",
|
||||
cwd: input.cwd,
|
||||
detail: "fatal: Needed a single revision",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(processOutput()),
|
||||
statusDetails: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
}),
|
||||
pushCurrentBranch: () =>
|
||||
Effect.sync(() => {
|
||||
pushCalls += 1;
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch: "main",
|
||||
upstreamBranch: "origin/main",
|
||||
setUpstream: true,
|
||||
};
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,320 @@
|
||||
import OS from "node:os";
|
||||
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
|
||||
import {
|
||||
SourceControlRepositoryError,
|
||||
type SourceControlCloneRepositoryInput,
|
||||
type SourceControlCloneRepositoryResult,
|
||||
type SourceControlCloneProtocol,
|
||||
type SourceControlProviderKind,
|
||||
type SourceControlPublishRepositoryInput,
|
||||
type SourceControlPublishRepositoryResult,
|
||||
type SourceControlRepositoryCloneUrls,
|
||||
type SourceControlRepositoryInfo,
|
||||
type SourceControlRepositoryLookupInput,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
|
||||
|
||||
export interface SourceControlRepositoryServiceShape {
|
||||
readonly lookupRepository: (
|
||||
input: SourceControlRepositoryLookupInput,
|
||||
) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
|
||||
readonly cloneRepository: (
|
||||
input: SourceControlCloneRepositoryInput,
|
||||
) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
|
||||
readonly publishRepository: (
|
||||
input: SourceControlPublishRepositoryInput,
|
||||
) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
|
||||
}
|
||||
|
||||
export class SourceControlRepositoryService extends Context.Service<
|
||||
SourceControlRepositoryService,
|
||||
SourceControlRepositoryServiceShape
|
||||
>()("t3/source-control/SourceControlRepositoryService") {}
|
||||
|
||||
function detailFromUnknown(cause: unknown): string {
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
if ("detail" in cause && typeof cause.detail === "string" && cause.detail.length > 0) {
|
||||
return cause.detail;
|
||||
}
|
||||
if ("message" in cause && typeof cause.message === "string" && cause.message.length > 0) {
|
||||
return cause.message;
|
||||
}
|
||||
}
|
||||
|
||||
return "An unexpected source control error occurred.";
|
||||
}
|
||||
|
||||
function repositoryError(input: {
|
||||
readonly operation: string;
|
||||
readonly provider: SourceControlProviderKind;
|
||||
readonly detail: string;
|
||||
readonly cause?: unknown;
|
||||
}): SourceControlRepositoryError {
|
||||
return new SourceControlRepositoryError({
|
||||
provider: input.provider,
|
||||
operation: input.operation,
|
||||
detail: input.detail,
|
||||
...(input.cause === undefined ? {} : { cause: input.cause }),
|
||||
});
|
||||
}
|
||||
|
||||
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
|
||||
return Effect.mapError((cause: unknown) =>
|
||||
Schema.is(SourceControlRepositoryError)(cause)
|
||||
? cause
|
||||
: repositoryError({
|
||||
operation,
|
||||
provider,
|
||||
detail: detailFromUnknown(cause),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toRepositoryInfo(
|
||||
provider: SourceControlProviderKind,
|
||||
urls: SourceControlRepositoryCloneUrls,
|
||||
): SourceControlRepositoryInfo {
|
||||
return {
|
||||
provider,
|
||||
nameWithOwner: urls.nameWithOwner,
|
||||
url: urls.url,
|
||||
sshUrl: urls.sshUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function selectRemoteUrl(
|
||||
urls: SourceControlRepositoryCloneUrls,
|
||||
protocol: SourceControlCloneProtocol | undefined,
|
||||
): string {
|
||||
switch (protocol ?? "auto") {
|
||||
case "https":
|
||||
return urls.url;
|
||||
case "ssh":
|
||||
case "auto":
|
||||
return urls.sshUrl;
|
||||
}
|
||||
}
|
||||
|
||||
function expandHomePath(input: string, path: Path.Path): string {
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return path.join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeSourceControlRepositoryService")(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const git = yield* GitVcsDriver;
|
||||
const path = yield* Path.Path;
|
||||
const providers = yield* SourceControlProviderRegistry;
|
||||
|
||||
const ensureConcreteProvider = (input: {
|
||||
readonly operation: string;
|
||||
readonly provider: SourceControlProviderKind;
|
||||
}) => {
|
||||
if (input.provider !== "unknown") {
|
||||
return Effect.succeed(input.provider);
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
repositoryError({
|
||||
operation: input.operation,
|
||||
provider: input.provider,
|
||||
detail: "Choose a source control provider before continuing.",
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
|
||||
input: SourceControlRepositoryLookupInput,
|
||||
) {
|
||||
const providerKind = yield* ensureConcreteProvider({
|
||||
operation: "lookupRepository",
|
||||
provider: input.provider,
|
||||
});
|
||||
const provider = yield* providers.get(providerKind);
|
||||
const urls = yield* provider.getRepositoryCloneUrls({
|
||||
cwd: input.cwd ?? config.cwd,
|
||||
repository: input.repository.trim(),
|
||||
});
|
||||
return toRepositoryInfo(providerKind, urls);
|
||||
});
|
||||
|
||||
const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
|
||||
function* (destinationPath: string) {
|
||||
const trimmed = destinationPath.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return yield* Effect.fail(
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider: "unknown",
|
||||
detail: "Choose a destination path before cloning.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return path.resolve(expandHomePath(trimmed, path));
|
||||
},
|
||||
);
|
||||
|
||||
const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
|
||||
function* (destinationPath: string) {
|
||||
const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
|
||||
if (yield* fileSystem.exists(normalizedDestination).pipe(Effect.orElseSucceed(() => false))) {
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(normalizedDestination, { recursive: false })
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider: "unknown",
|
||||
detail: "Destination path already exists and is not a directory.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (entries.length > 0) {
|
||||
return yield* Effect.fail(
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider: "unknown",
|
||||
detail: "Destination path already exists and is not empty.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
|
||||
}
|
||||
|
||||
return {
|
||||
destinationPath: normalizedDestination,
|
||||
parentPath: path.dirname(normalizedDestination),
|
||||
directoryName: path.basename(normalizedDestination),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
|
||||
input: SourceControlCloneRepositoryInput,
|
||||
) {
|
||||
const preparedDestination = yield* prepareDestination(input.destinationPath);
|
||||
let repository: SourceControlRepositoryInfo | null = null;
|
||||
let remoteUrl = input.remoteUrl?.trim() ?? null;
|
||||
let provider: SourceControlProviderKind = input.provider ?? "unknown";
|
||||
|
||||
if (input.provider && input.repository) {
|
||||
repository = yield* lookupRepository({
|
||||
provider: input.provider,
|
||||
repository: input.repository,
|
||||
cwd: preparedDestination.parentPath,
|
||||
});
|
||||
remoteUrl = selectRemoteUrl(repository, input.protocol);
|
||||
provider = input.provider;
|
||||
}
|
||||
|
||||
if (!remoteUrl) {
|
||||
return yield* Effect.fail(
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider,
|
||||
detail: "Enter a repository path or clone URL before cloning.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation: "SourceControlRepositoryService.cloneRepository",
|
||||
cwd: preparedDestination.parentPath,
|
||||
args: ["clone", remoteUrl, preparedDestination.directoryName],
|
||||
timeoutMs: 120_000,
|
||||
maxOutputBytes: 256 * 1024,
|
||||
});
|
||||
|
||||
return {
|
||||
cwd: preparedDestination.destinationPath,
|
||||
remoteUrl,
|
||||
repository,
|
||||
};
|
||||
});
|
||||
|
||||
const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
|
||||
function* (input: SourceControlPublishRepositoryInput) {
|
||||
const providerKind = yield* ensureConcreteProvider({
|
||||
operation: "publishRepository",
|
||||
provider: input.provider,
|
||||
});
|
||||
const provider = yield* providers.get(providerKind);
|
||||
const urls = yield* provider.createRepository({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository.trim(),
|
||||
visibility: input.visibility,
|
||||
});
|
||||
const remoteUrl = selectRemoteUrl(urls, input.protocol);
|
||||
const remoteName = yield* git.ensureRemote({
|
||||
cwd: input.cwd,
|
||||
preferredName: input.remoteName?.trim() || "origin",
|
||||
url: remoteUrl,
|
||||
});
|
||||
|
||||
// An empty local repo (no commits) would make `git push HEAD:...` fail
|
||||
// with an opaque "src refspec HEAD does not match any". Treat this as a
|
||||
// partial success: the remote was created and wired up, but there is
|
||||
// nothing to push yet.
|
||||
const hasCommits = yield* git
|
||||
.execute({
|
||||
operation: "SourceControlRepositoryService.publishRepository.headCheck",
|
||||
cwd: input.cwd,
|
||||
args: ["rev-parse", "--verify", "HEAD"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
if (!hasCommits) {
|
||||
const details = yield* git
|
||||
.statusDetails(input.cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
return {
|
||||
repository: toRepositoryInfo(providerKind, urls),
|
||||
remoteName,
|
||||
remoteUrl,
|
||||
branch: details?.branch ?? "main",
|
||||
status: "remote_added" as const,
|
||||
};
|
||||
}
|
||||
|
||||
const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
|
||||
|
||||
return {
|
||||
repository: toRepositoryInfo(providerKind, urls),
|
||||
remoteName,
|
||||
remoteUrl,
|
||||
branch: pushResult.branch,
|
||||
...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
|
||||
status: "pushed" as const,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
return SourceControlRepositoryService.of({
|
||||
lookupRepository: (input) =>
|
||||
lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
|
||||
cloneRepository: (input) =>
|
||||
cloneRepository(input).pipe(
|
||||
mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
|
||||
),
|
||||
publishRepository: (input) =>
|
||||
publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlRepositoryService, make());
|
||||
File renamed without changes.
@@ -0,0 +1,148 @@
|
||||
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface NormalizedGitLabMergeRequestRecord {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: Option.Option<DateTime.Utc>;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
const GitLabProjectReferenceSchema = Schema.Struct({
|
||||
path_with_namespace: Schema.optional(Schema.String),
|
||||
pathWithNamespace: Schema.optional(Schema.String),
|
||||
namespace: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
path: Schema.optional(Schema.String),
|
||||
full_path: Schema.optional(Schema.String),
|
||||
fullPath: Schema.optional(Schema.String),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const GitLabMergeRequestSchema = Schema.Struct({
|
||||
iid: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
source_branch: TrimmedNonEmptyString,
|
||||
target_branch: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
|
||||
source_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
|
||||
target_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
|
||||
source_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
|
||||
target_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
|
||||
});
|
||||
|
||||
function trimOptionalString(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeGitLabMergeRequestState(
|
||||
state: string | null | undefined,
|
||||
): "open" | "closed" | "merged" {
|
||||
const normalized = state?.trim().toLowerCase();
|
||||
if (normalized === "merged") {
|
||||
return "merged";
|
||||
}
|
||||
if (normalized === "closed") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
function projectPathWithNamespace(
|
||||
project: Schema.Schema.Type<typeof GitLabProjectReferenceSchema> | null | undefined,
|
||||
): string | null {
|
||||
const explicit =
|
||||
trimOptionalString(project?.path_with_namespace) ??
|
||||
trimOptionalString(project?.pathWithNamespace);
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const namespacePath =
|
||||
trimOptionalString(project?.namespace?.full_path) ??
|
||||
trimOptionalString(project?.namespace?.fullPath) ??
|
||||
trimOptionalString(project?.namespace?.path);
|
||||
return namespacePath;
|
||||
}
|
||||
|
||||
function ownerLoginFromPathWithNamespace(pathWithNamespace: string | null): string | null {
|
||||
const [owner] = pathWithNamespace?.split("/") ?? [];
|
||||
return trimOptionalString(owner);
|
||||
}
|
||||
|
||||
function normalizeGitLabMergeRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitLabMergeRequestSchema>,
|
||||
): NormalizedGitLabMergeRequestRecord {
|
||||
const sourceProjectPath = projectPathWithNamespace(raw.source_project);
|
||||
const targetProjectPath = projectPathWithNamespace(raw.target_project);
|
||||
const isCrossRepository =
|
||||
typeof raw.source_project_id === "number" && typeof raw.target_project_id === "number"
|
||||
? raw.source_project_id !== raw.target_project_id
|
||||
: sourceProjectPath !== null && targetProjectPath !== null
|
||||
? sourceProjectPath.toLowerCase() !== targetProjectPath.toLowerCase()
|
||||
: undefined;
|
||||
const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath);
|
||||
|
||||
return {
|
||||
number: raw.iid,
|
||||
title: raw.title,
|
||||
url: raw.web_url,
|
||||
baseRefName: raw.target_branch,
|
||||
headRefName: raw.source_branch,
|
||||
state: normalizeGitLabMergeRequestState(raw.state),
|
||||
updatedAt: raw.updated_at ?? Option.none(),
|
||||
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
|
||||
...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeGitLabMergeRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeGitLabMergeRequest = decodeJsonResult(GitLabMergeRequestSchema);
|
||||
const decodeGitLabMergeRequestEntry = Schema.decodeUnknownExit(GitLabMergeRequestSchema);
|
||||
|
||||
export const formatGitLabJsonDecodeError = formatSchemaError;
|
||||
|
||||
export function decodeGitLabMergeRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitLabMergeRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitLabMergeRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const mergeRequests: NormalizedGitLabMergeRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitLabMergeRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
mergeRequests.push(normalizeGitLabMergeRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(mergeRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
|
||||
export function decodeGitLabMergeRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<NormalizedGitLabMergeRequestRecord, Cause.Cause<Schema.SchemaError>> {
|
||||
const result = decodeGitLabMergeRequest(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
return Result.succeed(normalizeGitLabMergeRequestRecord(result.success));
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Context, Effect, Layer, Option } from "effect";
|
||||
import { Context, DateTime, Effect, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
|
||||
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
|
||||
import { nowFreshness } from "./VcsFreshness.ts";
|
||||
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
@@ -56,6 +55,7 @@ export interface GitStatusDetails {
|
||||
hasUpstream: boolean;
|
||||
aheadCount: number;
|
||||
behindCount: number;
|
||||
aheadOfDefaultCount: number;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
@@ -134,6 +134,12 @@ export interface GitFetchRemoteBranchInput {
|
||||
localBranch: string;
|
||||
}
|
||||
|
||||
export interface GitFetchRemoteTrackingBranchInput {
|
||||
cwd: string;
|
||||
remoteName: string;
|
||||
remoteBranch: string;
|
||||
}
|
||||
|
||||
export interface GitSetBranchUpstreamInput {
|
||||
cwd: string;
|
||||
branch: string;
|
||||
@@ -159,6 +165,7 @@ export interface GitVcsDriverShape {
|
||||
readonly pushCurrentBranch: (
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
options?: { readonly remoteName?: string | null },
|
||||
) => Effect.Effect<GitPushResult, GitCommandError>;
|
||||
readonly readRangeContext: (
|
||||
cwd: string,
|
||||
@@ -177,9 +184,13 @@ export interface GitVcsDriverShape {
|
||||
input: GitFetchPullRequestBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
|
||||
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
|
||||
readonly fetchRemoteBranch: (
|
||||
input: GitFetchRemoteBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly fetchRemoteTrackingBranch: (
|
||||
input: GitFetchRemoteTrackingBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly setBranchUpstream: (
|
||||
input: GitSetBranchUpstreamInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
@@ -210,6 +221,15 @@ const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
|
||||
"core.untrackedCache=false",
|
||||
] as const;
|
||||
|
||||
const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
return {
|
||||
source: "live-local" as const,
|
||||
observedAt: now,
|
||||
expiresAt: Option.none(),
|
||||
};
|
||||
});
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
@@ -503,6 +523,12 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const initRepository: VcsDriverShape["initRepository"] = (input) =>
|
||||
gitCommand(process, "GitVcsDriver.initRepository", input.cwd, ["init"], {
|
||||
timeoutMs: 10_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
return {
|
||||
capabilities,
|
||||
execute,
|
||||
@@ -511,6 +537,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
listWorkspaceFiles,
|
||||
listRemotes,
|
||||
filterIgnoredPaths,
|
||||
initRepository,
|
||||
} satisfies VcsDriverShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -102,6 +102,51 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports default-branch delta separately from upstream delta", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["checkout", "-b", "feature/synced"]);
|
||||
yield* writeTextFile(cwd, "feature.txt", "feature\n");
|
||||
yield* git(cwd, ["add", "feature.txt"]);
|
||||
yield* git(cwd, ["commit", "-m", "feature commit"]);
|
||||
yield* git(cwd, ["push", "-u", "origin", "feature/synced"]);
|
||||
|
||||
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
|
||||
|
||||
assert.equal(status.hasUpstream, true);
|
||||
assert.equal(status.aheadCount, 0);
|
||||
assert.equal(status.behindCount, 0);
|
||||
assert.equal(status.aheadOfDefaultCount, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["checkout", "-b", "feature/no-upstream"]);
|
||||
yield* writeTextFile(cwd, "feature.txt", "feature\n");
|
||||
yield* git(cwd, ["add", "feature.txt"]);
|
||||
yield* git(cwd, ["commit", "-m", "feature commit"]);
|
||||
|
||||
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
|
||||
|
||||
assert.equal(status.hasUpstream, false);
|
||||
assert.equal(status.aheadCount, 1);
|
||||
assert.equal(status.behindCount, 0);
|
||||
assert.equal(status.aheadOfDefaultCount, 1);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("refName operations", () => {
|
||||
@@ -242,5 +287,80 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"pushes upstream branches to the remote branch name, not the upstream shorthand",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-remote-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* git(cwd, ["branch", "-M", "main"]);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", "main"]);
|
||||
yield* writeTextFile(cwd, "upstream.txt", "upstream\n");
|
||||
yield* driver.prepareCommitContext(cwd);
|
||||
yield* driver.commit(cwd, "Add upstream update", "");
|
||||
|
||||
const pushed = yield* driver.pushCurrentBranch(cwd, null);
|
||||
|
||||
assert.deepInclude(pushed, {
|
||||
status: "pushed",
|
||||
branch: "main",
|
||||
upstreamBranch: "origin/main",
|
||||
setUpstream: false,
|
||||
});
|
||||
assert.equal(
|
||||
yield* git(remote, ["log", "-1", "--pretty=%s", "main"]),
|
||||
"Add upstream update",
|
||||
);
|
||||
const badBranch = yield* driver.execute({
|
||||
operation: "GitVcsDriver.test.showBadRemoteBranch",
|
||||
cwd: remote,
|
||||
args: ["show-ref", "--verify", "--quiet", "refs/heads/origin/main"],
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
assert.notEqual(badBranch.exitCode, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes to the requested remote instead of the primary remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const originRemote = yield* makeTmpDir("git-origin-remote-");
|
||||
const publishRemote = yield* makeTmpDir("git-publish-remote-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* git(cwd, ["branch", "-M", "main"]);
|
||||
yield* git(originRemote, ["init", "--bare"]);
|
||||
yield* git(publishRemote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", originRemote]);
|
||||
yield* git(cwd, ["remote", "add", "origin-1", publishRemote]);
|
||||
|
||||
const pushed = yield* driver.pushCurrentBranch(cwd, null, { remoteName: "origin-1" });
|
||||
|
||||
assert.deepInclude(pushed, {
|
||||
status: "pushed",
|
||||
branch: "main",
|
||||
upstreamBranch: "origin-1/main",
|
||||
setUpstream: true,
|
||||
});
|
||||
assert.equal(
|
||||
yield* git(publishRemote, ["log", "-1", "--pretty=%s", "main"]),
|
||||
"initial commit",
|
||||
);
|
||||
const originMain = yield* driver.execute({
|
||||
operation: "GitVcsDriver.test.originMainMissing",
|
||||
cwd: originRemote,
|
||||
args: ["show-ref", "--verify", "--quiet", "refs/heads/main"],
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
assert.notEqual(originMain.exitCode, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -62,6 +62,7 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
@@ -448,7 +449,7 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
|
||||
|
||||
if (event === "child_exit") {
|
||||
hookStartByChildKey.delete(childKey);
|
||||
const code = traceRecord.success.code;
|
||||
const code = traceRecord.success.exitCode;
|
||||
const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
|
||||
const now = yield* DateTime.now;
|
||||
const durationMs = started
|
||||
@@ -969,6 +970,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
Effect.map(parseRemoteNamesInGitOrder),
|
||||
);
|
||||
|
||||
const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* (
|
||||
cwd: string,
|
||||
branchName: string,
|
||||
) {
|
||||
const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.catch(() => Effect.succeed([])));
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames);
|
||||
return parsedRemoteRef?.branchName ?? branchName;
|
||||
});
|
||||
|
||||
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
|
||||
if (yield* originRemoteExists(cwd)) {
|
||||
return "origin";
|
||||
@@ -1213,6 +1223,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
let upstreamRef: string | null = null;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
let aheadOfDefaultCount = 0;
|
||||
let hasWorkingTreeChanges = false;
|
||||
const changedFilesWithoutNumstat = new Set<string>();
|
||||
|
||||
@@ -1241,13 +1252,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}
|
||||
}
|
||||
|
||||
if (!upstreamRef && refName) {
|
||||
aheadCount = yield* computeAheadCountAgainstBase(cwd, refName).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
);
|
||||
const fallbackAheadCount =
|
||||
!upstreamRef && refName
|
||||
? yield* computeAheadCountAgainstBase(cwd, refName).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
)
|
||||
: null;
|
||||
|
||||
if (fallbackAheadCount !== null) {
|
||||
aheadCount = fallbackAheadCount;
|
||||
behindCount = 0;
|
||||
}
|
||||
|
||||
const isDefaultBranch =
|
||||
refName !== null &&
|
||||
(refName === defaultBranch ||
|
||||
(defaultBranch === null && (refName === "main" || refName === "master")));
|
||||
if (refName && !isDefaultBranch) {
|
||||
aheadOfDefaultCount =
|
||||
fallbackAheadCount !== null
|
||||
? fallbackAheadCount
|
||||
: yield* computeAheadCountAgainstBase(cwd, refName).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
);
|
||||
}
|
||||
|
||||
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
||||
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
||||
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
||||
@@ -1277,10 +1306,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: hasPrimaryRemote,
|
||||
isDefaultBranch:
|
||||
refName !== null &&
|
||||
(refName === defaultBranch ||
|
||||
(defaultBranch === null && (refName === "main" || refName === "master"))),
|
||||
isDefaultBranch,
|
||||
branch: refName,
|
||||
upstreamRef,
|
||||
hasWorkingTreeChanges,
|
||||
@@ -1292,6 +1318,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
hasUpstream: upstreamRef !== null,
|
||||
aheadCount,
|
||||
behindCount,
|
||||
aheadOfDefaultCount,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1314,7 +1341,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const status: GitVcsDriverShape["status"] = (input) =>
|
||||
statusDetails(input.cwd).pipe(
|
||||
Effect.map((details) => ({
|
||||
kind: "git" as const,
|
||||
isRepo: details.isRepo,
|
||||
hasPrimaryRemote: details.hasOriginRemote,
|
||||
isDefaultRef: details.isDefaultBranch,
|
||||
@@ -1324,6 +1350,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
||||
pr: null,
|
||||
})),
|
||||
);
|
||||
@@ -1404,7 +1431,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
});
|
||||
|
||||
const pushCurrentBranch: GitVcsDriverShape["pushCurrentBranch"] = Effect.fn("pushCurrentBranch")(
|
||||
function* (cwd, fallbackBranch) {
|
||||
function* (cwd, fallbackBranch, options) {
|
||||
const details = yield* statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
@@ -1416,6 +1443,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
);
|
||||
}
|
||||
|
||||
const requestedRemoteName = options?.remoteName?.trim() || null;
|
||||
if (requestedRemoteName) {
|
||||
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
|
||||
yield* runGit("GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, [
|
||||
"push",
|
||||
"-u",
|
||||
requestedRemoteName,
|
||||
`HEAD:refs/heads/${publishBranch}`,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch,
|
||||
upstreamBranch: `${requestedRemoteName}/${publishBranch}`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}
|
||||
|
||||
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
|
||||
if (hasNoLocalDelta) {
|
||||
if (details.hasUpstream) {
|
||||
@@ -1462,16 +1506,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
"Cannot push because no git remote is configured for this repository.",
|
||||
);
|
||||
}
|
||||
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
|
||||
yield* runGit("GitVcsDriver.pushCurrentBranch.pushWithUpstream", cwd, [
|
||||
"push",
|
||||
"-u",
|
||||
publishRemoteName,
|
||||
`HEAD:refs/heads/${branch}`,
|
||||
`HEAD:refs/heads/${publishBranch}`,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch,
|
||||
upstreamBranch: `${publishRemoteName}/${branch}`,
|
||||
upstreamBranch: `${publishRemoteName}/${publishBranch}`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}
|
||||
@@ -1483,7 +1528,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
yield* runGit("GitVcsDriver.pushCurrentBranch.pushUpstream", cwd, [
|
||||
"push",
|
||||
currentUpstream.remoteName,
|
||||
`HEAD:${currentUpstream.upstreamRef}`,
|
||||
`HEAD:refs/heads/${currentUpstream.branchName}`,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
@@ -1895,6 +1940,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
},
|
||||
);
|
||||
|
||||
const fetchRemoteTrackingBranch: GitVcsDriverShape["fetchRemoteTrackingBranch"] = Effect.fn(
|
||||
"fetchRemoteTrackingBranch",
|
||||
)(function* (input) {
|
||||
yield* runGit("GitVcsDriver.fetchRemoteTrackingBranch", input.cwd, [
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
input.remoteName,
|
||||
`+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,
|
||||
]);
|
||||
});
|
||||
|
||||
const setBranchUpstream: GitVcsDriverShape["setBranchUpstream"] = (input) =>
|
||||
runGit("GitVcsDriver.setBranchUpstream", input.cwd, [
|
||||
"branch",
|
||||
@@ -2076,7 +2133,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
createWorktree,
|
||||
fetchPullRequestBranch,
|
||||
ensureRemote,
|
||||
resolvePrimaryRemoteName,
|
||||
fetchRemoteBranch,
|
||||
fetchRemoteTrackingBranch,
|
||||
setBranchUpstream,
|
||||
removeWorktree,
|
||||
renameBranch,
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts";
|
||||
import { VcsProcess, layer as VcsProcessLayer } from "./VcsProcess.ts";
|
||||
import * as JjVcsDriver from "./JjVcsDriver.ts";
|
||||
import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
|
||||
|
||||
const JjContractLayer = JjVcsDriver.vcsLayer.pipe(
|
||||
Layer.provideMerge(VcsProcessLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
|
||||
calls.map((call) => [call.command].concat(call.args));
|
||||
|
||||
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(exitCode),
|
||||
stdout,
|
||||
stderr,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
const runJj = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
yield* process.run({
|
||||
operation: "JjVcsDriver.contract.jj",
|
||||
command: "jj",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
type JjContractError = PlatformError.PlatformError | VcsError;
|
||||
|
||||
runVcsDriverContractSuite<VcsProcess, JjContractError>({
|
||||
name: "JJ",
|
||||
kind: "jj",
|
||||
layer: JjContractLayer,
|
||||
fixture: {
|
||||
createRepo: (cwd) => runJj(cwd, ["git", "init", "--colocate"]),
|
||||
writeFile: (cwd, relativePath, contents) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(absolutePath, contents);
|
||||
}),
|
||||
ignorePath: (cwd, pattern) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
describe("JjVcsDriver", () => {
|
||||
it.effect("detects repository identity with jj root", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const identity = yield* driver.detectRepository("/repo/src");
|
||||
|
||||
assert.equal(identity?.kind, "jj");
|
||||
assert.equal(identity?.rootPath, "/repo");
|
||||
assert.equal(identity?.metadataPath, "/repo/.jj");
|
||||
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
return processOutput("/repo\n");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("lists workspace files using jj file list", () => {
|
||||
let observedInput: VcsProcessInput | null = null;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const result = yield* driver.listWorkspaceFiles("/repo");
|
||||
|
||||
assert.deepStrictEqual(result.paths, ["README.md", "src/index.ts"]);
|
||||
assert.deepStrictEqual(observedInput?.args, ["--no-pager", "file", "list"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
observedInput = input;
|
||||
return processOutput("README.md\nsrc/index.ts\n");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("filters paths with the git ignore oracle", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const result = yield* driver.filterIgnoredPaths("/repo", [
|
||||
"keep.ts",
|
||||
"debug.log",
|
||||
"src/index.ts",
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(result, ["keep.ts", "src/index.ts"]);
|
||||
assert.equal(calls[0]?.command, "git");
|
||||
assert.deepStrictEqual(calls[0]?.args.slice(-2), ["init", "--bare"]);
|
||||
assert.equal(calls[1]?.command, "git");
|
||||
assert.deepStrictEqual(calls[1]?.args.slice(-4), [
|
||||
"check-ignore",
|
||||
"--no-index",
|
||||
"-z",
|
||||
"--stdin",
|
||||
]);
|
||||
assert.equal(calls[1]?.stdin, "keep.ts\0debug.log\0src/index.ts\0");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
if (input.command === "git" && input.args.includes("check-ignore")) {
|
||||
return processOutput("debug.log\0");
|
||||
}
|
||||
return processOutput("");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards execute env to the VCS process", () => {
|
||||
let observedEnv: NodeJS.ProcessEnv | undefined;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
|
||||
yield* driver.execute({
|
||||
operation: "JjVcsDriver.test.env",
|
||||
cwd: "/repo",
|
||||
args: ["status"],
|
||||
env: {
|
||||
JJ_CONFIG: "/tmp/t3-jj-config.toml",
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(observedEnv, {
|
||||
JJ_CONFIG: "/tmp/t3-jj-config.toml",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
observedEnv = input.env;
|
||||
return processOutput("");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,513 +0,0 @@
|
||||
import { Context, Effect, FileSystem, Layer, Option } from "effect";
|
||||
|
||||
import { VcsOutputDecodeError, VcsProcessExitError, type VcsError } from "@t3tools/contracts";
|
||||
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
|
||||
import { nowFreshness } from "./VcsFreshness.ts";
|
||||
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
|
||||
|
||||
export interface JjVcsDriverShape extends VcsDriverShape {
|
||||
readonly capabilities: VcsDriverShape["capabilities"] & {
|
||||
readonly kind: "jj";
|
||||
readonly supportsBookmarks: true;
|
||||
readonly supportsAtomicSnapshot: true;
|
||||
readonly supportsWorktrees: false;
|
||||
readonly ignoreClassifier: "git-compatible-fallback";
|
||||
};
|
||||
readonly currentChange: (cwd: string) => Effect.Effect<JjCurrentChange | null, VcsError>;
|
||||
readonly listBookmarks: (cwd: string) => Effect.Effect<ReadonlyArray<JjBookmark>, VcsError>;
|
||||
readonly listWorkspaces: (cwd: string) => Effect.Effect<ReadonlyArray<JjWorkspace>, VcsError>;
|
||||
}
|
||||
|
||||
export interface JjCurrentChange {
|
||||
readonly changeId: string;
|
||||
readonly commitId: string | null;
|
||||
readonly description: string | null;
|
||||
}
|
||||
|
||||
export interface JjBookmark {
|
||||
readonly name: string;
|
||||
readonly target: string | null;
|
||||
}
|
||||
|
||||
export interface JjWorkspace {
|
||||
readonly name: string;
|
||||
readonly path: string | null;
|
||||
}
|
||||
|
||||
export class JjVcsDriver extends Context.Service<JjVcsDriver, JjVcsDriverShape>()(
|
||||
"t3/vcs/JjVcsDriver",
|
||||
) {}
|
||||
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function splitLineSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const lines = input.split(/\r?\n/g);
|
||||
if (truncated && lines[lines.length - 1]?.length) {
|
||||
lines.pop();
|
||||
}
|
||||
|
||||
return lines.map((line) => line.trim()).filter((line) => line.length > 0);
|
||||
}
|
||||
|
||||
function parseJjRemoteList(output: string): Array<{ name: string; url: string }> {
|
||||
return output
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.flatMap((line) => {
|
||||
if (line.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const [name, ...urlParts] = line.split(/\s+/g);
|
||||
const url = urlParts.join(" ").trim();
|
||||
return name && url ? [{ name, url }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function parseNullRecord(record: string): string[] {
|
||||
return record.split("\0").map((value) => value.trim());
|
||||
}
|
||||
|
||||
function decodeJjCurrentChange(raw: string, cwd: string): JjCurrentChange | null {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [changeId, commitId, description] = parseNullRecord(trimmed);
|
||||
if (!changeId) {
|
||||
throw new VcsOutputDecodeError({
|
||||
operation: "JjVcsDriver.currentChange",
|
||||
command: "jj log",
|
||||
cwd,
|
||||
detail: "jj current change output did not include a change id",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
changeId,
|
||||
commitId: commitId || null,
|
||||
description: description || null,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeJjBookmarkList(raw: string): ReadonlyArray<JjBookmark> {
|
||||
return raw
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const [name, target] = parseNullRecord(line);
|
||||
return {
|
||||
name: name ?? line,
|
||||
target: target || null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function decodeJjWorkspaceList(raw: string): ReadonlyArray<JjWorkspace> {
|
||||
return raw
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const [name, path] = parseNullRecord(line);
|
||||
return {
|
||||
name: name ?? line,
|
||||
path: path || null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function chunkPathsForCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
|
||||
const chunks: string[][] = [];
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (chunk.length > 0 && chunkBytes + relativePathBytes > CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length > 0) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
const processCommand = (
|
||||
process: VcsProcessShape,
|
||||
command: string,
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options?: {
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
},
|
||||
) =>
|
||||
process.run({
|
||||
operation,
|
||||
command,
|
||||
args,
|
||||
cwd,
|
||||
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
|
||||
...(options?.env !== undefined ? { env: options.env } : {}),
|
||||
...(options?.allowNonZeroExit !== undefined
|
||||
? { allowNonZeroExit: options.allowNonZeroExit }
|
||||
: {}),
|
||||
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
...(options?.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const jjCommand = (
|
||||
process: VcsProcessShape,
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options?: {
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
},
|
||||
) => processCommand(process, "jj", operation, cwd, ["--no-pager", ...args], options);
|
||||
|
||||
const gitCommand = (
|
||||
process: VcsProcessShape,
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options?: Parameters<typeof processCommand>[5],
|
||||
) => processCommand(process, "git", operation, cwd, args, options);
|
||||
|
||||
function fileSystemError(operation: string, cwd: string, detail: string, cause: unknown) {
|
||||
return new VcsOutputDecodeError({
|
||||
operation,
|
||||
command: "git check-ignore",
|
||||
cwd,
|
||||
detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
const makeScopedTempGitDir = (fileSystem: FileSystem.FileSystem, operation: string, cwd: string) =>
|
||||
fileSystem
|
||||
.makeTempDirectoryScoped({ prefix: "t3-jj-check-ignore-" })
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
fileSystemError(operation, cwd, "failed to create temp git dir", cause),
|
||||
),
|
||||
);
|
||||
|
||||
export const makeVcsDriverShape = Effect.fn("makeJjVcsDriverShape")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const capabilities = {
|
||||
kind: "jj" as const,
|
||||
supportsWorktrees: false as const,
|
||||
supportsBookmarks: true as const,
|
||||
supportsAtomicSnapshot: true as const,
|
||||
supportsPushDefaultRemote: false as const,
|
||||
ignoreClassifier: "git-compatible-fallback" as const,
|
||||
};
|
||||
|
||||
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
|
||||
jjCommand(process, "JjVcsDriver.isInsideWorkTree", cwd, ["root"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
}).pipe(
|
||||
Effect.map((result) => result.exitCode === 0 && result.stdout.trim().length > 0),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
const execute: VcsDriverShape["execute"] = (input) =>
|
||||
jjCommand(process, input.operation, input.cwd, input.args, {
|
||||
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
|
||||
...(input.env !== undefined ? { env: input.env } : {}),
|
||||
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
|
||||
...(input.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
|
||||
function* (cwd) {
|
||||
const root = yield* jjCommand(process, "JjVcsDriver.detectRepository.root", cwd, ["root"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
}).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!root || root.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rootPath = root.stdout.trim();
|
||||
if (rootPath.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "jj" as const,
|
||||
rootPath,
|
||||
metadataPath: `${rootPath.replace(/[\\/]$/g, "")}/.jj`,
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
|
||||
jjCommand(process, "JjVcsDriver.listWorkspaceFiles", cwd, ["file", "list"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode === 0
|
||||
? Effect.gen(function* () {
|
||||
return {
|
||||
paths: splitLineSeparatedPaths(result.stdout, result.stdoutTruncated),
|
||||
truncated: result.stdoutTruncated,
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
})
|
||||
: Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "JjVcsDriver.listWorkspaceFiles",
|
||||
command: "jj file list",
|
||||
cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "jj file list failed",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
|
||||
const result = yield* jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.listRemotes",
|
||||
cwd,
|
||||
["git", "remote", "list"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
return {
|
||||
remotes: [],
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
remotes: parseJjRemoteList(result.stdout).map((remote) => ({
|
||||
name: remote.name,
|
||||
url: remote.url,
|
||||
pushUrl: Option.none(),
|
||||
isPrimary: remote.name === "origin",
|
||||
})),
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
});
|
||||
|
||||
const currentChange: JjVcsDriverShape["currentChange"] = (cwd) =>
|
||||
jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.currentChange",
|
||||
cwd,
|
||||
[
|
||||
"log",
|
||||
"-r",
|
||||
"@",
|
||||
"--no-graph",
|
||||
"--template",
|
||||
'change_id ++ "\\0" ++ commit_id ++ "\\0" ++ description.first_line()',
|
||||
],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
},
|
||||
).pipe(Effect.map((result) => decodeJjCurrentChange(result.stdout, cwd)));
|
||||
|
||||
const listBookmarks: JjVcsDriverShape["listBookmarks"] = (cwd) =>
|
||||
jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.listBookmarks",
|
||||
cwd,
|
||||
["bookmark", "list", "--template", 'name ++ "\\0" ++ target.commit_id() ++ "\\n"'],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 256 * 1024,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) => (result.exitCode === 0 ? decodeJjBookmarkList(result.stdout) : [])),
|
||||
);
|
||||
|
||||
const listWorkspaces: JjVcsDriverShape["listWorkspaces"] = (cwd) =>
|
||||
jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.listWorkspaces",
|
||||
cwd,
|
||||
["workspace", "list", "--template", 'name ++ "\\0" ++ root ++ "\\n"'],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 256 * 1024,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) => (result.exitCode === 0 ? decodeJjWorkspaceList(result.stdout) : [])),
|
||||
);
|
||||
|
||||
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
|
||||
function* (cwd, relativePaths) {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const operation = "JjVcsDriver.filterIgnoredPaths";
|
||||
const ignoredPaths = new Set<string>();
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const gitDir = yield* makeScopedTempGitDir(fileSystem, operation, cwd);
|
||||
const initResult = yield* gitCommand(
|
||||
process,
|
||||
operation,
|
||||
cwd,
|
||||
["--git-dir", gitDir, "init", "--bare"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
if (initResult.exitCode !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git init --bare",
|
||||
cwd,
|
||||
exitCode: initResult.exitCode,
|
||||
detail: initResult.stderr.trim() || "git init --bare failed",
|
||||
});
|
||||
}
|
||||
|
||||
for (const chunk of chunkPathsForCheckIgnore(relativePaths)) {
|
||||
const result = yield* gitCommand(
|
||||
process,
|
||||
operation,
|
||||
cwd,
|
||||
[
|
||||
"--git-dir",
|
||||
gitDir,
|
||||
"--work-tree",
|
||||
cwd,
|
||||
"check-ignore",
|
||||
"--no-index",
|
||||
"-z",
|
||||
"--stdin",
|
||||
],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.exitCode !== 0 && result.exitCode !== 1) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git check-ignore",
|
||||
cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "git check-ignore failed",
|
||||
});
|
||||
}
|
||||
|
||||
for (const ignoredPath of splitNullSeparatedPaths(
|
||||
result.stdout,
|
||||
result.stdoutTruncated,
|
||||
)) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
capabilities,
|
||||
execute,
|
||||
detectRepository,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
listRemotes,
|
||||
filterIgnoredPaths,
|
||||
currentChange,
|
||||
listBookmarks,
|
||||
listWorkspaces,
|
||||
} satisfies JjVcsDriverShape;
|
||||
});
|
||||
|
||||
export const makeJjVcsDriver = Effect.fn("makeJjVcsDriver")(function* () {
|
||||
const driver = yield* makeVcsDriverShape();
|
||||
return JjVcsDriver.of(driver);
|
||||
});
|
||||
|
||||
export const makeVcsDriver = Effect.fn("makeJjGenericVcsDriver")(function* () {
|
||||
const driver = yield* makeVcsDriverShape();
|
||||
return VcsDriver.of(driver);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(JjVcsDriver, makeJjVcsDriver());
|
||||
export const vcsLayer = Layer.effect(VcsDriver, makeVcsDriver());
|
||||
@@ -3,6 +3,7 @@ import { Context, type Effect } from "effect";
|
||||
import type {
|
||||
VcsDriverCapabilities,
|
||||
VcsError,
|
||||
VcsInitInput,
|
||||
VcsListRemotesResult,
|
||||
VcsListWorkspaceFilesResult,
|
||||
VcsRepositoryIdentity,
|
||||
@@ -24,6 +25,7 @@ export interface VcsDriverShape {
|
||||
cwd: string,
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, VcsError>;
|
||||
readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsDriver extends Context.Service<VcsDriver, VcsDriverShape>()("t3/vcs/VcsDriver") {}
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -8,18 +7,37 @@ import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "./VcsPr
|
||||
import { VcsProjectConfig } from "./VcsProjectConfig.ts";
|
||||
import { VcsDriverRegistry, make as makeVcsDriverRegistry } from "./VcsDriverRegistry.ts";
|
||||
|
||||
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
|
||||
calls.map((call) => [call.command].concat(call.args));
|
||||
|
||||
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(exitCode),
|
||||
const processOutput = (stdout: string): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
describe("VcsDriverRegistry", () => {
|
||||
it.effect("routes directly by VCS driver kind for non-repository workflows", () => {
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: () => Effect.succeed(processOutput("")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const driver = yield* registry.get("git");
|
||||
|
||||
assert.strictEqual(driver.capabilities.kind, "git");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
@@ -47,7 +65,6 @@ describe("VcsDriverRegistry", () => {
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
@@ -67,75 +84,4 @@ describe("VcsDriverRegistry", () => {
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("resolves an explicitly requested jj repository", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
const command = input.args.join(" ");
|
||||
if (input.command === "jj" && command === "--no-pager root") {
|
||||
return processOutput("/repo\n");
|
||||
}
|
||||
return processOutput("", 1, "not found");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const handle = yield* registry.resolve({ cwd: "/repo", requestedKind: "jj" });
|
||||
|
||||
assert.equal(handle.kind, "jj");
|
||||
assert.equal(handle.repository.rootPath, "/repo");
|
||||
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("prefers jj auto-detection before git for colocated repositories", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
const command = input.args.join(" ");
|
||||
if (input.command === "jj" && command === "--no-pager root") {
|
||||
return processOutput("/repo\n");
|
||||
}
|
||||
if (input.command === "git") {
|
||||
return processOutput("true\n");
|
||||
}
|
||||
return processOutput("", 1, "not found");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const handle = yield* registry.resolve({ cwd: "/repo" });
|
||||
|
||||
assert.equal(handle.kind, "jj");
|
||||
assert.equal(handle.repository.rootPath, "/repo");
|
||||
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
|
||||
import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/contracts";
|
||||
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
import * as JjVcsDriver from "./JjVcsDriver.ts";
|
||||
import * as VcsProjectConfig from "./VcsProjectConfig.ts";
|
||||
import type { VcsDriverShape } from "./VcsDriver.ts";
|
||||
|
||||
@@ -22,6 +21,7 @@ export interface VcsDriverHandle {
|
||||
}
|
||||
|
||||
export interface VcsDriverRegistryShape {
|
||||
readonly get: (kind: VcsDriverKind) => Effect.Effect<VcsDriverShape, VcsError>;
|
||||
readonly detect: (
|
||||
input: VcsDriverResolveInput,
|
||||
) => Effect.Effect<VcsDriverHandle | null, VcsError>;
|
||||
@@ -66,10 +66,18 @@ function parseDetectionCacheKey(key: string): {
|
||||
export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
|
||||
const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;
|
||||
const git = yield* GitVcsDriver.makeVcsDriverShape();
|
||||
const jj = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const drivers: Partial<Record<VcsDriverKind, VcsDriverShape>> = {
|
||||
git,
|
||||
jj,
|
||||
};
|
||||
|
||||
const get: VcsDriverRegistryShape["get"] = (kind) => {
|
||||
const driver = drivers[kind];
|
||||
if (!driver) {
|
||||
return Effect.fail(
|
||||
unsupported("VcsDriverRegistry.get", kind, `No ${kind} VCS driver is registered.`),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(driver);
|
||||
};
|
||||
|
||||
const detectWithDriver = Effect.fn("VcsDriverRegistry.detectWithDriver")(function* (
|
||||
@@ -95,22 +103,10 @@ export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
|
||||
const requestedKind = input.requestedKind;
|
||||
|
||||
if (requestedKind !== "auto" && requestedKind !== "unknown") {
|
||||
const driver = drivers[requestedKind];
|
||||
if (!driver) {
|
||||
return yield* unsupported(
|
||||
"VcsDriverRegistry.detect",
|
||||
requestedKind,
|
||||
`No ${requestedKind} VCS driver is registered.`,
|
||||
);
|
||||
}
|
||||
const driver = yield* get(requestedKind);
|
||||
return yield* detectWithDriver(requestedKind, driver, input.cwd);
|
||||
}
|
||||
|
||||
const jjDetected = yield* detectWithDriver("jj", jj, input.cwd);
|
||||
if (jjDetected) {
|
||||
return jjDetected;
|
||||
}
|
||||
|
||||
return yield* detectWithDriver("git", git, input.cwd);
|
||||
});
|
||||
|
||||
@@ -148,6 +144,7 @@ export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
|
||||
);
|
||||
|
||||
return VcsDriverRegistry.of({
|
||||
get,
|
||||
detect,
|
||||
resolve,
|
||||
});
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { DateTime, Effect, Option } from "effect";
|
||||
|
||||
export const nowFreshness = Effect.fn("VcsFreshness.nowFreshness")(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
return {
|
||||
source: "live-local" as const,
|
||||
observedAt: now,
|
||||
expiresAt: Option.none(),
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import type { VcsDriverShape } from "./VcsDriver.ts";
|
||||
import { VcsDriverRegistry } from "./VcsDriverRegistry.ts";
|
||||
import { VcsProvisioningService, layer } from "./VcsProvisioningService.ts";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
function makeDriver(calls: string[]): VcsDriverShape {
|
||||
return {
|
||||
capabilities: {
|
||||
kind: "git",
|
||||
supportsWorktrees: true,
|
||||
supportsBookmarks: false,
|
||||
supportsAtomicSnapshot: false,
|
||||
supportsPushDefaultRemote: true,
|
||||
ignoreClassifier: "native",
|
||||
},
|
||||
execute: () =>
|
||||
Effect.succeed({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
detectRepository: () => Effect.succeed(null),
|
||||
isInsideWorkTree: () => Effect.succeed(false),
|
||||
listWorkspaceFiles: () =>
|
||||
Effect.succeed({
|
||||
paths: [],
|
||||
truncated: false,
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
listRemotes: () =>
|
||||
Effect.succeed({
|
||||
remotes: [],
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
|
||||
initRepository: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(`${input.kind ?? "default"}:${input.cwd}`);
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
it.effect("routes repository initialization through an explicit VCS driver kind", () => {
|
||||
const calls: string[] = [];
|
||||
const driver = makeDriver(calls);
|
||||
const testLayer = layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const provisioning = yield* VcsProvisioningService;
|
||||
yield* provisioning.initRepository({ cwd: "/repo", kind: "git" });
|
||||
|
||||
assert.deepStrictEqual(calls, ["git:/repo"]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("defaults repository initialization to Git until callers choose a VCS kind", () => {
|
||||
const calls: string[] = [];
|
||||
const driver = makeDriver(calls);
|
||||
const testLayer = layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry)({
|
||||
get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const provisioning = yield* VcsProvisioningService;
|
||||
yield* provisioning.initRepository({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(calls, ["default:/repo"]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
|
||||
import {
|
||||
type VcsDriverKind,
|
||||
type VcsError,
|
||||
type VcsInitInput,
|
||||
VcsUnsupportedOperationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { VcsDriverRegistry } from "./VcsDriverRegistry.ts";
|
||||
|
||||
export interface VcsProvisioningServiceShape {
|
||||
readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsProvisioningService extends Context.Service<
|
||||
VcsProvisioningService,
|
||||
VcsProvisioningServiceShape
|
||||
>()("t3/vcs/VcsProvisioningService") {}
|
||||
|
||||
function resolveRequestedKind(
|
||||
kind: VcsDriverKind | undefined,
|
||||
): Effect.Effect<VcsDriverKind, VcsUnsupportedOperationError> {
|
||||
if (kind === undefined) {
|
||||
return Effect.succeed("git");
|
||||
}
|
||||
if (kind === "unknown") {
|
||||
return Effect.fail(
|
||||
new VcsUnsupportedOperationError({
|
||||
operation: "VcsProvisioningService.resolveRequestedKind",
|
||||
kind,
|
||||
detail: "A concrete VCS driver kind is required for repository provisioning.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(kind);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeVcsProvisioningService")(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
|
||||
const initRepository: VcsProvisioningServiceShape["initRepository"] = Effect.fn(
|
||||
"VcsProvisioningService.initRepository",
|
||||
)(function* (input) {
|
||||
const kind = yield* resolveRequestedKind(input.kind);
|
||||
const driver = yield* registry.get(kind);
|
||||
return yield* driver.initRepository(input);
|
||||
});
|
||||
|
||||
return VcsProvisioningService.of({
|
||||
initRepository,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(VcsProvisioningService, make());
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
import { GitWorkflowService, type GitWorkflowServiceShape } from "../git/GitWorkflowService.ts";
|
||||
|
||||
const baseLocalStatus: VcsStatusLocalResult = {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
sourceControlProvider: {
|
||||
kind: "github",
|
||||
@@ -50,30 +49,29 @@ function makeTestLayer(state: {
|
||||
localInvalidationCalls: number;
|
||||
remoteInvalidationCalls: number;
|
||||
}) {
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
});
|
||||
|
||||
return VcsStatusBroadcasterLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -190,31 +188,31 @@ describe("VcsStatusBroadcaster", () => {
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
localStatus: (input) =>
|
||||
Effect.sync(() => {
|
||||
seenCwds.push(input.cwd);
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: (input) =>
|
||||
Effect.sync(() => {
|
||||
seenCwds.push(input.cwd);
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowServiceShape>);
|
||||
const testLayer = VcsStatusBroadcasterLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
localStatus: (input) =>
|
||||
Effect.sync(() => {
|
||||
seenCwds.push(input.cwd);
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: (input) =>
|
||||
Effect.sync(() => {
|
||||
seenCwds.push(input.cwd);
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowServiceShape>),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
@@ -237,7 +235,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.deepStrictEqual(seenCwds, [realPath, realPath]);
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
}).pipe(Effect.provide(Layer.mergeAll(testLayer, NodeServices.layer)));
|
||||
});
|
||||
|
||||
it.effect("streams a local snapshot first and remote updates later", () => {
|
||||
@@ -291,40 +289,40 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
remoteStartedDeferred
|
||||
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
|
||||
Effect.onInterrupt(() =>
|
||||
remoteInterruptedDeferred
|
||||
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowServiceShape>);
|
||||
const testLayer = VcsStatusBroadcasterLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
remoteStartedDeferred
|
||||
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
|
||||
Effect.onInterrupt(() =>
|
||||
remoteInterruptedDeferred
|
||||
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowServiceShape>),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Fiber,
|
||||
Layer,
|
||||
PubSub,
|
||||
@@ -68,11 +69,18 @@ function fingerprintStatusPart(status: unknown): string {
|
||||
return JSON.stringify(status);
|
||||
}
|
||||
|
||||
function normalizeCwd(cwd: string): string {
|
||||
try {
|
||||
return realpathSync.native(cwd);
|
||||
} catch {
|
||||
return cwd;
|
||||
}
|
||||
}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
VcsStatusBroadcaster,
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<VcsStatusChange>(),
|
||||
(pubsub) => PubSub.shutdown(pubsub),
|
||||
@@ -83,9 +91,6 @@ export const layer = Layer.effect(
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
|
||||
const normalizeCwd = (cwd: string) =>
|
||||
fileSystem.realPath(cwd).pipe(Effect.catch(() => Effect.succeed(cwd)));
|
||||
|
||||
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
@@ -193,7 +198,7 @@ export const layer = Layer.effect(
|
||||
const getStatus: VcsStatusBroadcasterShape["getStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.getStatus",
|
||||
)(function* (input) {
|
||||
const cwd = yield* normalizeCwd(input.cwd);
|
||||
const cwd = normalizeCwd(input.cwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
getOrLoadLocalStatus(cwd),
|
||||
getOrLoadRemoteStatus(cwd),
|
||||
@@ -204,7 +209,7 @@ export const layer = Layer.effect(
|
||||
const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshLocalStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* normalizeCwd(rawCwd);
|
||||
const cwd = normalizeCwd(rawCwd);
|
||||
yield* workflow.invalidateLocalStatus(cwd);
|
||||
const local = yield* workflow.localStatus({ cwd });
|
||||
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
|
||||
@@ -221,7 +226,7 @@ export const layer = Layer.effect(
|
||||
const refreshStatus: VcsStatusBroadcasterShape["refreshStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* normalizeCwd(rawCwd);
|
||||
const cwd = normalizeCwd(rawCwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
refreshLocalStatus(cwd),
|
||||
refreshRemoteStatus(cwd),
|
||||
@@ -307,7 +312,7 @@ export const layer = Layer.effect(
|
||||
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* normalizeCwd(input.cwd);
|
||||
const cwd = normalizeCwd(input.cwd);
|
||||
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||
const initialLocal = yield* getOrLoadLocalStatus(cwd);
|
||||
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
|
||||
|
||||
@@ -56,11 +56,9 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
|
||||
|
||||
yield* input.fixture.createRepo(cwd);
|
||||
yield* input.fixture.writeFile(cwd, "src/index.ts", "export const value = 1;\n");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCwd = yield* fileSystem.realPath(cwd);
|
||||
const identity = yield* driver.detectRepository(cwd);
|
||||
assert.equal(identity?.kind, input.kind);
|
||||
assert.isTrue(identity?.rootPath.endsWith(realCwd));
|
||||
assert.isTrue(identity?.rootPath.endsWith(cwd));
|
||||
assert.equal(identity?.freshness.source, "live-local");
|
||||
assert.isTrue(DateTime.isDateTime(identity?.freshness.observedAt));
|
||||
assert.isTrue(Option.isNone(identity?.freshness.expiresAt ?? Option.none()));
|
||||
|
||||
+33
-1
@@ -48,12 +48,14 @@ import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts";
|
||||
import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import { VcsProvisioningService } from "./vcs/VcsProvisioningService.ts";
|
||||
import { GitWorkflowService } from "./git/GitWorkflowService.ts";
|
||||
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
|
||||
import { SourceControlRepositoryService } from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import {
|
||||
BootstrapCredentialService,
|
||||
@@ -138,6 +140,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const keybindings = yield* Keybindings;
|
||||
const open = yield* Open;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsProvisioning = yield* VcsProvisioningService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
@@ -152,6 +155,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
|
||||
const sourceControlRepositories = yield* SourceControlRepositoryService;
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const serverCommandId = (tag: string) =>
|
||||
@@ -792,6 +796,32 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.sourceControlLookupRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
sourceControlRepositories.lookupRepository(input),
|
||||
{
|
||||
"rpc.aggregate": "source-control",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.sourceControlCloneRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlCloneRepository,
|
||||
sourceControlRepositories.cloneRepository(input),
|
||||
{
|
||||
"rpc.aggregate": "source-control",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.sourceControlPublishRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlPublishRepository,
|
||||
sourceControlRepositories
|
||||
.publishRepository(input)
|
||||
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{
|
||||
"rpc.aggregate": "source-control",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.projectsSearchEntries]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsSearchEntries,
|
||||
@@ -938,7 +968,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
[WS_METHODS.vcsInit]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsInit,
|
||||
gitWorkflow.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
vcsProvisioning
|
||||
.initRepository(input)
|
||||
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
|
||||
@@ -21,9 +21,9 @@ import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import { cn } from "../lib/utils";
|
||||
import { parsePullRequestReference } from "../pullRequestReference";
|
||||
import { getSourceControlPresentation } from "../sourceControlPresentation";
|
||||
import { useStore } from "../store";
|
||||
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { resolveVcsTerms } from "../vcsPresentation";
|
||||
import {
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveBranchSelectionTarget,
|
||||
@@ -67,11 +67,10 @@ function getBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: "local" | "worktree";
|
||||
resolvedActiveBranch: string | null;
|
||||
refNoun: string;
|
||||
}): string {
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch, refNoun } = input;
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return `Select ${refNoun}`;
|
||||
return "Select ref";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
return `From ${resolvedActiveBranch}`;
|
||||
@@ -203,7 +202,6 @@ export function BranchToolbarBranchSelector({
|
||||
const deferredBranchQuery = useDeferredValue(branchQuery);
|
||||
|
||||
const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
|
||||
const vcsTerms = resolveVcsTerms(branchStatusQuery.data?.kind);
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
|
||||
|
||||
@@ -233,6 +231,11 @@ export function BranchToolbarBranchSelector({
|
||||
);
|
||||
const currentGitBranch =
|
||||
branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
|
||||
const sourceControlPresentation = useMemo(
|
||||
() => getSourceControlPresentation(branchStatusQuery.data?.sourceControlProvider),
|
||||
[branchStatusQuery.data?.sourceControlProvider],
|
||||
);
|
||||
const SourceControlIcon = sourceControlPresentation.Icon;
|
||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||
envMode: effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
@@ -292,11 +295,11 @@ export function BranchToolbarBranchSelector({
|
||||
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
||||
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
|
||||
const branchStatusText = isBranchesSearchPending
|
||||
? `Loading ${vcsTerms.refNounPlural}...`
|
||||
? "Loading refs..."
|
||||
: isFetchingNextPage
|
||||
? `Loading more ${vcsTerms.refNounPlural}...`
|
||||
? "Loading more refs..."
|
||||
: hasNextPage
|
||||
? `Showing ${refs.length} of ${totalBranchCount} ${vcsTerms.refNounPlural}`
|
||||
? `Showing ${refs.length} of ${totalBranchCount} refs`
|
||||
: null;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -360,7 +363,7 @@ export function BranchToolbarBranchSelector({
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to switch ${vcsTerms.refNoun}.`,
|
||||
title: "Failed to switch ref.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
@@ -392,7 +395,7 @@ export function BranchToolbarBranchSelector({
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to create and switch ${vcsTerms.refNoun}.`,
|
||||
title: "Failed to create and switch ref.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
@@ -491,7 +494,6 @@ export function BranchToolbarBranchSelector({
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
refNoun: vcsTerms.refNoun,
|
||||
});
|
||||
|
||||
function renderPickerItem(itemValue: string, index: number) {
|
||||
@@ -512,9 +514,14 @@ export function BranchToolbarBranchSelector({
|
||||
onCheckoutPullRequestRequest(prReference);
|
||||
}}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col items-start py-1">
|
||||
<span className="truncate font-medium">Checkout Pull Request</span>
|
||||
<span className="truncate text-muted-foreground text-xs">{prReference}</span>
|
||||
<div className="flex min-w-0 items-center gap-2 py-1">
|
||||
<SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="flex min-w-0 flex-col items-start">
|
||||
<span className="truncate font-medium">
|
||||
Checkout {sourceControlPresentation.terminology.singular}
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground text-xs">{prReference}</span>
|
||||
</span>
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
@@ -528,9 +535,7 @@ export function BranchToolbarBranchSelector({
|
||||
value={itemValue}
|
||||
onClick={() => createRef(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">
|
||||
Create new {vcsTerms.refNoun} "{trimmedBranchQuery}"
|
||||
</span>
|
||||
<span className="truncate">Create new ref "{trimmedBranchQuery}"</span>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -206,6 +206,7 @@ function createMockEnvironmentApi(input: {
|
||||
filesystem: {
|
||||
browse: input.browse,
|
||||
},
|
||||
sourceControl: {} as EnvironmentApi["sourceControl"],
|
||||
vcs: {} as EnvironmentApi["vcs"],
|
||||
git: {} as EnvironmentApi["git"],
|
||||
orchestration: {
|
||||
@@ -2297,7 +2298,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const checkoutItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("span")).find(
|
||||
(element) => element.textContent?.trim() === "Checkout Pull Request",
|
||||
(element) => element.textContent?.trim() === "Checkout pull request",
|
||||
) as HTMLSpanElement | null,
|
||||
"Unable to find checkout pull request option.",
|
||||
);
|
||||
@@ -4257,8 +4258,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
await waitForCommandPaletteShortcutLabel();
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
@@ -4310,8 +4310,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
await waitForCommandPaletteShortcutLabel();
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
@@ -4384,13 +4383,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
await waitForCommandPaletteShortcutLabel();
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("Local folder", { exact: true }).click();
|
||||
|
||||
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
|
||||
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
|
||||
@@ -4437,6 +4436,126 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows clone destination controls after resolving an add project repository", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-command-palette-add-project-remote" as MessageId,
|
||||
targetText: "command palette add project remote",
|
||||
}),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
keybindings: [
|
||||
{
|
||||
command: "commandPalette.toggle",
|
||||
shortcut: {
|
||||
key: "k",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.filesystemBrowse) {
|
||||
return {
|
||||
parentPath: "~/",
|
||||
entries: [{ name: "Development", fullPath: "~/Development" }],
|
||||
};
|
||||
}
|
||||
|
||||
if (body._tag === WS_METHODS.sourceControlLookupRepository) {
|
||||
return {
|
||||
provider: "github",
|
||||
nameWithOwner: "t3-oss/t3-env",
|
||||
url: "https://github.com/t3-oss/t3-env",
|
||||
sshUrl: "[email protected]:t3-oss/t3-env.git",
|
||||
};
|
||||
}
|
||||
|
||||
if (body._tag === WS_METHODS.sourceControlCloneRepository) {
|
||||
return {
|
||||
cwd: body.destinationPath,
|
||||
remoteUrl: body.remoteUrl,
|
||||
repository: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
|
||||
return {
|
||||
sequence: fixture.snapshot.snapshotSequence + 1,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("GitHub repository", { exact: true }).click();
|
||||
|
||||
const repositoryInput = await waitForCommandPaletteInput(
|
||||
"Enter GitHub repository (owner/repo)",
|
||||
);
|
||||
await page.getByPlaceholder("Enter GitHub repository (owner/repo)").fill("t3-oss/t3-env");
|
||||
await dispatchInputKey(repositoryInput, { key: "Enter" });
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const clonePathInput = document.querySelector<HTMLInputElement>(
|
||||
'input[placeholder="Enter path (e.g. ~/projects/my-app)"]',
|
||||
);
|
||||
expect(clonePathInput?.value).toBe("~/");
|
||||
expect(document.body.textContent).toContain("Repository");
|
||||
expect(document.body.textContent).toContain("t3-oss/t3-env");
|
||||
expect(document.body.textContent).toContain("https://github.com/t3-oss/t3-env");
|
||||
expect(document.body.textContent).toContain("Select where to clone");
|
||||
expect(document.body.textContent).toContain("Development");
|
||||
expect(document.body.textContent).toContain("Clone");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await page
|
||||
.getByPlaceholder("Enter path (e.g. ~/projects/my-app)")
|
||||
.fill("~/Development/t3env");
|
||||
const clonePathInput = await waitForCommandPaletteInput(
|
||||
"Enter path (e.g. ~/projects/my-app)",
|
||||
);
|
||||
await dispatchInputKey(clonePathInput, { key: "Enter" });
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const cloneRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.sourceControlCloneRepository,
|
||||
) as { destinationPath?: string; remoteUrl?: string } | undefined;
|
||||
expect(cloneRequest).toMatchObject({
|
||||
remoteUrl: "[email protected]:t3-oss/t3-env.git",
|
||||
destinationPath: "~/Development/t3env",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens add project browse mode from the sidebar add button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -4789,6 +4908,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("Local folder", { exact: true }).click();
|
||||
await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument();
|
||||
await expect
|
||||
.element(palette.getByText("This device", { exact: true }).first())
|
||||
@@ -5004,6 +5124,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("Local folder", { exact: true }).click();
|
||||
|
||||
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
|
||||
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
|
||||
|
||||
@@ -1458,8 +1458,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
? terminalLaunchContext
|
||||
: (storeServerTerminalLaunchContext ?? null);
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const vcsKind = gitStatusQuery.data?.kind ?? null;
|
||||
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const terminalShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
context: {
|
||||
@@ -2137,7 +2136,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
: (activeThread?.branch ?? null);
|
||||
const sendEnvMode = resolveSendEnvMode({
|
||||
requestedEnvMode: envMode,
|
||||
isGitRepo: isVcsRepo,
|
||||
isGitRepo,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -3298,8 +3297,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.name}
|
||||
isVcsRepo={isVcsRepo}
|
||||
vcsKind={vcsKind}
|
||||
isGitRepo={isGitRepo}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
@@ -3379,7 +3377,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
<div
|
||||
className={cn(
|
||||
"pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-1.5 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-2",
|
||||
isVcsRepo
|
||||
isGitRepo
|
||||
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
|
||||
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
|
||||
)}
|
||||
@@ -3452,7 +3450,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
{isVcsRepo && (
|
||||
{isGitRepo && (
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
type FilesystemBrowseResult,
|
||||
type ProjectId,
|
||||
ProviderInstanceId,
|
||||
type SourceControlProviderKind,
|
||||
type SourceControlRepositoryInfo,
|
||||
} from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
@@ -17,6 +19,7 @@ import {
|
||||
CornerLeftUpIcon,
|
||||
FolderIcon,
|
||||
FolderPlusIcon,
|
||||
LinkIcon,
|
||||
MessageSquareIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
@@ -89,6 +92,7 @@ import {
|
||||
} from "./CommandPalette.logic";
|
||||
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { GitHubIcon, GitLabIcon } from "./Icons";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
@@ -139,6 +143,70 @@ interface AddProjectEnvironmentOption {
|
||||
readonly isPrimary: boolean;
|
||||
}
|
||||
|
||||
type AddProjectRemoteProviderKind = Extract<SourceControlProviderKind, "github" | "gitlab">;
|
||||
type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
|
||||
|
||||
type AddProjectCloneFlow =
|
||||
| {
|
||||
readonly step: "repository";
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly source: AddProjectRemoteSource;
|
||||
}
|
||||
| {
|
||||
readonly step: "confirm";
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly source: AddProjectRemoteSource;
|
||||
readonly repositoryInput: string;
|
||||
readonly repository: SourceControlRepositoryInfo | null;
|
||||
readonly remoteUrl: string;
|
||||
};
|
||||
|
||||
const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = ["github", "gitlab", "url"];
|
||||
|
||||
function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {
|
||||
switch (source) {
|
||||
case "github":
|
||||
return "GitHub";
|
||||
case "gitlab":
|
||||
return "GitLab";
|
||||
case "url":
|
||||
return "Git URL";
|
||||
}
|
||||
}
|
||||
|
||||
function remoteProjectSourceProvider(
|
||||
source: AddProjectRemoteSource,
|
||||
): AddProjectRemoteProviderKind | null {
|
||||
return source === "url" ? null : source;
|
||||
}
|
||||
|
||||
function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: string): ReactNode {
|
||||
switch (source) {
|
||||
case "github":
|
||||
return <GitHubIcon className={className} />;
|
||||
case "gitlab":
|
||||
return <GitLabIcon className={className} />;
|
||||
case "url":
|
||||
return <LinkIcon className={className} />;
|
||||
}
|
||||
}
|
||||
|
||||
function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null {
|
||||
if (!flow) return null;
|
||||
if (flow.step === "confirm") return null;
|
||||
if (flow.source === "url") {
|
||||
return "Enter Git clone URL";
|
||||
}
|
||||
return `Enter ${remoteProjectSourceLabel(flow.source)} repository (owner/repo)`;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
return "An error occurred.";
|
||||
}
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
@@ -227,6 +295,9 @@ function OpenCommandPaletteDialog() {
|
||||
null,
|
||||
);
|
||||
const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);
|
||||
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
|
||||
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
|
||||
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null;
|
||||
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId);
|
||||
@@ -295,7 +366,10 @@ function OpenCommandPaletteDialog() {
|
||||
: null;
|
||||
return getEnvironmentBrowsePlatform(os);
|
||||
}, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]);
|
||||
const isBrowsing = isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
|
||||
const isRemoteProjectCloneFlow = addProjectCloneFlow !== null;
|
||||
const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository";
|
||||
const isBrowsing =
|
||||
!isRemoteProjectRepositoryStep && isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
|
||||
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
|
||||
const getAddProjectInitialQueryForEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId | null): string => {
|
||||
@@ -541,6 +615,7 @@ function OpenCommandPaletteDialog() {
|
||||
}
|
||||
|
||||
function popView(): void {
|
||||
setAddProjectCloneFlow(null);
|
||||
if (viewStack.length <= 1) {
|
||||
setAddProjectEnvironmentId(null);
|
||||
}
|
||||
@@ -560,6 +635,7 @@ function OpenCommandPaletteDialog() {
|
||||
const startAddProjectBrowse = useCallback(
|
||||
(environmentId: EnvironmentId): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow(null);
|
||||
pushPaletteView({
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [],
|
||||
@@ -569,6 +645,19 @@ function OpenCommandPaletteDialog() {
|
||||
[getAddProjectInitialQueryForEnvironment],
|
||||
);
|
||||
|
||||
const startAddProjectClone = useCallback(
|
||||
(environmentId: EnvironmentId, source: AddProjectRemoteSource): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow({ step: "repository", environmentId, source });
|
||||
pushPaletteView({
|
||||
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
|
||||
groups: [],
|
||||
initialQuery: "",
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
|
||||
(option) => ({
|
||||
kind: "action",
|
||||
@@ -595,6 +684,156 @@ function OpenCommandPaletteDialog() {
|
||||
[addProjectEnvironmentItems],
|
||||
);
|
||||
|
||||
const addProjectRemoteEnvironmentGroups = useMemo<
|
||||
Record<AddProjectRemoteSource, CommandPaletteView["groups"]>
|
||||
>(() => {
|
||||
const buildGroups = (source: AddProjectRemoteSource): CommandPaletteView["groups"] => [
|
||||
{
|
||||
value: `environments:${source}`,
|
||||
label: "Environments",
|
||||
items: addProjectEnvironmentOptions.map((option) => ({
|
||||
kind: "action" as const,
|
||||
value: `action:add-project:${source}:environment:${option.environmentId}`,
|
||||
searchTerms: [
|
||||
option.label,
|
||||
option.environmentId,
|
||||
option.isPrimary ? "this device" : "",
|
||||
remoteProjectSourceLabel(source),
|
||||
],
|
||||
title: option.label,
|
||||
description: option.isPrimary ? "This device" : option.environmentId,
|
||||
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectClone(option.environmentId, source);
|
||||
},
|
||||
})),
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
github: buildGroups("github"),
|
||||
gitlab: buildGroups("gitlab"),
|
||||
url: buildGroups("url"),
|
||||
};
|
||||
}, [addProjectEnvironmentOptions, startAddProjectClone]);
|
||||
|
||||
const openAddProjectCloneFlow = useCallback(
|
||||
(source: AddProjectRemoteSource) => {
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
pushPaletteView({
|
||||
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
|
||||
groups: addProjectRemoteEnvironmentGroups[source],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const environmentId = defaultAddProjectEnvironmentId;
|
||||
if (!environmentId) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to clone project",
|
||||
description: "No environment is available.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
startAddProjectClone(environmentId, source);
|
||||
},
|
||||
[
|
||||
addProjectEnvironmentOptions.length,
|
||||
addProjectRemoteEnvironmentGroups,
|
||||
defaultAddProjectEnvironmentId,
|
||||
startAddProjectClone,
|
||||
],
|
||||
);
|
||||
|
||||
const addProjectSourceGroups = useMemo<CommandPaletteView["groups"]>(() => {
|
||||
const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
sourceItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:add-project:local",
|
||||
searchTerms: ["local", "folder", "directory", "browse", "environment"],
|
||||
title: "Local folder",
|
||||
description: "Browse a folder on disk",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectEnvironmentGroups,
|
||||
});
|
||||
} else {
|
||||
sourceItems.push({
|
||||
kind: "action",
|
||||
value: "action:add-project:local",
|
||||
searchTerms: ["local", "folder", "directory", "browse"],
|
||||
title: "Local folder",
|
||||
description: "Browse a folder on disk",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
const environmentId = defaultAddProjectEnvironmentId;
|
||||
if (!environmentId) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to browse projects",
|
||||
description: "No environment is available.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
startAddProjectBrowse(environmentId);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (const source of REMOTE_PROJECT_SOURCES) {
|
||||
const label = remoteProjectSourceLabel(source);
|
||||
const title = source === "url" ? "Git URL" : `${label} repository`;
|
||||
const description =
|
||||
source === "url" ? "Clone from a remote URL" : `Clone ${label} owner/repo`;
|
||||
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
sourceItems.push({
|
||||
kind: "submenu",
|
||||
value: `action:add-project:${source}`,
|
||||
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
|
||||
title,
|
||||
description,
|
||||
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
|
||||
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
|
||||
groups: addProjectRemoteEnvironmentGroups[source],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
sourceItems.push({
|
||||
kind: "action",
|
||||
value: `action:add-project:${source}`,
|
||||
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
|
||||
title,
|
||||
description,
|
||||
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
openAddProjectCloneFlow(source);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return [{ value: "sources", label: "Sources", items: sourceItems }];
|
||||
}, [
|
||||
addProjectEnvironmentGroups,
|
||||
addProjectEnvironmentOptions.length,
|
||||
addProjectRemoteEnvironmentGroups,
|
||||
defaultAddProjectEnvironmentId,
|
||||
openAddProjectCloneFlow,
|
||||
startAddProjectBrowse,
|
||||
]);
|
||||
|
||||
const openAddProjectFlow = useCallback(() => {
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
pushPaletteView({
|
||||
@@ -674,29 +913,29 @@ function OpenCommandPaletteDialog() {
|
||||
});
|
||||
}
|
||||
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:add-project",
|
||||
searchTerms: ["add project", "folder", "directory", "browse", "environment"],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectEnvironmentGroups,
|
||||
});
|
||||
} else {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:add-project",
|
||||
searchTerms: ["add project", "folder", "directory", "browse"],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
openAddProjectFlow();
|
||||
},
|
||||
});
|
||||
}
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:add-project",
|
||||
searchTerms: [
|
||||
"add project",
|
||||
"folder",
|
||||
"directory",
|
||||
"browse",
|
||||
"clone",
|
||||
"remote",
|
||||
"repository",
|
||||
"repo",
|
||||
"git",
|
||||
"github",
|
||||
"gitlab",
|
||||
"url",
|
||||
"environment",
|
||||
],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectSourceGroups,
|
||||
});
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
@@ -820,6 +1059,137 @@ function OpenCommandPaletteDialog() {
|
||||
],
|
||||
);
|
||||
|
||||
function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
|
||||
return getAddProjectInitialQueryForEnvironment(environmentId);
|
||||
}
|
||||
|
||||
async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> {
|
||||
if (!addProjectCloneFlow) {
|
||||
return;
|
||||
}
|
||||
|
||||
const api = readEnvironmentApi(addProjectCloneFlow.environmentId);
|
||||
if (!api) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to clone project",
|
||||
description: "Environment API is not available.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (addProjectCloneFlow.step === "repository") {
|
||||
const rawRepository = query.trim();
|
||||
if (rawRepository.length === 0 || isRemoteProjectLookingUp) {
|
||||
return;
|
||||
}
|
||||
|
||||
const provider = remoteProjectSourceProvider(addProjectCloneFlow.source);
|
||||
if (!provider) {
|
||||
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
|
||||
setAddProjectCloneFlow({
|
||||
step: "confirm",
|
||||
environmentId: addProjectCloneFlow.environmentId,
|
||||
source: addProjectCloneFlow.source,
|
||||
repositoryInput: rawRepository,
|
||||
repository: null,
|
||||
remoteUrl: rawRepository,
|
||||
});
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(destinationPath);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRemoteProjectLookingUp(true);
|
||||
try {
|
||||
const repository = await api.sourceControl.lookupRepository({
|
||||
provider,
|
||||
repository: rawRepository,
|
||||
});
|
||||
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
|
||||
setAddProjectCloneFlow({
|
||||
step: "confirm",
|
||||
environmentId: addProjectCloneFlow.environmentId,
|
||||
source: addProjectCloneFlow.source,
|
||||
repositoryInput: rawRepository,
|
||||
repository,
|
||||
remoteUrl: repository.sshUrl,
|
||||
});
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(destinationPath);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Repository lookup failed",
|
||||
description: errorMessage(error),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsRemoteProjectLookingUp(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const rawDestination = (destinationPathInput ?? query).trim();
|
||||
if (rawDestination.length === 0 || isRemoteProjectCloning) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Clone failed",
|
||||
description: "Windows-style paths are only supported on Windows.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Clone failed",
|
||||
description: "Relative paths require an active project.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const destinationPath = resolveProjectPathForDispatch(
|
||||
rawDestination,
|
||||
currentProjectCwdForBrowse,
|
||||
);
|
||||
if (destinationPath.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRemoteProjectCloning(true);
|
||||
try {
|
||||
const result = await api.sourceControl.cloneRepository({
|
||||
remoteUrl: addProjectCloneFlow.remoteUrl,
|
||||
destinationPath,
|
||||
});
|
||||
await handleAddProject(result.cwd);
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Clone failed",
|
||||
description: errorMessage(error),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsRemoteProjectCloning(false);
|
||||
}
|
||||
}
|
||||
|
||||
function browseTo(name: string): void {
|
||||
const nextQuery = appendBrowsePathSegment(query, name);
|
||||
setHighlightedItemValue(null);
|
||||
@@ -858,13 +1228,38 @@ function OpenCommandPaletteDialog() {
|
||||
browseUp,
|
||||
browseTo,
|
||||
});
|
||||
const cloneDestinationBrowseGroups = useMemo(
|
||||
() =>
|
||||
browseGroups.map((group) =>
|
||||
group.value === "directories" ? { ...group, label: "Select where to clone" } : group,
|
||||
),
|
||||
[browseGroups],
|
||||
);
|
||||
|
||||
let displayedGroups = filteredGroups;
|
||||
if (isBrowsing) {
|
||||
const remoteProjectContext = useMemo(() => {
|
||||
if (addProjectCloneFlow?.step !== "confirm") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
title: addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.repositoryInput,
|
||||
description: addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl,
|
||||
icon: remoteProjectSourceIcon(addProjectCloneFlow.source, ITEM_ICON_CLASS),
|
||||
};
|
||||
}, [addProjectCloneFlow]);
|
||||
|
||||
let displayedGroups: CommandPaletteView["groups"] = filteredGroups;
|
||||
if (addProjectCloneFlow?.step === "repository") {
|
||||
displayedGroups = [];
|
||||
} else if (addProjectCloneFlow?.step === "confirm") {
|
||||
displayedGroups = relativePathNeedsActiveProject ? [] : cloneDestinationBrowseGroups;
|
||||
} else if (isBrowsing) {
|
||||
displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
|
||||
}
|
||||
|
||||
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
|
||||
const inputPlaceholder =
|
||||
remoteProjectInputPlaceholder(addProjectCloneFlow) ??
|
||||
getCommandPaletteInputPlaceholder(paletteMode);
|
||||
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
|
||||
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
|
||||
const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
|
||||
@@ -876,8 +1271,25 @@ function OpenCommandPaletteDialog() {
|
||||
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
|
||||
const submitActionLabel = willCreateProjectPath ? "Create & Add" : "Add";
|
||||
const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm";
|
||||
const submitActionLabel = isCloneDestinationStep
|
||||
? willCreateProjectPath
|
||||
? "Create & Clone"
|
||||
: "Clone"
|
||||
: willCreateProjectPath
|
||||
? "Create & Add"
|
||||
: "Add";
|
||||
const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter";
|
||||
const remoteProjectButtonLabel = addProjectCloneFlow
|
||||
? addProjectCloneFlow.source === "url"
|
||||
? "Continue"
|
||||
: "Lookup"
|
||||
: null;
|
||||
const isRemoteProjectPending = isRemoteProjectLookingUp || isRemoteProjectCloning;
|
||||
const canSubmitRemoteProjectFlow =
|
||||
addProjectCloneFlow?.step === "repository" &&
|
||||
query.trim().length > 0 &&
|
||||
!isRemoteProjectPending;
|
||||
const fileManagerName = getLocalFileManagerName(navigator.platform);
|
||||
const canOpenProjectFromFileManager =
|
||||
isBrowsing &&
|
||||
@@ -915,6 +1327,12 @@ function OpenCommandPaletteDialog() {
|
||||
}
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
|
||||
if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
void submitAddProjectCloneFlow();
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldSubmitBrowsePath =
|
||||
canSubmitBrowsePath &&
|
||||
event.key === "Enter" &&
|
||||
@@ -922,7 +1340,11 @@ function OpenCommandPaletteDialog() {
|
||||
|
||||
if (shouldSubmitBrowsePath) {
|
||||
event.preventDefault();
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -999,9 +1421,9 @@ function OpenCommandPaletteDialog() {
|
||||
}}
|
||||
>
|
||||
<Command
|
||||
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
|
||||
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}`}
|
||||
aria-label="Command palette"
|
||||
autoHighlight={isBrowsing ? false : "always"}
|
||||
autoHighlight={isBrowsing || isRemoteProjectCloneFlow ? false : "always"}
|
||||
mode="none"
|
||||
onItemHighlighted={(value) => {
|
||||
setHighlightedItemValue(typeof value === "string" ? value : null);
|
||||
@@ -1011,7 +1433,15 @@ function OpenCommandPaletteDialog() {
|
||||
>
|
||||
<div className="relative">
|
||||
<CommandInput
|
||||
className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
|
||||
className={
|
||||
addProjectCloneFlow?.step === "repository"
|
||||
? "pe-32"
|
||||
: isBrowsing
|
||||
? willCreateProjectPath
|
||||
? "pe-36"
|
||||
: "pe-16"
|
||||
: undefined
|
||||
}
|
||||
placeholder={inputPlaceholder}
|
||||
wrapperClassName={
|
||||
isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
|
||||
@@ -1036,7 +1466,28 @@ function OpenCommandPaletteDialog() {
|
||||
: {})}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
{isBrowsing ? (
|
||||
{addProjectCloneFlow?.step === "repository" ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className="absolute end-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
|
||||
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
disabled={!canSubmitRemoteProjectFlow}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
void submitAddProjectCloneFlow();
|
||||
}}
|
||||
title={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
>
|
||||
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>Enter</Kbd>
|
||||
</KbdGroup>
|
||||
</Button>
|
||||
) : isBrowsing ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
@@ -1046,7 +1497,9 @@ function OpenCommandPaletteDialog() {
|
||||
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
|
||||
)}
|
||||
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
disabled={relativePathNeedsActiveProject}
|
||||
disabled={
|
||||
relativePathNeedsActiveProject || (isCloneDestinationStep && isRemoteProjectPending)
|
||||
}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
@@ -1054,11 +1507,17 @@ function OpenCommandPaletteDialog() {
|
||||
if (relativePathNeedsActiveProject) {
|
||||
return;
|
||||
}
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
}}
|
||||
title={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
>
|
||||
<span>{submitActionLabel}</span>
|
||||
<span>
|
||||
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
|
||||
</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
|
||||
</KbdGroup>
|
||||
@@ -1066,19 +1525,47 @@ function OpenCommandPaletteDialog() {
|
||||
) : null}
|
||||
</div>
|
||||
<CommandPanel className="max-h-[min(28rem,70vh)]">
|
||||
{remoteProjectContext ? (
|
||||
<div className="p-2 pb-0">
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Repository
|
||||
</div>
|
||||
<div className="flex min-h-8 items-center gap-2 rounded-sm px-2 py-1.5">
|
||||
{remoteProjectContext.icon}
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-foreground text-sm">
|
||||
{remoteProjectContext.title}
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">
|
||||
{remoteProjectContext.description}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<CommandPaletteResults
|
||||
groups={displayedGroups}
|
||||
highlightedItemValue={highlightedItemValue}
|
||||
isActionsOnly={isActionsOnly}
|
||||
keybindings={keybindings}
|
||||
onExecuteItem={executeItem}
|
||||
{...(relativePathNeedsActiveProject
|
||||
? { emptyStateMessage: "Relative paths require an active project." }
|
||||
: willCreateProjectPath
|
||||
? {
|
||||
emptyStateMessage: "Press Enter to create this folder and add it as a project.",
|
||||
}
|
||||
: {})}
|
||||
{...(addProjectCloneFlow?.step === "repository"
|
||||
? {
|
||||
emptyStateMessage:
|
||||
addProjectCloneFlow.source === "url"
|
||||
? "Enter a Git clone URL and press Enter to continue."
|
||||
: "Enter a repository path and press Enter to look it up.",
|
||||
}
|
||||
: addProjectCloneFlow?.step === "confirm"
|
||||
? { emptyStateMessage: "Choose a destination path and press Enter to clone." }
|
||||
: relativePathNeedsActiveProject
|
||||
? { emptyStateMessage: "Relative paths require an active project." }
|
||||
: willCreateProjectPath
|
||||
? {
|
||||
emptyStateMessage:
|
||||
"Press Enter to create this folder and add it as a project.",
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</CommandPanel>
|
||||
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
|
||||
@@ -1092,7 +1579,14 @@ function OpenCommandPaletteDialog() {
|
||||
</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Navigate</span>
|
||||
</KbdGroup>
|
||||
{!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
|
||||
{addProjectCloneFlow?.step === "repository" ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>
|
||||
{remoteProjectButtonLabel ?? "Continue"}
|
||||
</span>
|
||||
</KbdGroup>
|
||||
) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Select</span>
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
Rows3Icon,
|
||||
TextWrapIcon,
|
||||
} from "lucide-react";
|
||||
@@ -35,7 +36,6 @@ import { createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { resolveVcsTerms } from "../vcsPresentation";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
@@ -173,6 +173,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const settings = useSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const previousDiffOpenRef = useRef(false);
|
||||
@@ -202,8 +203,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
environmentId: activeThread?.environmentId ?? null,
|
||||
cwd: activeCwd ?? null,
|
||||
});
|
||||
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const vcsTerms = resolveVcsTerms(gitStatusQuery.data?.kind);
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -279,8 +279,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
threadId: activeThreadId,
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
ignoreWhitespace: diffIgnoreWhitespace,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
enabled: isVcsRepo,
|
||||
enabled: isGitRepo,
|
||||
}),
|
||||
);
|
||||
const selectedTurnCheckpointDiff = selectedTurn
|
||||
@@ -319,9 +320,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
useEffect(() => {
|
||||
if (diffOpen && !previousDiffOpenRef.current) {
|
||||
setDiffWordWrap(settings.diffWordWrap);
|
||||
setDiffIgnoreWhitespace(settings.diffIgnoreWhitespace);
|
||||
}
|
||||
previousDiffOpenRef.current = diffOpen;
|
||||
}, [diffOpen, settings.diffWordWrap]);
|
||||
}, [diffOpen, settings.diffIgnoreWhitespace, settings.diffWordWrap]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath || !patchViewportRef.current) {
|
||||
@@ -553,6 +555,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<TextWrapIcon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle
|
||||
aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffIgnoreWhitespace}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffIgnoreWhitespace(Boolean(pressed));
|
||||
}}
|
||||
>
|
||||
<PilcrowIcon className="size-3" />
|
||||
</Toggle>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
@@ -563,9 +577,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : !isVcsRepo ? (
|
||||
) : !isGitRepo ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Turn diffs are unavailable because this project is not a {vcsTerms.repositoryNoun}.
|
||||
Turn diffs are unavailable because this project is not a git repository.
|
||||
</div>
|
||||
) : orderedTurnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
|
||||
@@ -100,12 +100,14 @@ vi.mock("~/editorPreferences", () => ({
|
||||
vi.mock("~/lib/gitReactQuery", () => ({
|
||||
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
|
||||
gitMutationKeys: {
|
||||
publishRepository: vi.fn(() => ["publish-repository"]),
|
||||
pull: vi.fn(() => ["pull"]),
|
||||
runStackedAction: vi.fn(() => ["run-stacked-action"]),
|
||||
},
|
||||
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
|
||||
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
|
||||
invalidateGitQueries: invalidateGitQueriesSpy,
|
||||
sourceControlPublishRepositoryMutationOptions: vi.fn(() => ({ __kind: "publish-repository" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/lib/gitStatusState", () => ({
|
||||
@@ -113,7 +115,6 @@ vi.mock("~/lib/gitStatusState", () => ({
|
||||
resetGitStatusStateForTests: () => undefined,
|
||||
useGitStatus: vi.fn(() => ({
|
||||
data: {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
sourceControlProvider: {
|
||||
kind: "github",
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
@@ -254,7 +253,53 @@ describe("when: ref is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: source control provider uses merge requests", () => {
|
||||
it("uses GitLab MR terminology in quick actions and menu items", () => {
|
||||
const gitlabStatus = status({
|
||||
aheadCount: 2,
|
||||
sourceControlProvider: {
|
||||
kind: "gitlab",
|
||||
name: "GitLab",
|
||||
baseUrl: "https://gitlab.com",
|
||||
},
|
||||
});
|
||||
|
||||
const quick = resolveQuickAction(gitlabStatus, false);
|
||||
const items = buildMenuItems(gitlabStatus, false);
|
||||
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
label: "Push & create MR",
|
||||
});
|
||||
assert.deepInclude(items[2], {
|
||||
id: "pr",
|
||||
label: "Create MR",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is clean, up to date, and has no open PR", () => {
|
||||
it("enables create PR when synced with upstream but ahead of default", () => {
|
||||
const syncedFeature = status({
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 1,
|
||||
pr: null,
|
||||
});
|
||||
|
||||
const quick = resolveQuickAction(syncedFeature, false);
|
||||
assert.deepInclude(quick, {
|
||||
label: "Create PR",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
});
|
||||
|
||||
const items = buildMenuItems(syncedFeature, false);
|
||||
assert.equal(items.find((item) => item.id === "pr")?.disabled, false);
|
||||
});
|
||||
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||
@@ -419,6 +464,48 @@ describe("when: working tree has local changes", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("buildMenuItems enables push for ahead commits while local changes remain uncommitted", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
refName: "feature/test",
|
||||
hasWorkingTreeChanges: true,
|
||||
aheadCount: 1,
|
||||
workingTree: {
|
||||
files: [{ path: ".vercel/project.json", insertions: 1, deletions: 0 }],
|
||||
insertions: 1,
|
||||
deletions: 0,
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: false,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
icon: "push",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "push",
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: true,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "create_pr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: on default ref without open PR", () => {
|
||||
@@ -643,7 +730,7 @@ describe("when: ref has no upstream configured", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction disables push-and-pr flows when no origin remote exists", () => {
|
||||
it("resolveQuickAction publishes when no origin remote exists", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
@@ -655,10 +742,9 @@ describe("when: ref has no upstream configured", () => {
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(quick, {
|
||||
kind: "show_hint",
|
||||
label: "Push",
|
||||
hint: 'Add an "origin" remote before pushing or creating a PR.',
|
||||
disabled: true,
|
||||
kind: "open_publish",
|
||||
label: "Publish repository",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -692,7 +778,7 @@ describe("when: ref has no upstream configured", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("buildMenuItems disables push and create PR when no origin remote exists", () => {
|
||||
it("buildMenuItems hides push and create PR when no origin remote exists", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
|
||||
false,
|
||||
@@ -707,22 +793,6 @@ describe("when: ref has no upstream configured", () => {
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
icon: "push",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "push",
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: true,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "create_pr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -841,7 +911,7 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
assert.deepEqual(copy, {
|
||||
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 ref or create a feature ref and run the same action there.',
|
||||
'This action will push local commits and create a pull request on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
continueLabel: "Push & create PR",
|
||||
});
|
||||
});
|
||||
@@ -856,7 +926,7 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
assert.deepEqual(copy, {
|
||||
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 ref or create a feature ref and run the same action there.',
|
||||
'This action will commit, push, and create a pull request on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
continueLabel: "Commit, push & create PR",
|
||||
});
|
||||
});
|
||||
@@ -885,7 +955,7 @@ describe("buildGitActionProgressStages", () => {
|
||||
"Pushing to origin/feature/test...",
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating GitHub pull request...",
|
||||
"Creating pull request...",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -899,7 +969,7 @@ describe("buildGitActionProgressStages", () => {
|
||||
assert.deepEqual(stages, [
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating GitHub pull request...",
|
||||
"Creating pull request...",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -929,7 +999,7 @@ describe("buildGitActionProgressStages", () => {
|
||||
"Pushing to origin/feature/test...",
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating GitHub pull request...",
|
||||
"Creating pull request...",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,11 @@ import type {
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
import {
|
||||
DEFAULT_CHANGE_REQUEST_TERMINOLOGY,
|
||||
getChangeRequestTerminology,
|
||||
type ChangeRequestTerminology,
|
||||
} from "../sourceControlPresentation";
|
||||
|
||||
export type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
@@ -21,7 +26,7 @@ export interface GitActionMenuItem {
|
||||
export interface GitQuickAction {
|
||||
label: string;
|
||||
disabled: boolean;
|
||||
kind: "run_action" | "run_pull" | "open_pr" | "show_hint";
|
||||
kind: "run_action" | "run_pull" | "open_pr" | "open_publish" | "show_hint";
|
||||
action?: GitStackedAction;
|
||||
hint?: string;
|
||||
}
|
||||
@@ -38,6 +43,14 @@ export type DefaultBranchConfirmableAction =
|
||||
| "commit_push"
|
||||
| "commit_push_pr";
|
||||
|
||||
function resolveChangeRequestTerminology(
|
||||
gitStatus: VcsStatusResult | null,
|
||||
): ChangeRequestTerminology {
|
||||
return gitStatus?.sourceControlProvider
|
||||
? getChangeRequestTerminology(gitStatus.sourceControlProvider)
|
||||
: DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
}
|
||||
|
||||
export function buildGitActionProgressStages(input: {
|
||||
action: GitStackedAction;
|
||||
hasCustomCommitMessage: boolean;
|
||||
@@ -45,13 +58,15 @@ export function buildGitActionProgressStages(input: {
|
||||
pushTarget?: string;
|
||||
featureBranch?: boolean;
|
||||
shouldPushBeforePr?: boolean;
|
||||
terminology?: ChangeRequestTerminology;
|
||||
}): string[] {
|
||||
const terminology = input.terminology ?? DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
const branchStages = input.featureBranch ? ["Preparing feature ref..."] : [];
|
||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||
const prStages = [
|
||||
"Preparing PR...",
|
||||
"Generating PR content...",
|
||||
"Creating GitHub pull request...",
|
||||
`Preparing ${terminology.shortLabel}...`,
|
||||
`Generating ${terminology.shortLabel} content...`,
|
||||
`Creating ${terminology.singular}...`,
|
||||
];
|
||||
|
||||
if (input.action === "push") {
|
||||
@@ -82,17 +97,18 @@ export function buildMenuItems(
|
||||
hasPrimaryRemote = true,
|
||||
): GitActionMenuItem[] {
|
||||
if (!gitStatus) return [];
|
||||
const terminology = resolveChangeRequestTerminology(gitStatus);
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
|
||||
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
const canPush =
|
||||
!isBusy &&
|
||||
hasBranch &&
|
||||
!hasChanges &&
|
||||
!isBehind &&
|
||||
gitStatus.aheadCount > 0 &&
|
||||
(gitStatus.hasUpstream || canPushWithoutUpstream);
|
||||
@@ -101,20 +117,26 @@ export function buildMenuItems(
|
||||
hasBranch &&
|
||||
!hasChanges &&
|
||||
!hasOpenPr &&
|
||||
gitStatus.aheadCount > 0 &&
|
||||
hasDefaultBranchDelta &&
|
||||
!isBehind &&
|
||||
(gitStatus.hasUpstream || canPushWithoutUpstream);
|
||||
const canOpenPr = !isBusy && hasOpenPr;
|
||||
|
||||
const commitItem: GitActionMenuItem = {
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: !canCommit,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
};
|
||||
|
||||
if (!hasPrimaryRemote) {
|
||||
return [commitItem];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: !canCommit,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
commitItem,
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
@@ -126,14 +148,14 @@ export function buildMenuItems(
|
||||
hasOpenPr
|
||||
? {
|
||||
id: "pr",
|
||||
label: "View PR",
|
||||
label: `View ${terminology.shortLabel}`,
|
||||
disabled: !canOpenPr,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
}
|
||||
: {
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
label: `Create ${terminology.shortLabel}`,
|
||||
disabled: !canCreatePr,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
@@ -165,15 +187,17 @@ export function resolveQuickAction(
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
const terminology = resolveChangeRequestTerminology(gitStatus);
|
||||
|
||||
if (!hasBranch) {
|
||||
return {
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "Create and checkout a ref before pushing or opening a PR.",
|
||||
hint: `Create and checkout a ref before pushing or opening a ${terminology.singular}.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -185,7 +209,7 @@ export function resolveQuickAction(
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
label: "Commit, push & PR",
|
||||
label: `Commit, push & ${terminology.shortLabel}`,
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
@@ -195,18 +219,17 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!hasPrimaryRemote) {
|
||||
if (hasOpenPr && !isAhead) {
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: 'Add an "origin" remote before pushing or creating a PR.',
|
||||
label: "Publish repository",
|
||||
disabled: false,
|
||||
kind: "open_publish",
|
||||
};
|
||||
}
|
||||
if (!isAhead) {
|
||||
if (hasOpenPr) {
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
@@ -224,7 +247,7 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: "Push & create PR",
|
||||
label: `Push & create ${terminology.shortLabel}`,
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
@@ -258,7 +281,7 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: "Push & create PR",
|
||||
label: `Push & create ${terminology.shortLabel}`,
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
@@ -266,7 +289,16 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (hasOpenPr && gitStatus.hasUpstream) {
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
if (hasDefaultBranchDelta && !isDefaultRef) {
|
||||
return {
|
||||
label: `Create ${terminology.shortLabel}`,
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "create_pr",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -294,9 +326,11 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
action: DefaultBranchConfirmableAction;
|
||||
branchName: string;
|
||||
includesCommit: boolean;
|
||||
terminology?: ChangeRequestTerminology;
|
||||
}): DefaultBranchActionDialogCopy {
|
||||
const branchLabel = input.branchName;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this ref or create a feature ref and run the same action there.`;
|
||||
const terminology = input.terminology ?? DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
|
||||
if (input.action === "push" || input.action === "commit_push") {
|
||||
if (input.includesCommit) {
|
||||
@@ -315,15 +349,15 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit, push & create PR from default ref?",
|
||||
description: `This action will commit, push, and create a PR${suffix}`,
|
||||
continueLabel: `Commit, push & create PR`,
|
||||
title: `Commit, push & create ${terminology.shortLabel} from default ref?`,
|
||||
description: `This action will commit, push, and create a ${terminology.singular}${suffix}`,
|
||||
continueLabel: `Commit, push & create ${terminology.shortLabel}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push & create PR from default ref?",
|
||||
description: `This action will push local commits and create a PR${suffix}`,
|
||||
continueLabel: "Push & create PR",
|
||||
title: `Push & create ${terminology.shortLabel} from default ref?`,
|
||||
description: `This action will push local commits and create a ${terminology.singular}${suffix}`,
|
||||
continueLabel: `Push & create ${terminology.shortLabel}`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,30 @@ import type {
|
||||
GitActionProgressEvent,
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
SourceControlCloneProtocol,
|
||||
SourceControlProviderKind,
|
||||
SourceControlPublishRepositoryResult,
|
||||
SourceControlRepositoryVisibility,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Option } from "effect";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
CloudUploadIcon,
|
||||
ExternalLinkIcon,
|
||||
GitCommitIcon,
|
||||
InfoIcon,
|
||||
LockIcon,
|
||||
GlobeIcon,
|
||||
} from "lucide-react";
|
||||
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
|
||||
import { GitHubIcon, GitLabIcon } from "~/components/Icons";
|
||||
import { RadioGroup } from "~/components/ui/radio-group";
|
||||
import { Spinner } from "~/components/ui/spinner";
|
||||
import { cn } from "~/lib/utils";
|
||||
import {
|
||||
buildGitActionProgressStages,
|
||||
buildMenuItems,
|
||||
@@ -34,9 +52,18 @@ import {
|
||||
DialogTitle,
|
||||
} from "~/components/ui/dialog";
|
||||
import { Group, GroupSeparator } from "~/components/ui/group";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectPopup,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import { stackedThreadToast, toastManager, type ThreadToastData } from "~/components/ui/toast";
|
||||
import { openInPreferredEditor } from "~/editorPreferences";
|
||||
@@ -45,16 +72,18 @@ import {
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
gitRunStackedActionMutationOptions,
|
||||
sourceControlPublishRepositoryMutationOptions,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
|
||||
import { useSourceControlDiscovery } from "~/lib/sourceControlDiscoveryState";
|
||||
import { newCommandId, randomUUID } from "~/lib/utils";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { readEnvironmentApi } from "~/environmentApi";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { getSourceControlPresentation } from "~/sourceControlPresentation";
|
||||
import { useStore } from "~/store";
|
||||
import { createThreadSelectorByRef } from "~/storeSelectors";
|
||||
import { resolveVcsActionPresentation, resolveVcsTerms } from "~/vcsPresentation";
|
||||
|
||||
interface GitActionsControlProps {
|
||||
gitCwd: string | null;
|
||||
@@ -71,6 +100,8 @@ interface PendingDefaultBranchAction {
|
||||
filePaths?: string[];
|
||||
}
|
||||
|
||||
type PublishProviderKind = Extract<SourceControlProviderKind, "github" | "gitlab">;
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
interface ActiveGitActionProgress {
|
||||
@@ -138,6 +169,7 @@ function getMenuActionDisabledReason({
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const terminology = getSourceControlPresentation(gitStatus.sourceControlProvider).terminology;
|
||||
|
||||
if (item.id === "commit") {
|
||||
if (!hasChanges) {
|
||||
@@ -166,46 +198,59 @@ function getMenuActionDisabledReason({
|
||||
}
|
||||
|
||||
if (hasOpenPr) {
|
||||
return "View PR is currently unavailable.";
|
||||
return `View ${terminology.singular} is currently unavailable.`;
|
||||
}
|
||||
if (!hasBranch) {
|
||||
return "Detached HEAD: checkout a refName before creating a PR.";
|
||||
return `Detached HEAD: checkout a refName before creating a ${terminology.singular}.`;
|
||||
}
|
||||
if (hasChanges) {
|
||||
return "Commit local changes before creating a PR.";
|
||||
return `Commit local changes before creating a ${terminology.singular}.`;
|
||||
}
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
return 'Add an "origin" remote before creating a PR.';
|
||||
return `Add an "origin" remote before creating a ${terminology.singular}.`;
|
||||
}
|
||||
if (!isAhead) {
|
||||
return "No local commits to include in a PR.";
|
||||
return `No local commits to include in a ${terminology.singular}.`;
|
||||
}
|
||||
if (isBehind) {
|
||||
return "Branch is behind upstream. Pull/rebase before creating a PR.";
|
||||
return `Branch is behind upstream. Pull/rebase before creating a ${terminology.singular}.`;
|
||||
}
|
||||
return "Create PR is currently unavailable.";
|
||||
return `Create ${terminology.singular} is currently unavailable.`;
|
||||
}
|
||||
|
||||
const COMMIT_DIALOG_TITLE = "Commit changes";
|
||||
const COMMIT_DIALOG_DESCRIPTION =
|
||||
"Review and confirm your commit. Leave the message blank to auto-generate one.";
|
||||
|
||||
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
|
||||
function GitActionItemIcon({
|
||||
icon,
|
||||
SourceControlIcon,
|
||||
}: {
|
||||
icon: GitActionIconName;
|
||||
SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
|
||||
}) {
|
||||
if (icon === "commit") return <GitCommitIcon />;
|
||||
if (icon === "push") return <CloudUploadIcon />;
|
||||
return <GitHubIcon />;
|
||||
return <SourceControlIcon />;
|
||||
}
|
||||
|
||||
function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
function GitQuickActionIcon({
|
||||
quickAction,
|
||||
SourceControlIcon,
|
||||
}: {
|
||||
quickAction: GitQuickAction;
|
||||
SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
|
||||
}) {
|
||||
const iconClassName = "size-3.5";
|
||||
if (quickAction.kind === "open_pr") return <GitHubIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "open_pr") return <SourceControlIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "open_publish") return <CloudUploadIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_action") {
|
||||
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
|
||||
if (quickAction.action === "push" || quickAction.action === "commit_push") {
|
||||
return <CloudUploadIcon className={iconClassName} />;
|
||||
}
|
||||
return <GitHubIcon className={iconClassName} />;
|
||||
return <SourceControlIcon className={iconClassName} />;
|
||||
}
|
||||
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
|
||||
return <InfoIcon className={iconClassName} />;
|
||||
@@ -240,8 +285,35 @@ export default function GitActionsControl({
|
||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
|
||||
const [isEditingFiles, setIsEditingFiles] = useState(false);
|
||||
const [isPublishDialogOpen, setIsPublishDialogOpen] = useState(false);
|
||||
const [publishProvider, setPublishProvider] = useState<PublishProviderKind>("github");
|
||||
const [publishRepository, setPublishRepository] = useState("");
|
||||
const [publishVisibility, setPublishVisibility] =
|
||||
useState<SourceControlRepositoryVisibility>("private");
|
||||
const [publishRemoteName, setPublishRemoteName] = useState("origin");
|
||||
const [publishProtocol, setPublishProtocol] = useState<SourceControlCloneProtocol>("ssh");
|
||||
const [publishWizardStep, setPublishWizardStep] = useState(0);
|
||||
const [publishAdvancedOpen, setPublishAdvancedOpen] = useState(false);
|
||||
const [publishError, setPublishError] = useState<string | null>(null);
|
||||
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
|
||||
null,
|
||||
);
|
||||
const [hasUserEditedPublishRepository, setHasUserEditedPublishRepository] = useState(false);
|
||||
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||
useState<PendingDefaultBranchAction | null>(null);
|
||||
const sourceControlDiscovery = useSourceControlDiscovery();
|
||||
const publishAccountByProvider = useMemo(() => {
|
||||
const accounts: Record<PublishProviderKind, string | null> = { github: null, gitlab: null };
|
||||
for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
|
||||
if (provider.kind === "github" || provider.kind === "gitlab") {
|
||||
accounts[provider.kind] = Option.getOrNull(provider.auth.account);
|
||||
}
|
||||
}
|
||||
return accounts;
|
||||
}, [sourceControlDiscovery.data]);
|
||||
const publishRepositoryPrefill = publishAccountByProvider[publishProvider]
|
||||
? `${publishAccountByProvider[publishProvider]}/`
|
||||
: "";
|
||||
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
|
||||
let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise<void>;
|
||||
|
||||
@@ -323,14 +395,16 @@ export default function GitActionsControl({
|
||||
environmentId: activeEnvironmentId,
|
||||
cwd: gitCwd,
|
||||
});
|
||||
const sourceControlPresentation = useMemo(
|
||||
() => getSourceControlPresentation(gitStatus?.sourceControlProvider),
|
||||
[gitStatus?.sourceControlProvider],
|
||||
);
|
||||
const changeRequestTerminology = sourceControlPresentation.terminology;
|
||||
const SourceControlIcon = sourceControlPresentation.Icon;
|
||||
// Default to true while loading so we don't flash init controls.
|
||||
const isRepo = gitStatus?.isRepo ?? true;
|
||||
const vcsKind = gitStatus?.kind ?? null;
|
||||
const vcsTerms = resolveVcsTerms(vcsKind);
|
||||
const vcsActionPresentation = resolveVcsActionPresentation(vcsKind);
|
||||
const supportsGitWorkflowActions = !isRepo || vcsActionPresentation.supportsGitWorkflowActions;
|
||||
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
|
||||
const gitStatusForActions = supportsGitWorkflowActions ? gitStatus : null;
|
||||
const gitStatusForActions = gitStatus;
|
||||
|
||||
const allFiles = gitStatusForActions?.workingTree.files ?? [];
|
||||
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
|
||||
@@ -351,6 +425,13 @@ export default function GitActionsControl({
|
||||
const pullMutation = useMutation(
|
||||
gitPullMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }),
|
||||
);
|
||||
const publishRepositoryMutation = useMutation(
|
||||
sourceControlPublishRepositoryMutationOptions({
|
||||
environmentId: activeEnvironmentId,
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
}),
|
||||
);
|
||||
|
||||
const isRunStackedActionRunning =
|
||||
useIsMutating({
|
||||
@@ -358,7 +439,11 @@ export default function GitActionsControl({
|
||||
}) > 0;
|
||||
const isPullRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const isPublishRunning =
|
||||
useIsMutating({
|
||||
mutationKey: gitMutationKeys.publishRepository(activeEnvironmentId, gitCwd),
|
||||
}) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning || isPublishRunning;
|
||||
const isSelectingWorktreeBase =
|
||||
!activeServerThread &&
|
||||
activeDraftThread?.envMode === "worktree" &&
|
||||
@@ -408,6 +493,7 @@ export default function GitActionsControl({
|
||||
action: pendingDefaultBranchAction.action,
|
||||
branchName: pendingDefaultBranchAction.branchName,
|
||||
includesCommit: pendingDefaultBranchAction.includesCommit,
|
||||
terminology: changeRequestTerminology,
|
||||
})
|
||||
: null;
|
||||
|
||||
@@ -424,6 +510,13 @@ export default function GitActionsControl({
|
||||
};
|
||||
}, [updateActiveProgressToast]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPublishDialogOpen || hasUserEditedPublishRepository) {
|
||||
return;
|
||||
}
|
||||
setPublishRepository(publishRepositoryPrefill);
|
||||
}, [isPublishDialogOpen, hasUserEditedPublishRepository, publishRepositoryPrefill]);
|
||||
|
||||
useEffect(() => {
|
||||
if (gitCwd === null) {
|
||||
return;
|
||||
@@ -473,7 +566,7 @@ export default function GitActionsControl({
|
||||
if (!prUrl) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "No open PR found.",
|
||||
title: "No open pull request found.",
|
||||
data: threadToastData,
|
||||
});
|
||||
return;
|
||||
@@ -482,7 +575,7 @@ export default function GitActionsControl({
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
title: "Unable to open pull request link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
...(threadToastData !== undefined ? { data: threadToastData } : {}),
|
||||
}),
|
||||
@@ -539,6 +632,7 @@ export default function GitActionsControl({
|
||||
hasCustomCommitMessage: !!commitMessage?.trim(),
|
||||
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
|
||||
featureBranch,
|
||||
terminology: changeRequestTerminology,
|
||||
shouldPushBeforePr:
|
||||
action === "create_pr" &&
|
||||
(!actionStatus?.hasUpstream || (actionStatus?.aheadCount ?? 0) > 0),
|
||||
@@ -769,6 +863,10 @@ export default function GitActionsControl({
|
||||
void openExistingPr();
|
||||
return;
|
||||
}
|
||||
if (quickAction.kind === "open_publish") {
|
||||
setIsPublishDialogOpen(true);
|
||||
return;
|
||||
}
|
||||
if (quickAction.kind === "run_pull") {
|
||||
const promise = pullMutation.mutateAsync();
|
||||
void toastManager.promise<
|
||||
@@ -866,6 +964,47 @@ export default function GitActionsControl({
|
||||
[gitCwd, threadToastData],
|
||||
);
|
||||
|
||||
const canPublishRepository = isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
|
||||
const canSubmitPublishRepository = (() => {
|
||||
if (publishRepositoryMutation.isPending) return false;
|
||||
const repositoryParts = publishRepository.trim().split("/");
|
||||
const owner = repositoryParts[0]?.trim() ?? "";
|
||||
const rest = repositoryParts.slice(1);
|
||||
const name = rest.join("/").trim();
|
||||
return owner.length > 0 && name.length > 0;
|
||||
})();
|
||||
|
||||
const publishHost = publishProvider === "github" ? "github.com" : "gitlab.com";
|
||||
const publishPathPlaceholder = publishProvider === "github" ? "owner/repo" : "group/project";
|
||||
const publishProviderLabel = publishProvider === "github" ? "GitHub" : "GitLab";
|
||||
|
||||
const submitPublishRepository = () => {
|
||||
if (!canSubmitPublishRepository) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPublishError(null);
|
||||
|
||||
void publishRepositoryMutation
|
||||
.mutateAsync({
|
||||
provider: publishProvider,
|
||||
repository: publishRepository.trim(),
|
||||
visibility: publishVisibility,
|
||||
remoteName: publishRemoteName.trim() || "origin",
|
||||
protocol: publishProtocol,
|
||||
})
|
||||
.then((result) => {
|
||||
setPublishResult(result);
|
||||
setPublishWizardStep(2);
|
||||
void refreshGitStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
setPublishError(err instanceof Error ? err.message : "An error occurred.");
|
||||
});
|
||||
};
|
||||
|
||||
if (!gitCwd) return null;
|
||||
|
||||
return (
|
||||
@@ -879,25 +1018,6 @@ export default function GitActionsControl({
|
||||
>
|
||||
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
|
||||
</Button>
|
||||
) : !supportsGitWorkflowActions ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
render={
|
||||
<Button
|
||||
aria-disabled="true"
|
||||
className="cursor-not-allowed opacity-70"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{vcsTerms.systemName} {vcsTerms.repositoryNoun}
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup tooltipStyle side="bottom" align="end">
|
||||
{vcsActionPresentation.unsupportedGitWorkflowDescription}
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
) : (
|
||||
<Group aria-label="Git actions" className="shrink-0">
|
||||
{quickActionDisabledReason ? (
|
||||
@@ -913,7 +1033,10 @@ export default function GitActionsControl({
|
||||
/>
|
||||
}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<GitQuickActionIcon
|
||||
quickAction={quickAction}
|
||||
SourceControlIcon={SourceControlIcon}
|
||||
/>
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
@@ -929,7 +1052,7 @@ export default function GitActionsControl({
|
||||
disabled={isGitActionRunning || quickAction.disabled}
|
||||
onClick={runQuickAction}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<GitQuickActionIcon quickAction={quickAction} SourceControlIcon={SourceControlIcon} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
@@ -969,7 +1092,10 @@ export default function GitActionsControl({
|
||||
render={<span className="block w-max cursor-not-allowed" />}
|
||||
>
|
||||
<MenuItem className="w-full" disabled>
|
||||
<GitActionItemIcon icon={item.icon} />
|
||||
<GitActionItemIcon
|
||||
icon={item.icon}
|
||||
SourceControlIcon={SourceControlIcon}
|
||||
/>
|
||||
{item.label}
|
||||
</MenuItem>
|
||||
</PopoverTrigger>
|
||||
@@ -988,14 +1114,26 @@ export default function GitActionsControl({
|
||||
openDialogForMenuItem(item);
|
||||
}}
|
||||
>
|
||||
<GitActionItemIcon icon={item.icon} />
|
||||
<GitActionItemIcon icon={item.icon} SourceControlIcon={SourceControlIcon} />
|
||||
{item.label}
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{canPublishRepository ? (
|
||||
<MenuItem
|
||||
disabled={isGitActionRunning}
|
||||
onClick={() => {
|
||||
setIsPublishDialogOpen(true);
|
||||
}}
|
||||
>
|
||||
<CloudUploadIcon />
|
||||
Publish repository...
|
||||
</MenuItem>
|
||||
) : null}
|
||||
{gitStatusForActions?.refName === null && (
|
||||
<p className="px-2 py-1.5 text-xs text-warning">
|
||||
Detached HEAD: create and checkout a refName to enable push and PR actions.
|
||||
Detached HEAD: create and checkout a refName to enable push and pull request
|
||||
actions.
|
||||
</p>
|
||||
)}
|
||||
{gitStatusForActions &&
|
||||
@@ -1184,6 +1322,423 @@ export default function GitActionsControl({
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={isPublishDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsPublishDialogOpen(open);
|
||||
if (!open) {
|
||||
setPublishProvider("github");
|
||||
setPublishRemoteName("origin");
|
||||
setPublishRepository("");
|
||||
setPublishVisibility("private");
|
||||
setPublishProtocol("ssh");
|
||||
setHasUserEditedPublishRepository(false);
|
||||
setPublishWizardStep(0);
|
||||
setPublishAdvancedOpen(false);
|
||||
setPublishError(null);
|
||||
setPublishResult(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Publish repository</DialogTitle>
|
||||
<DialogDescription>
|
||||
Pick where to host it, then point us at a repo to push to.
|
||||
</DialogDescription>
|
||||
<div className="mt-1 grid grid-cols-3 gap-2">
|
||||
{(["Provider", "Repository", "Summary"] as const).map((label, index) => {
|
||||
const summary =
|
||||
index === 0 && publishWizardStep > 0
|
||||
? publishProviderLabel
|
||||
: index === 1 && publishWizardStep > 1 && publishResult
|
||||
? publishResult.repository.nameWithOwner
|
||||
: null;
|
||||
const isComplete = index < publishWizardStep;
|
||||
const isDoneStep = index === 2;
|
||||
// The summary step is only reachable via a successful submit;
|
||||
// disallow user-driven navigation to or from it.
|
||||
const isClickable =
|
||||
publishWizardStep !== 2 && !isDoneStep && index <= publishWizardStep;
|
||||
return (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
onClick={isClickable ? () => setPublishWizardStep(index) : undefined}
|
||||
disabled={!isClickable}
|
||||
className={cn(
|
||||
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left transition",
|
||||
index === publishWizardStep
|
||||
? "border-primary bg-primary/10 ring-1 ring-primary/25"
|
||||
: isComplete
|
||||
? "border-border bg-background"
|
||||
: "border-border bg-muted/40",
|
||||
!isClickable && "cursor-default",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
|
||||
isComplete
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: index === publishWizardStep
|
||||
? "border-primary bg-background"
|
||||
: "border-muted-foreground/35 bg-background",
|
||||
)}
|
||||
>
|
||||
{isComplete ? <CheckIcon className="size-3" /> : null}
|
||||
</span>
|
||||
<span className="text-[10px] font-medium uppercase text-muted-foreground">
|
||||
Step {index + 1}
|
||||
</span>
|
||||
<span className="truncate text-xs font-semibold text-foreground">
|
||||
{label}
|
||||
{summary ? `: ${summary}` : ""}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Step 1: Provider */}
|
||||
{publishWizardStep === 0 && (
|
||||
<DialogPanel className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<span
|
||||
id="publish-provider-cards-label"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Provider
|
||||
</span>
|
||||
<RadioGroup
|
||||
value={publishProvider}
|
||||
onValueChange={(value) => setPublishProvider(value as PublishProviderKind)}
|
||||
aria-labelledby="publish-provider-cards-label"
|
||||
className="grid grid-cols-2 gap-2.5"
|
||||
>
|
||||
{[
|
||||
{
|
||||
value: "github" as const,
|
||||
label: "GitHub",
|
||||
description: "github.com",
|
||||
Icon: GitHubIcon,
|
||||
},
|
||||
{
|
||||
value: "gitlab" as const,
|
||||
label: "GitLab",
|
||||
description: "gitlab.com",
|
||||
Icon: GitLabIcon,
|
||||
},
|
||||
].map((option) => {
|
||||
const isSelected = publishProvider === option.value;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className={cn(
|
||||
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<option.Icon className="size-5 shrink-0" aria-hidden />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{option.description}
|
||||
</span>
|
||||
</span>
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
)}
|
||||
{publishWizardStep === 1 && (
|
||||
<DialogPanel className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="publish-repository-path"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Repository
|
||||
</label>
|
||||
<div className="flex items-stretch overflow-hidden rounded-md border border-input bg-background focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-ring">
|
||||
<span className="flex shrink-0 items-center gap-1.5 border-r border-input bg-muted/50 px-2.5 font-mono text-xs text-muted-foreground">
|
||||
{publishProvider === "github" ? (
|
||||
<GitHubIcon className="size-3.5" />
|
||||
) : (
|
||||
<GitLabIcon className="size-3.5" />
|
||||
)}
|
||||
{publishHost}/
|
||||
</span>
|
||||
<input
|
||||
id="publish-repository-path"
|
||||
name="publish-repository-path"
|
||||
value={publishRepository}
|
||||
onChange={(event) => {
|
||||
setPublishRepository(event.target.value);
|
||||
setHasUserEditedPublishRepository(true);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
submitPublishRepository();
|
||||
}
|
||||
}}
|
||||
placeholder={publishPathPlaceholder}
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
className="w-full bg-transparent px-3 py-2 font-mono text-sm placeholder:text-muted-foreground/60 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<span
|
||||
id="publish-visibility-cards-label"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Visibility
|
||||
</span>
|
||||
<RadioGroup
|
||||
value={publishVisibility}
|
||||
onValueChange={(value) =>
|
||||
setPublishVisibility(value as SourceControlRepositoryVisibility)
|
||||
}
|
||||
aria-labelledby="publish-visibility-cards-label"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
className="grid grid-cols-2 gap-2.5"
|
||||
>
|
||||
{[
|
||||
{
|
||||
value: "private" as const,
|
||||
label: "Private",
|
||||
description: "Only invited people",
|
||||
Icon: LockIcon,
|
||||
},
|
||||
{
|
||||
value: "public" as const,
|
||||
label: "Public",
|
||||
description: "Anyone on the web",
|
||||
Icon: GlobeIcon,
|
||||
},
|
||||
].map((option) => {
|
||||
const isSelected = publishVisibility === option.value;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className={cn(
|
||||
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<option.Icon
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{option.description}
|
||||
</span>
|
||||
</span>
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPublishAdvancedOpen((prev) => !prev)}
|
||||
aria-expanded={publishAdvancedOpen}
|
||||
className="flex items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<ChevronDownIcon
|
||||
className={cn(
|
||||
"size-3.5 transition-transform",
|
||||
publishAdvancedOpen ? "" : "-rotate-90",
|
||||
)}
|
||||
/>
|
||||
Advanced
|
||||
</button>
|
||||
{publishAdvancedOpen && (
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||
<label className="space-y-1.5" htmlFor="publish-remote-name">
|
||||
<span className="text-xs font-medium text-foreground">Remote</span>
|
||||
<Input
|
||||
id="publish-remote-name"
|
||||
value={publishRemoteName}
|
||||
onChange={(event) => setPublishRemoteName(event.target.value)}
|
||||
placeholder="origin"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
/>
|
||||
</label>
|
||||
<div className="space-y-1.5">
|
||||
<span
|
||||
id="publish-protocol-label"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Protocol
|
||||
</span>
|
||||
<RadioGroup
|
||||
value={publishProtocol}
|
||||
onValueChange={(value) =>
|
||||
setPublishProtocol(value as SourceControlCloneProtocol)
|
||||
}
|
||||
aria-labelledby="publish-protocol-label"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
className="grid grid-cols-2 gap-2"
|
||||
>
|
||||
{(["ssh", "https"] as const).map((value) => {
|
||||
const isSelected = publishProtocol === value;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={value}
|
||||
value={value}
|
||||
className={cn(
|
||||
"rounded-md border px-3 py-1.5 text-center text-sm font-medium outline-none transition",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background ring-2 ring-primary/35 text-foreground"
|
||||
: "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{value === "ssh" ? "SSH" : "HTTPS"}
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{publishRepositoryMutation.isPending && (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground"
|
||||
>
|
||||
<Spinner className="size-3.5" aria-hidden />
|
||||
Publishing repository to {publishProviderLabel}...
|
||||
</div>
|
||||
)}
|
||||
{publishError && !publishRepositoryMutation.isPending && (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
|
||||
>
|
||||
<p className="font-medium">Publish failed</p>
|
||||
<p className="mt-0.5 text-destructive/90">{publishError}</p>
|
||||
</div>
|
||||
)}
|
||||
</DialogPanel>
|
||||
)}
|
||||
{publishWizardStep === 2 && publishResult && (
|
||||
<DialogPanel className="space-y-4">
|
||||
<div className="flex flex-col items-center gap-2 py-1 text-center">
|
||||
<span className="grid size-8 place-items-center rounded-full bg-success/15 text-success">
|
||||
<CheckIcon className="size-4" aria-hidden />
|
||||
</span>
|
||||
<h3 className="text-sm font-semibold text-foreground">
|
||||
{publishResult.status === "pushed"
|
||||
? "Repository published"
|
||||
: "Repository created"}
|
||||
</h3>
|
||||
<p className="max-w-xs text-pretty text-xs text-muted-foreground">
|
||||
{publishResult.status === "pushed"
|
||||
? `${publishResult.branch} is now live on ${publishProviderLabel}.`
|
||||
: `Remote "${publishResult.remoteName}" is set up. Make a commit and push it to share your code.`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2">
|
||||
{publishProvider === "github" ? (
|
||||
<GitHubIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<GitLabIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
|
||||
{publishResult.repository.nameWithOwner}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => {
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
void api.shell.openExternal(publishResult.repository.url);
|
||||
}}
|
||||
>
|
||||
<ExternalLinkIcon className="size-3.5" aria-hidden />
|
||||
Open on {publishProviderLabel}
|
||||
</Button>
|
||||
</DialogPanel>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{publishWizardStep === 2 ? (
|
||||
<Button size="sm" onClick={() => setIsPublishDialogOpen(false)}>
|
||||
Done
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
onClick={() => {
|
||||
if (publishWizardStep === 0) {
|
||||
setIsPublishDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
setPublishWizardStep((step) => Math.max(0, step - 1));
|
||||
}}
|
||||
>
|
||||
{publishWizardStep === 0 ? "Cancel" : "Back"}
|
||||
</Button>
|
||||
{publishWizardStep < 1 ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setPublishWizardStep((step) => Math.min(1, step + 1))}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!canSubmitPublishRepository}
|
||||
onClick={submitPublishRepository}
|
||||
>
|
||||
{publishRepositoryMutation.isPending ? (
|
||||
<>
|
||||
<Spinner className="size-3.5" aria-hidden />
|
||||
Publishing...
|
||||
</>
|
||||
) : (
|
||||
"Publish"
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={pendingDefaultBranchAction !== null}
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -15,6 +15,180 @@ export const GitHubIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const GitIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 256 256">
|
||||
<path
|
||||
d="M251.17 116.6 139.4 4.82a16.49 16.49 0 0 0-23.31 0l-23.21 23.2 29.44 29.45a19.57 19.57 0 0 1 24.8 24.96l28.37 28.38a19.61 19.61 0 1 1-11.75 11.06L137.28 95.4v69.64a19.62 19.62 0 1 1-16.13-.57V94.2a19.61 19.61 0 0 1-10.65-25.73L81.46 39.44 4.83 116.08a16.49 16.49 0 0 0 0 23.32L116.6 251.17a16.49 16.49 0 0 0 23.32 0l111.25-111.25a16.5 16.5 0 0 0 0-23.33"
|
||||
fill="#DE4C36"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const JujutsuIcon: Icon = (props) => {
|
||||
const groupId = `${useId().replaceAll(":", "")}-jj-a`;
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<g id={groupId}>
|
||||
<path
|
||||
d="M380.7 632.3s-14.3 56-50.3 55.5c-12.1-.2-29-10.9-47.1-26.8-34.2 82.7-98.5 239-108.5 268.6-8.9 26.5 13 52 38.2 56 36.4 5.7 49-18.1 49-18.1s13.6 40.7 37.6 39.7c29.9-1.2 34.6-33 34.6-33s11.4 23.8 26.8 23.2c38.4-1.4 41.7-102.9 43.8-135.6 3.8-57.5 6.3-135.4 7.8-190.1-9 6.7-16.5 10.7-21.3 9.9-16.1-2.7-10.6-49.3-10.6-49.3z"
|
||||
fill="#42acde"
|
||||
/>
|
||||
<path
|
||||
d="M403.7 75.1c-89.7-.3-201.5 32.6-200.6 99.6 1.3 87.4 52.2 62.4 41.2 111.2-4.9 21.6-59.9 49.8-65.5 153.8 2.8.7 5.3 1 7.2 1.2 14.2.7 29.9-26.3 29.9-26.3s9.5 38 35 38 50.7-26.3 50.7-26.3 15 30.3 39.6 32c20 1.6 34-8 34-8s.8 15 14.6 14c13.9-1.2 37.6-27.8 37.6-27.8 16.5 30.3 31.9 21 54.7 5.1 0 0 6.2 26.6 36.8 23.7 6-.6 12.3-1 18.5-1.5l.9-11.6c2-58.8-20.4-129.8-50.4-183-21.7-38.7-52.5-83.4-49.6-107.3 3.5-28.3 46.7-28.4 46.7-28.4l-48.5-16 24-37a279.7 279.7 0 0 0-56.8-5.4Z"
|
||||
fill="#2f9fdf"
|
||||
/>
|
||||
<path
|
||||
d="M215.9 414.6s-15.7 27-30 26.3c-1.8-.1-4.3-.5-7-1.2l-.3 3c-2.3 52 7.7 100.3 29.7 132 35.1 50.7 92.6 112.6 122 113 36.1.6 50.4-55.4 50.4-55.4s-5.5 46.6 10.6 49.3c16 2.6 62.4-46.7 87.9-79.5 15.8-20.5 52-82.3 58.2-138.3-6.2.4-12.4 1-18.5 1.5-30.6 3-36.8-23.7-36.8-23.7-22.8 16-38.2 25.2-54.7-5 0 0-23.7 26.5-37.6 27.6-13.8 1.1-14.6-13.8-14.6-13.8s-14 9.5-34 8c-24.5-1.8-39.6-32.1-39.6-32.1s-25.2 26.3-50.7 26.3c-25.5 0-35-38-35-38z"
|
||||
fill="#0e254f"
|
||||
/>
|
||||
<path
|
||||
d="M309.5 418.5a1.5 1.5 0 0 0-.7 0c-.6.2-1.1.8-1.5 1.8a34.7 34.7 0 0 0 4 16.6c5.5 10.6 12.4 22 23.3 27.6 4 2 8.5 3.5 12.5 3.3a36 36 0 0 0 12.5-2.3c4-2 7.6-3.8 10.8-6.2 6-4.4 7.6-6.5 7.6-9.8 0-3.3-2.7-3.5-7.6-.5-5 3-14.6 6.1-18.8 6.1-11.2 0-21.2-8-33.1-26.4-4.3-6.6-7.1-9.9-9-10.2zm174 5c-1.2-.2-2.4.4-3.8 1.7-2.3 2.3-2.7 4-2.6 10.7.5 9 4.8 19.2 11.8 24.6 4.4 3.3 13.2 6 20.4 5.8 6.8-1.1 18.8-6.6 15.3-10.3-2-1.6-5 .7-9.9.7-10.6 0-15.3-3.4-19.6-9-3.8-5-5.4-8.7-7.2-16.8-1.1-4.6-2.6-7.1-4.4-7.4zm-67.5 2.2a1 1 0 0 0-.4 0c-.4.1-.7.4-1.2.9-2.4 2-2.5 5.1-.2 12.6a41.4 41.4 0 0 0 25.3 22c7.6 1.7 14.5.6 20.3-2.7 3.8-2.4 5.3-5 4.4-7.3-4.8-2.9-7.7-1-13.3-1A39.5 39.5 0 0 1 424 435c-4.8-5.9-7-9.3-8-9.4zm-199 .8c-1 .3-1.4 2.7-1 7.2.3 5.3 1.3 8.2 4 12 3 4.5 11.5 11 14.7 11.7 2.5 1 6.9 2.3 10.7 2.3 3.8 0 8-.6 11.2-1.3 3.2-.7 6.8-2 10.3-4l1.3-.7c4-2.1 8-5.1 10.9-7.9l1.4-1.2c6.3-5.4 9.9-10.7 9.9-14.6 0-2.4-5.3-.5-14 5-16 9.8-31.1 13.2-40.9 9l-2.2-1.3-8.8-7.7a32.9 32.9 0 0 1-3.6-4.8c-1.4-2.2-2.5-3.4-3.3-3.7a1 1 0 0 0-.5 0z"
|
||||
fill="#71beea"
|
||||
/>
|
||||
<path
|
||||
d="M221.6 468.8c-.5 0-.8.1-1.1.4-.3.2-.5.6-.6 1.2a10 10 0 0 0 .6 5.1 55 55 0 0 0 28.3 28.9 42.4 42.4 0 0 0 16.4 2c6.1-.2 12.3-1.4 16.6-3.4a48.3 48.3 0 0 0 13.7-10.6c.9-1 1.3-2 1.3-2.3 0-.6 0-.9-.3-1-.3-.3-.7-.4-1.6-.4-1.8 0-4.9.8-9.7 2.3-6.2 1.9-12.7 3-18.5 3.1-7.8.2-10.2-.4-17-3.7-4.5-2.2-12-7.7-17.7-12.8a232 232 0 0 0-7.2-6.3 63 63 0 0 0-2.4-2 12 12 0 0 0-.7-.4h-.1zm214.8 13.6c-.2 0-.5.7-.7 1.8v4a32 32 0 0 0 2.7 9.9 38.5 38.5 0 0 0 49.1 19.3c5.2-2.3 10-6.4 13-10.5 1.4-2.1 2.5-4.3 3-6.2.5-1.9.4-3.6-.3-4.9-.4-.8-.9-1.4-1.3-1.7-.3-.3-.6-.3-1-.2-.9.2-2.3 1.4-4.3 3.8-5 6.2-12.8 9.5-22.6 9.4-6.2 0-11-1.1-16-4.4-5-3.2-10.4-8.6-18-17.3-.8-1-1.7-2-2.5-2.4l-1-.6c-.1 0-.2 0 0 0zm-33.6 4.2-.6.2-1.4.7a53.5 53.5 0 0 0-4 2.5c-8 5.5-15.6 8.3-23.9 8.4-8.3 0-17.2-2.7-28-8.2a42 42 0 0 0-7.3-3c-2-.5-3.1-.5-3.6-.2-.2.1-.3.3-.4.6 0 .3 0 .8.2 1.5.4 1.3 1.4 3.1 3.1 5.5 4 5.4 10.5 10.1 19.7 14 9.3 3.9 23.8 3.5 32.4-1a42 42 0 0 0 9.1-6.5c2.6-2.6 4.5-6.5 5.3-9.6.5-1.5.6-3 .4-3.8 0-.4-.2-.7-.4-.9-.1-.2-.3-.2-.6-.2zm-132.5 30.8c-.3 0-.4 0-.5.2l-.1.5c0 .5.4 1.7 1.2 3.1a87.3 87.3 0 0 0 13.5 16.2c17 15.6 34.6 20.7 49 14.4a33.3 33.3 0 0 0 19-23c.4-2 .1-3.1-.2-3.5-.2-.2-.5-.3-1-.3l-1.7.5a24 24 0 0 0-5.7 4.6c-7.7 8-14.6 12-23 11.4-8.3-.4-18-5.2-31.7-14.3-5.2-3.4-9.4-6-12.5-7.6a15.5 15.5 0 0 0-6.3-2.2zm109.4 0c-.2 0-.3 0-.5.2-.1 0-.3.3-.4.7a9 9 0 0 0 0 3.3c.4 2.9 1.6 6.7 3.5 10.3 11 20.5 29.4 30.5 46.8 25.7a37.3 37.3 0 0 0 15.6-10c4.4-4.6 7.4-9.9 7.4-13.8 0-1.3-.1-2.3-.4-2.7 0-.3-.2-.4-.3-.4h-.5c-.6 0-1.5.4-2.7 1.2a57 57 0 0 0-4.7 3.7c-9 7.7-16.9 11.2-25.1 10-8.2-1.3-16.7-7.1-27-17.7a159.8 159.8 0 0 0-10.6-9.8 9.8 9.8 0 0 0-.9-.6l-.2-.1zm-140.2 43.5c-1 0-1.6.2-1.8.5-.2.4-.3 1 0 2.1.8 2.2 3.1 5.6 7.1 9.6a78.2 78.2 0 0 0 27.4 17.9c9.7 3.8 16.7 4.1 23.4 1.1 5.5-2.5 8.4-6.1 8.4-10.4a4 4 0 0 0-.4-2c-.3-.4-.6-.6-1-.7-.9-.1-2.5.4-4.6 1.8-2.7 2-6.4 2.3-11.3 1.2-5-1.2-11.3-3.8-19.5-8-8-4-17.5-9-21.3-11-2.9-1.4-5-2-6.4-2.1zm160.1 2.8c-.6-.1-1.7.2-3.1 1-1.4 1-3.2 2.3-5.2 4.1a58 58 0 0 1-12.7 8.7c-5.9 2.7-8.6 3.2-18.3 3.2-12.6 0-17.2-1.6-29.9-11.2a21 21 0 0 0-6.4-3.8c-.5 0-.5 0-.7.2-.2.3-.3 1-.3 2 0 2.2 1.5 5.7 3.8 9.2 2.4 3.4 5.7 7 9.2 9.5 8.1 6 14.3 7.8 26.2 7.4a34 34 0 0 0 18.3-4.1 51 51 0 0 0 13.1-9.8c3.8-3.8 6.5-8 7-10.7.4-2 .4-3.5.2-4.5a2 2 0 0 0-.5-1 1 1 0 0 0-.7-.2zm-2 21.4c-.5 0-.6 0-.8.4-.2.4-.3 1.2-.3 2.4 0 3.2 1.7 7.3 4.4 11 2.7 4 6.3 7.4 10 9.5a35 35 0 0 0 21.3 4.8c11-.9 17.8-3.4 23.8-12.6 1.5-2.5 2-4.8 1.4-6.7-.2-.7-.4-1.1-.8-1.4-.3-.2-.6-.3-1.2-.3-1 0-2.6.7-4.7 2.1-6 4.3-12 6.1-19.9 6.2-8.8 0-16.3-3-26.2-11-3.6-2.8-6-4.3-7-4.4zM290 605.5c-.6.3-.9.5-1 1a9 9 0 0 0 .1 3.3c1.8 11 13 25 24.4 30.2 8.5 4 20 4 28.5 0 7.7-3.5 16-11.1 19-17.3a25 25 0 0 0 2.2-6.3c.1-.7.1-1.3 0-1.6 0-.4-.2-.6-.4-.7-.3-.2-1.3-.2-2.8.5-1.6.7-3.6 2-6 4-10 8.2-18.6 12.1-27 11.4-8.6-.7-16.9-6-26.4-15.9a82.6 82.6 0 0 0-7.6-7.1 10 10 0 0 0-2-1.4c-.5-.2-.8-.2-1-.1z"
|
||||
fill="#309fdf"
|
||||
/>
|
||||
<path
|
||||
d="M290 125.7a61.4 61.4 0 0 0-19 2.3c-19.9 5.7-33.5 15.8-36.5 52.2-3 36.6-18 45.5-20.3 46.7 14.7 26.7 38 24.5 30.1 59-2.4 11-17.6 23.5-32.8 46.5 34-27 56.4-48 99.6-100.5 0 0 39-47.6 25.1-77a52 52 0 0 0-46.1-29.2z"
|
||||
fill="#e9f2f1"
|
||||
/>
|
||||
<path
|
||||
d="M288.5 120.8c-8.1 0-16.7 1.4-25.6 5.3-22.5 9.9-25 20.3-29.1 37a96.8 96.8 0 0 0-1.4 24.6 178 178 0 0 0-16.5-31.6s-19 19.8-36.5 18.6c-22.9-1.7-34 2-44.8 9.8-25.4 18.5-21.2 43.8-21.2 43.8s17.6-1.8 40.5 1c20.3 2.7 37.4 4.3 61.3 2.6 8.5-.6 15.8-10 19.3-19 4.5-4 2.9-22 4.8-24.5 3-3.4 8-4.7 10.6-5.2 3.7-.7 4.3 1.5 4.7 2.8a31 31 0 0 0 60.5-3.2c1-4.4 9-5 15.9-4.5 7 0 .9 15.9-1.7 22.3-5.4 13.2-24.9 39-24.9 39l124.3-85s-45.8 22-61.5 20c-19.7-2.3-25.7-34.8-43.2-44-9.9-5.1-22-9.6-35.5-9.8zm1.4 9.4a48.2 48.2 0 0 1 40.6 23.5c3.7 7.1 6.2 17-.3 20.2-7.6 3.7-14.7.7-15.5-2.8a31 31 0 0 0-30.2-24.1 30 30 0 0 0-30.8 27.4c-.4 5.2-9.1 7.7-12.7 3.7-2.7-3 1.7-16.8 3.7-22 6.2-16.2 27.8-25.7 45.2-26zm5.6 27.8a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11zm-22 29a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11zm40 523.4c-2.6-1.8-15.1 23.5-20 59-6.8 49-8.3 63.2-14.2 96-6 32.7-12.6 66.3-13.4 73.7-.6 4.8-1.7 19-.6 20.1 3.2 3.3 14.7-31.7 16.8-42 2-10.3 7.7-40.7 14.2-86.9 6.4-46.1 8.5-69.6 13.1-91.5 4.7-22 6.7-26.6 4.2-28.4zm66.3-27c-4.1-1.3-10.5 24.6-13.1 37.8-5.6 28.6-6.2 64-8.4 87a1099 1099 0 0 1-12 87.4c-2.7 15-8 29.4-9.8 44.6-1 9-5.2 26-.2 27.3 5.2 1.5 15.4-36.5 20-55.7 8.1-32.9 10.7-65.6 14.2-99.3 3.3-30.7 4.6-62.8 6.5-93.6.7-18.5 5.1-34.5 2.8-35.6z"
|
||||
fill="#0e254f"
|
||||
/>
|
||||
</g>
|
||||
</defs>
|
||||
<rect width="1024" height="1024" rx="270" fill="#a7bcd9" />
|
||||
<use href={`#${groupId}`} transform="matrix(-1 0 0 1 1024 0)" />
|
||||
<use href={`#${groupId}`} />
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const GitLabIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 32 32" fill="none">
|
||||
<path
|
||||
d="m31.46 12.78-.04-.12-4.35-11.35A1.14 1.14 0 0 0 25.94.6c-.24 0-.47.1-.66.24-.19.15-.33.36-.39.6l-2.94 9h-11.9l-2.94-9A1.14 1.14 0 0 0 6.07.58a1.15 1.15 0 0 0-1.14.72L.58 12.68l-.05.11a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48 6.67-5h.02a8.09 8.09 0 0 0 2.7-9.36Z"
|
||||
fill="#E24329"
|
||||
/>
|
||||
<path
|
||||
d="m31.46 12.78-.04-.12a14.75 14.75 0 0 0-5.86 2.64l-9.55 7.24 6.09 4.6 6.67-5h.02a8.09 8.09 0 0 0 2.67-9.36Z"
|
||||
fill="#FC6D26"
|
||||
/>
|
||||
<path
|
||||
d="m9.9 27.14 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48-6.1-4.6-6.07 4.6Z"
|
||||
fill="#FCA326"
|
||||
/>
|
||||
<path
|
||||
d="M6.44 15.3a14.71 14.71 0 0 0-5.86-2.63l-.05.12a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 6.1-4.6-9.56-7.24Z"
|
||||
fill="#FC6D26"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const AzureDevOpsIcon: Icon = (props) => {
|
||||
const id = useId().replaceAll(":", "");
|
||||
const gradientA = `${id}-azure-a`;
|
||||
const gradientB = `${id}-azure-b`;
|
||||
const gradientC = `${id}-azure-c`;
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 96 96">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientA}
|
||||
x1="-1032.17"
|
||||
x2="-1059.21"
|
||||
y1="145.31"
|
||||
y2="65.43"
|
||||
gradientTransform="matrix(1 0 0 -1 1075 158)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0" stopColor="#114a8b" />
|
||||
<stop offset="1" stopColor="#0669bc" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientB}
|
||||
x1="-1023.73"
|
||||
x2="-1029.98"
|
||||
y1="108.08"
|
||||
y2="105.97"
|
||||
gradientTransform="matrix(1 0 0 -1 1075 158)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0" stopOpacity=".3" />
|
||||
<stop offset=".07" stopOpacity=".2" />
|
||||
<stop offset=".32" stopOpacity=".1" />
|
||||
<stop offset=".62" stopOpacity=".05" />
|
||||
<stop offset="1" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientC}
|
||||
x1="-1027.16"
|
||||
x2="-997.48"
|
||||
y1="147.64"
|
||||
y2="68.56"
|
||||
gradientTransform="matrix(1 0 0 -1 1075 158)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0" stopColor="#3ccbf4" />
|
||||
<stop offset="1" stopColor="#2892df" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${gradientA})`}
|
||||
d="M33.34 6.54h26.04l-27.03 80.1a4.15 4.15 0 0 1-3.94 2.81H8.15a4.14 4.14 0 0 1-3.93-5.47L29.4 9.38a4.15 4.15 0 0 1 3.94-2.83z"
|
||||
/>
|
||||
<path
|
||||
fill="#0078d4"
|
||||
d="M71.17 60.26H29.88a1.91 1.91 0 0 0-1.3 3.31l26.53 24.76a4.17 4.17 0 0 0 2.85 1.13h23.38z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientB})`}
|
||||
d="M33.34 6.54a4.12 4.12 0 0 0-3.95 2.88L4.25 83.92a4.14 4.14 0 0 0 3.91 5.54h20.79a4.44 4.44 0 0 0 3.4-2.9l5.02-14.78 17.91 16.7a4.24 4.24 0 0 0 2.67.97h23.29L71.02 60.26H41.24L59.47 6.55z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientC})`}
|
||||
d="M66.6 9.36a4.14 4.14 0 0 0-3.93-2.82H33.65a4.15 4.15 0 0 1 3.93 2.82l25.18 74.62a4.15 4.15 0 0 1-3.93 5.48h29.02a4.15 4.15 0 0 0 3.93-5.48z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const BitbucketIcon: Icon = (props) => {
|
||||
const id = useId().replaceAll(":", "");
|
||||
const gradientId = `${id}-bitbucket-a`;
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="8.4 14.39 2481.29 2231.21">
|
||||
<path fill="none" d="M989.97,1493.09h518.05l125.04-730.04H852.22L989.97,1493.09z" />
|
||||
<path
|
||||
fill="#2684FF"
|
||||
d="M88.92,14.4C45.02,13.83,8.97,48.96,8.41,92.86c-0.06,4.61,0.28,9.22,1.02,13.77l337.48,2048.72 c8.68,51.75,53.26,89.8,105.74,90.24h1619.03c39.38,0.5,73.19-27.9,79.49-66.78l337.49-2071.78c7.03-43.34-22.41-84.17-65.75-91.2 c-4.55-0.74-9.15-1.08-13.76-1.02L88.92,14.4z M1509.99,1495.09H993.24l-139.92-731h781.89L1509.99,1495.09z"
|
||||
/>
|
||||
<linearGradient
|
||||
id={gradientId}
|
||||
gradientUnits="userSpaceOnUse"
|
||||
x1="945.1094"
|
||||
y1="1524.8389"
|
||||
x2="944.4923"
|
||||
y2="1524.1893"
|
||||
gradientTransform="matrix(1996.6343 0 0 -1480.3047 -1884485.625 2258195)"
|
||||
>
|
||||
<stop offset="0.18" stopColor="#0052CC" />
|
||||
<stop offset="1" stopColor="#2684FF" />
|
||||
</linearGradient>
|
||||
<path
|
||||
fill={`url(#${gradientId})`}
|
||||
d="M2379.27,763.06h-745.5l-125.12,730.42H992.31l-609.67,723.67c19.32,16.71,43.96,26,69.5,26.21h1618.13 c39.35,0.51,73.14-27.88,79.44-66.72L2379.27,763.06z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const CursorIcon: Icon = ({ className, ...props }) => (
|
||||
<svg
|
||||
{...props}
|
||||
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
gitPreparePullRequestThreadMutationOptions,
|
||||
gitResolvePullRequestQueryOptions,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { useGitStatus } from "~/lib/gitStatusState";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { parsePullRequestReference } from "~/pullRequestReference";
|
||||
import { getSourceControlPresentation } from "~/sourceControlPresentation";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -51,6 +53,13 @@ export function PullRequestThreadDialog({
|
||||
{ wait: 450 },
|
||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||
);
|
||||
const { data: gitStatus = null } = useGitStatus({ environmentId, cwd });
|
||||
const sourceControlPresentation = useMemo(
|
||||
() => getSourceControlPresentation(gitStatus?.sourceControlProvider),
|
||||
[gitStatus?.sourceControlProvider],
|
||||
);
|
||||
const terminology = sourceControlPresentation.terminology;
|
||||
const SourceControlIcon = sourceControlPresentation.Icon;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -161,20 +170,20 @@ export function PullRequestThreadDialog({
|
||||
const validationMessage = !referenceDirty
|
||||
? null
|
||||
: reference.trim().length === 0
|
||||
? "Paste a GitHub pull request URL, `gh pr checkout 123`, or enter 123 / #123."
|
||||
? `Paste a ${terminology.singular} URL, checkout command, or enter 123 / #123.`
|
||||
: parsedReference === null
|
||||
? "Use a GitHub pull request URL, `gh pr checkout 123`, 123, or #123."
|
||||
? `Use a ${terminology.singular} URL, checkout command, 123, or #123.`
|
||||
: null;
|
||||
const errorMessage =
|
||||
validationMessage ??
|
||||
(resolvedPullRequest === null && resolvePullRequestQuery.isError
|
||||
? resolvePullRequestQuery.error instanceof Error
|
||||
? resolvePullRequestQuery.error.message
|
||||
: "Failed to resolve pull request."
|
||||
: `Failed to resolve ${terminology.singular}.`
|
||||
: preparePullRequestThreadMutation.error instanceof Error
|
||||
? preparePullRequestThreadMutation.error.message
|
||||
: preparePullRequestThreadMutation.error
|
||||
? "Failed to prepare pull request thread."
|
||||
? `Failed to prepare ${terminology.singular} thread.`
|
||||
: null);
|
||||
|
||||
return (
|
||||
@@ -188,18 +197,23 @@ export function PullRequestThreadDialog({
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Checkout Pull Request</DialogTitle>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<SourceControlIcon className="size-4" />
|
||||
Checkout {terminology.singular}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Resolve a GitHub pull request, then create the draft thread in the main repo or in a
|
||||
dedicated worktree.
|
||||
Resolve a {sourceControlPresentation.providerName} {terminology.singular}, then create
|
||||
the draft thread in the main repo or in a dedicated worktree.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4">
|
||||
<label className="grid gap-1.5">
|
||||
<span className="text-xs font-medium text-foreground">Pull request</span>
|
||||
<span className="text-xs font-medium text-foreground capitalize">
|
||||
{terminology.singular}
|
||||
</span>
|
||||
<Input
|
||||
ref={referenceInputRef}
|
||||
placeholder="https://github.com/owner/repo/pull/42, gh pr checkout 42, or #42"
|
||||
placeholder={`${terminology.shortLabel} URL, checkout command, or #42`}
|
||||
value={reference}
|
||||
onChange={(event) => {
|
||||
setReferenceDirty(true);
|
||||
@@ -237,7 +251,7 @@ export function PullRequestThreadDialog({
|
||||
{isResolving ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground text-xs">
|
||||
<Spinner className="size-3.5" />
|
||||
Resolving pull request...
|
||||
Resolving {terminology.singular}...
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ArrowUpDownIcon,
|
||||
ChevronRightIcon,
|
||||
CloudIcon,
|
||||
GitPullRequestIcon,
|
||||
FolderPlusIcon,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
@@ -12,6 +11,7 @@ import {
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
ChangeRequestStatusIcon,
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
terminalStatusFromRunningIds,
|
||||
@@ -367,7 +367,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
},
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
|
||||
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
|
||||
const threadMetaClassName = isConfirmingArchive
|
||||
@@ -558,7 +558,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
|
||||
onClick={handlePrClick}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
<ChangeRequestStatusIcon className="size-3" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
@@ -1002,7 +1002,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
title: "Unable to open pull request link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -11,12 +11,13 @@ import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { type AppState, selectProjectByRef, useStore } from "../store";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
|
||||
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
|
||||
import type { SidebarThreadSummary } from "../types";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
export interface PrStatusIndicator {
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
label: string;
|
||||
colorClass: string;
|
||||
tooltip: string;
|
||||
url: string;
|
||||
@@ -30,36 +31,44 @@ export interface TerminalStatusIndicator {
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
): PrStatusIndicator | null {
|
||||
if (!pr) return null;
|
||||
const presentation = resolveChangeRequestPresentation(provider);
|
||||
|
||||
if (pr.state === "open") {
|
||||
return {
|
||||
label: "PR open",
|
||||
label: `${presentation.shortName} open`,
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
tooltip: `#${pr.number} PR open: ${pr.title}`,
|
||||
tooltip: `#${pr.number} ${presentation.shortName} open: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: "PR closed",
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip: `#${pr.number} PR closed: ${pr.title}`,
|
||||
tooltip: `#${pr.number} ${presentation.shortName} closed: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (pr.state === "merged") {
|
||||
return {
|
||||
label: "PR merged",
|
||||
label: `${presentation.shortName} merged`,
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
tooltip: `#${pr.number} PR merged: ${pr.title}`,
|
||||
tooltip: `#${pr.number} ${presentation.shortName} merged: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ChangeRequestStatusIcon({ className }: { className?: string }) {
|
||||
return <GitPullRequestIcon className={className} />;
|
||||
}
|
||||
|
||||
export function resolveThreadPr(
|
||||
threadBranch: string | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
@@ -124,7 +133,7 @@ export function ThreadStatusLabel({
|
||||
|
||||
/**
|
||||
* Non-interactive leading status icons for a thread row in compact contexts
|
||||
* like the command palette. Shows the PR state icon (if present) and the
|
||||
* like the command palette. Shows the change request state icon (if present) and the
|
||||
* thread status dot, matching the sidebar's leading indicators.
|
||||
*/
|
||||
export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
|
||||
@@ -146,7 +155,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
cwd: thread.branch != null ? gitCwd : null,
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
@@ -170,7 +179,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
/>
|
||||
}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
<ChangeRequestStatusIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
@@ -17,8 +17,6 @@ import { Toggle } from "../ui/toggle";
|
||||
import { SidebarTrigger } from "../ui/sidebar";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { usePrimaryEnvironmentId } from "../../environments/primary";
|
||||
import { resolveVcsTerms } from "../../vcsPresentation";
|
||||
import type { VcsDriverKind } from "@t3tools/contracts";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
@@ -26,8 +24,7 @@ interface ChatHeaderProps {
|
||||
draftId?: DraftId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
isVcsRepo: boolean;
|
||||
vcsKind: VcsDriverKind | null;
|
||||
isGitRepo: boolean;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ProjectScript[] | undefined;
|
||||
preferredScriptId: string | null;
|
||||
@@ -53,8 +50,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
draftId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
isVcsRepo,
|
||||
vcsKind,
|
||||
isGitRepo,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
@@ -76,7 +72,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const isRemoteEnvironment =
|
||||
primaryEnvironmentId !== null && activeThreadEnvironmentId !== primaryEnvironmentId;
|
||||
const vcsTerms = resolveVcsTerms(vcsKind);
|
||||
|
||||
return (
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
|
||||
@@ -93,9 +88,9 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
<span className="min-w-0 truncate">{activeProjectName}</span>
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isVcsRepo && (
|
||||
{activeProjectName && !isGitRepo && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
|
||||
No repository
|
||||
No Git
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
@@ -159,15 +154,15 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
aria-label="Toggle diff panel"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!isVcsRepo && !diffOpen}
|
||||
disabled={!isGitRepo && !diffOpen}
|
||||
>
|
||||
<DiffIcon className="size-3" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{!isVcsRepo && !diffOpen
|
||||
? `Diff panel is unavailable because this project is not a supported ${vcsTerms.repositoryNoun}.`
|
||||
{!isGitRepo && !diffOpen
|
||||
? "Diff panel is unavailable because this project is not a git repository."
|
||||
: diffToggleShortcutLabel
|
||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
||||
: "Toggle diff panel"}
|
||||
|
||||
@@ -386,6 +386,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap
|
||||
? ["Diff line wrapping"]
|
||||
: []),
|
||||
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
|
||||
? ["Diff whitespace changes"]
|
||||
: []),
|
||||
...(settings.autoOpenPlanSidebar !== DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar
|
||||
? ["Auto-open task panel"]
|
||||
: []),
|
||||
@@ -415,6 +418,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.confirmThreadDelete,
|
||||
settings.addProjectBaseDirectory,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.diffWordWrap,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.timestampFormat,
|
||||
@@ -889,6 +893,32 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Hide whitespace changes"
|
||||
description="Set whether the diff panel ignores whitespace-only edits by default."
|
||||
resetAction={
|
||||
settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace ? (
|
||||
<SettingResetButton
|
||||
label="diff whitespace changes"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.diffIgnoreWhitespace}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({ diffIgnoreWhitespace: Boolean(checked) })
|
||||
}
|
||||
aria-label="Hide whitespace changes by default"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Assistant output"
|
||||
description="Show token-by-token output while a response is in progress."
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { Option } from "effect";
|
||||
import { type ReactNode, useId } from "react";
|
||||
import { type ReactNode } from "react";
|
||||
import type {
|
||||
SourceControlProviderKind,
|
||||
SourceControlDiscoveryResult,
|
||||
SourceControlProviderAuth,
|
||||
SourceControlProviderDiscoveryItem,
|
||||
VcsDriverKind,
|
||||
VcsDiscoveryItem,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -27,7 +28,15 @@ import {
|
||||
import { Skeleton } from "../ui/skeleton";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { GitHubIcon, type Icon } from "../Icons";
|
||||
import {
|
||||
AzureDevOpsIcon,
|
||||
BitbucketIcon,
|
||||
GitHubIcon,
|
||||
GitIcon,
|
||||
GitLabIcon,
|
||||
JujutsuIcon,
|
||||
type Icon,
|
||||
} from "../Icons";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
|
||||
@@ -36,127 +45,6 @@ const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
|
||||
sourceControlProviders: [],
|
||||
};
|
||||
|
||||
const GitLabIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 32 32" fill="none">
|
||||
<path
|
||||
d="m31.46 12.78-.04-.12-4.35-11.35A1.14 1.14 0 0 0 25.94.6c-.24 0-.47.1-.66.24-.19.15-.33.36-.39.6l-2.94 9h-11.9l-2.94-9A1.14 1.14 0 0 0 6.07.58a1.15 1.15 0 0 0-1.14.72L.58 12.68l-.05.11a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48 6.67-5h.02a8.09 8.09 0 0 0 2.7-9.36Z"
|
||||
fill="#E24329"
|
||||
/>
|
||||
<path
|
||||
d="m31.46 12.78-.04-.12a14.75 14.75 0 0 0-5.86 2.64l-9.55 7.24 6.09 4.6 6.67-5h.02a8.09 8.09 0 0 0 2.67-9.36Z"
|
||||
fill="#FC6D26"
|
||||
/>
|
||||
<path
|
||||
d="m9.9 27.14 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48-6.1-4.6-6.07 4.6Z"
|
||||
fill="#FCA326"
|
||||
/>
|
||||
<path
|
||||
d="M6.44 15.3a14.71 14.71 0 0 0-5.86-2.63l-.05.12a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 6.1-4.6-9.56-7.24Z"
|
||||
fill="#FC6D26"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const AzureDevOpsIcon: Icon = (props) => {
|
||||
const id = useId().replaceAll(":", "");
|
||||
const gradientA = `${id}-azure-a`;
|
||||
const gradientB = `${id}-azure-b`;
|
||||
const gradientC = `${id}-azure-c`;
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 96 96">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientA}
|
||||
x1="-1032.17"
|
||||
x2="-1059.21"
|
||||
y1="145.31"
|
||||
y2="65.43"
|
||||
gradientTransform="matrix(1 0 0 -1 1075 158)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0" stopColor="#114a8b" />
|
||||
<stop offset="1" stopColor="#0669bc" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientB}
|
||||
x1="-1023.73"
|
||||
x2="-1029.98"
|
||||
y1="108.08"
|
||||
y2="105.97"
|
||||
gradientTransform="matrix(1 0 0 -1 1075 158)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0" stopOpacity=".3" />
|
||||
<stop offset=".07" stopOpacity=".2" />
|
||||
<stop offset=".32" stopOpacity=".1" />
|
||||
<stop offset=".62" stopOpacity=".05" />
|
||||
<stop offset="1" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientC}
|
||||
x1="-1027.16"
|
||||
x2="-997.48"
|
||||
y1="147.64"
|
||||
y2="68.56"
|
||||
gradientTransform="matrix(1 0 0 -1 1075 158)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0" stopColor="#3ccbf4" />
|
||||
<stop offset="1" stopColor="#2892df" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${gradientA})`}
|
||||
d="M33.34 6.54h26.04l-27.03 80.1a4.15 4.15 0 0 1-3.94 2.81H8.15a4.14 4.14 0 0 1-3.93-5.47L29.4 9.38a4.15 4.15 0 0 1 3.94-2.83z"
|
||||
/>
|
||||
<path
|
||||
fill="#0078d4"
|
||||
d="M71.17 60.26H29.88a1.91 1.91 0 0 0-1.3 3.31l26.53 24.76a4.17 4.17 0 0 0 2.85 1.13h23.38z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientB})`}
|
||||
d="M33.34 6.54a4.12 4.12 0 0 0-3.95 2.88L4.25 83.92a4.14 4.14 0 0 0 3.91 5.54h20.79a4.44 4.44 0 0 0 3.4-2.9l5.02-14.78 17.91 16.7a4.24 4.24 0 0 0 2.67.97h23.29L71.02 60.26H41.24L59.47 6.55z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientC})`}
|
||||
d="M66.6 9.36a4.14 4.14 0 0 0-3.93-2.82H33.65a4.15 4.15 0 0 1 3.93 2.82l25.18 74.62a4.15 4.15 0 0 1-3.93 5.48h29.02a4.15 4.15 0 0 0 3.93-5.48z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
const BitbucketIcon: Icon = (props) => {
|
||||
const id = useId().replaceAll(":", "");
|
||||
const gradientId = `${id}-bitbucket-a`;
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="8.4 14.39 2481.29 2231.21">
|
||||
<path fill="none" d="M989.97,1493.09h518.05l125.04-730.04H852.22L989.97,1493.09z" />
|
||||
<path
|
||||
fill="#2684FF"
|
||||
d="M88.92,14.4C45.02,13.83,8.97,48.96,8.41,92.86c-0.06,4.61,0.28,9.22,1.02,13.77l337.48,2048.72 c8.68,51.75,53.26,89.8,105.74,90.24h1619.03c39.38,0.5,73.19-27.9,79.49-66.78l337.49-2071.78c7.03-43.34-22.41-84.17-65.75-91.2 c-4.55-0.74-9.15-1.08-13.76-1.02L88.92,14.4z M1509.99,1495.09H993.24l-139.92-731h781.89L1509.99,1495.09z"
|
||||
/>
|
||||
<linearGradient
|
||||
id={gradientId}
|
||||
gradientUnits="userSpaceOnUse"
|
||||
x1="945.1094"
|
||||
y1="1524.8389"
|
||||
x2="944.4923"
|
||||
y2="1524.1893"
|
||||
gradientTransform="matrix(1996.6343 0 0 -1480.3047 -1884485.625 2258195)"
|
||||
>
|
||||
<stop offset="0.18" stopColor="#0052CC" />
|
||||
<stop offset="1" stopColor="#2684FF" />
|
||||
</linearGradient>
|
||||
<path
|
||||
fill={`url(#${gradientId})`}
|
||||
d="M2379.27,763.06h-745.5l-125.12,730.42H992.31l-609.67,723.67c19.32,16.71,43.96,26,69.5,26.21h1618.13 c39.35,0.51,73.14-27.88,79.44-66.72L2379.27,763.06z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {
|
||||
github: GitHubIcon,
|
||||
gitlab: GitLabIcon,
|
||||
@@ -164,6 +52,13 @@ const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, I
|
||||
bitbucket: BitbucketIcon,
|
||||
};
|
||||
|
||||
const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
|
||||
git: GitIcon,
|
||||
jj: JujutsuIcon,
|
||||
};
|
||||
|
||||
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
|
||||
|
||||
function optionLabel(value: Option.Option<string>): string | null {
|
||||
return Option.getOrNull(value);
|
||||
}
|
||||
@@ -211,7 +106,9 @@ function SourceControlItemMark({
|
||||
readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
|
||||
}) {
|
||||
const dotClassName = itemStatusDot(item);
|
||||
const Icon = isProviderDiscoveryItem(item) ? SOURCE_CONTROL_PROVIDER_ICONS[item.kind] : null;
|
||||
const Icon = isProviderDiscoveryItem(item)
|
||||
? SOURCE_CONTROL_PROVIDER_ICONS[item.kind]
|
||||
: VCS_ICONS[item.kind];
|
||||
|
||||
if (!Icon) {
|
||||
return <span className={cn("size-2 shrink-0 rounded-full", dotClassName)} aria-hidden />;
|
||||
@@ -262,6 +159,11 @@ function itemSummary({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (!item.executable) {
|
||||
return <span>{item.installHint}</span>;
|
||||
}
|
||||
|
||||
if (auth.status === "unauthenticated") {
|
||||
return <span>Sign in with the {item.executable} CLI to enable pull request actions.</span>;
|
||||
}
|
||||
@@ -337,12 +239,18 @@ function SourceControlSectionSkeleton({
|
||||
}) {
|
||||
return (
|
||||
<SettingsSection title={title} headerAction={headerAction}>
|
||||
{Array.from({ length: 2 }, (_, index) => (
|
||||
<div key={index} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
|
||||
{SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
|
||||
<div key={row} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="size-2 rounded-full" />
|
||||
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
|
||||
<Skeleton className="size-4.5 rounded-md" />
|
||||
<Skeleton
|
||||
className="pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background"
|
||||
aria-hidden
|
||||
/>
|
||||
</span>
|
||||
<Skeleton className="h-4 w-28 rounded-full" />
|
||||
<Skeleton className="h-5 w-14 rounded-full" />
|
||||
</div>
|
||||
|
||||
@@ -23,6 +23,11 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
|
||||
filesystem: {
|
||||
browse: rpcClient.filesystem.browse,
|
||||
},
|
||||
sourceControl: {
|
||||
lookupRepository: rpcClient.sourceControl.lookupRepository,
|
||||
cloneRepository: rpcClient.sourceControl.cloneRepository,
|
||||
publishRepository: rpcClient.sourceControl.publishRepository,
|
||||
},
|
||||
vcs: {
|
||||
pull: rpcClient.vcs.pull,
|
||||
refreshStatus: rpcClient.vcs.refreshStatus,
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
type EnvironmentId,
|
||||
type GitActionProgressEvent,
|
||||
type GitStackedAction,
|
||||
type SourceControlPublishRepositoryInput,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -36,6 +37,8 @@ export const gitMutationKeys = {
|
||||
["git", "mutation", "pull", environmentId ?? null, cwd] as const,
|
||||
preparePullRequestThread: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "prepare-pull-request-thread", environmentId ?? null, cwd] as const,
|
||||
publishRepository: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "publish-repository", environmentId ?? null, cwd] as const,
|
||||
};
|
||||
|
||||
export function invalidateGitQueries(
|
||||
@@ -228,6 +231,26 @@ export function gitPullMutationOptions(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export function sourceControlPublishRepositoryMutationOptions(input: {
|
||||
environmentId: EnvironmentId | null;
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.publishRepository(input.environmentId, input.cwd),
|
||||
mutationFn: async (args: Omit<SourceControlPublishRepositoryInput, "cwd">) => {
|
||||
if (!input.cwd || !input.environmentId) {
|
||||
throw new Error("Repository publishing is unavailable.");
|
||||
}
|
||||
const api = ensureEnvironmentApi(input.environmentId);
|
||||
return api.sourceControl.publishRepository({ cwd: input.cwd, ...args });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use a VCS-named mutation helper once the UI naming migration lands.
|
||||
*/
|
||||
|
||||
@@ -40,7 +40,6 @@ const TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/repo" } as const;
|
||||
const FRESH_TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/fresh" } as const;
|
||||
|
||||
const BASE_STATUS: VcsStatusResult = {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
|
||||
@@ -30,6 +30,7 @@ describe("providerQueryKeys.checkpointDiff", () => {
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: false,
|
||||
} as const;
|
||||
|
||||
expect(
|
||||
@@ -44,10 +45,32 @@ describe("providerQueryKeys.checkpointDiff", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("includes ignoreWhitespace so normal and whitespace-hidden diffs do not collide", () => {
|
||||
const baseInput = {
|
||||
environmentId,
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
cacheScope: "turn:abc",
|
||||
} as const;
|
||||
|
||||
expect(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
ignoreWhitespace: false,
|
||||
}),
|
||||
).not.toEqual(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
ignoreWhitespace: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkpointDiffQueryOptions", () => {
|
||||
it("forwards checkpoint range to the provider API", async () => {
|
||||
it("forwards checkpoint range to the provider API by default", async () => {
|
||||
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
mockNativeApi({ getTurnDiff, getFullThreadDiff });
|
||||
@@ -57,6 +80,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
|
||||
@@ -67,6 +91,33 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
expect(getFullThreadDiff).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards whitespace-hidden checkpoint range to the provider API", async () => {
|
||||
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
mockNativeApi({ getTurnDiff, getFullThreadDiff });
|
||||
|
||||
const options = checkpointDiffQueryOptions({
|
||||
environmentId,
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
await queryClient.fetchQuery(options);
|
||||
|
||||
expect(getTurnDiff).toHaveBeenCalledWith({
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
expect(getFullThreadDiff).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -81,6 +132,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
cacheScope: "thread:all",
|
||||
});
|
||||
|
||||
@@ -90,6 +142,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
expect(getFullThreadDiff).toHaveBeenCalledWith({
|
||||
threadId,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
expect(getTurnDiff).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -104,6 +157,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 4,
|
||||
toTurnCount: 3,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:invalid",
|
||||
});
|
||||
|
||||
@@ -122,6 +176,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retry = options.retry;
|
||||
@@ -147,6 +202,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retryDelay = options.retryDelay;
|
||||
|
||||
@@ -13,6 +13,7 @@ interface CheckpointDiffQueryInput {
|
||||
threadId: ThreadId | null;
|
||||
fromTurnCount: number | null;
|
||||
toTurnCount: number | null;
|
||||
ignoreWhitespace: boolean;
|
||||
cacheScope?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
@@ -27,6 +28,7 @@ export const providerQueryKeys = {
|
||||
input.threadId,
|
||||
input.fromTurnCount,
|
||||
input.toTurnCount,
|
||||
input.ignoreWhitespace,
|
||||
input.cacheScope ?? null,
|
||||
] as const,
|
||||
};
|
||||
@@ -36,6 +38,7 @@ function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
|
||||
return Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput)({
|
||||
threadId: input.threadId,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace,
|
||||
}).pipe(Option.map((fields) => ({ kind: "fullThreadDiff" as const, input: fields })));
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace,
|
||||
}).pipe(Option.map((fields) => ({ kind: "turnDiff" as const, input: fields })));
|
||||
}
|
||||
|
||||
@@ -64,7 +68,7 @@ function normalizeCheckpointErrorMessage(error: unknown): string {
|
||||
|
||||
const lower = message.toLowerCase();
|
||||
if (lower.includes("not a git repository")) {
|
||||
return "Turn diffs are unavailable because this project is not a repository.";
|
||||
return "Turn diffs are unavailable because this project is not a git repository.";
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -56,6 +56,11 @@ const rpcClientMock = {
|
||||
filesystem: {
|
||||
browse: vi.fn(),
|
||||
},
|
||||
sourceControl: {
|
||||
lookupRepository: vi.fn(),
|
||||
cloneRepository: vi.fn(),
|
||||
publishRepository: vi.fn(),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: vi.fn(),
|
||||
},
|
||||
@@ -262,7 +267,6 @@ const baseServerConfig: ServerConfig = {
|
||||
};
|
||||
|
||||
const baseGitStatus: VcsStatusResult = {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
@@ -538,6 +542,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
@@ -598,6 +603,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
|
||||
@@ -9,6 +9,24 @@ describe("parsePullRequestReference", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts Azure DevOps pull request URLs", () => {
|
||||
expect(
|
||||
parsePullRequestReference("https://dev.azure.com/acme/project/_git/t3code/pullrequest/42"),
|
||||
).toBe("https://dev.azure.com/acme/project/_git/t3code/pullrequest/42");
|
||||
});
|
||||
|
||||
it("accepts GitLab merge request URLs", () => {
|
||||
expect(parsePullRequestReference("https://gitlab.com/group/project/-/merge_requests/42")).toBe(
|
||||
"https://gitlab.com/group/project/-/merge_requests/42",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts legacy Azure DevOps pull request URLs", () => {
|
||||
expect(
|
||||
parsePullRequestReference("https://acme.visualstudio.com/project/_git/t3code/pullrequest/42"),
|
||||
).toBe("https://acme.visualstudio.com/project/_git/t3code/pullrequest/42");
|
||||
});
|
||||
|
||||
it("accepts raw numbers", () => {
|
||||
expect(parsePullRequestReference("42")).toBe("42");
|
||||
});
|
||||
@@ -31,6 +49,20 @@ describe("parsePullRequestReference", () => {
|
||||
).toBe("https://github.com/pingdotgg/t3code/pull/42");
|
||||
});
|
||||
|
||||
it("accepts glab mr checkout commands with raw numbers", () => {
|
||||
expect(parsePullRequestReference("glab mr checkout 42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts az repos pr checkout commands with raw numbers", () => {
|
||||
expect(parsePullRequestReference("az repos pr checkout --id 42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts az repos pr checkout commands with extra flags", () => {
|
||||
expect(parsePullRequestReference("az repos pr checkout --id 42 --remote-name origin")).toBe(
|
||||
"42",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects non-pull-request input", () => {
|
||||
expect(parsePullRequestReference("feature/my-branch")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
const GITHUB_PULL_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
|
||||
const GITLAB_MERGE_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/[^/\s]*gitlab[^/\s]*\/.+\/-\/merge_requests\/(\d+)(?:[/?#].*)?$/i;
|
||||
const AZURE_DEVOPS_PULL_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
|
||||
const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/;
|
||||
const GITHUB_CLI_PR_CHECKOUT_PATTERN = /^gh\s+pr\s+checkout\s+(.+)$/i;
|
||||
const GITLAB_CLI_MR_CHECKOUT_PATTERN = /^glab\s+mr\s+checkout\s+(.+)$/i;
|
||||
const AZURE_DEVOPS_CLI_PR_CHECKOUT_PATTERN = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
|
||||
|
||||
function parseAzureDevOpsCheckoutReference(args: string): string | null {
|
||||
const parts = args.trim().split(/\s+/).filter(Boolean);
|
||||
const idFlagIndex = parts.findIndex((part) => part === "--id" || part === "-i");
|
||||
if (idFlagIndex >= 0) {
|
||||
return parts[idFlagIndex + 1] ?? null;
|
||||
}
|
||||
return parts.find((part) => !part.startsWith("-")) ?? null;
|
||||
}
|
||||
|
||||
export function parsePullRequestReference(input: string): string | null {
|
||||
const trimmed = input.trim();
|
||||
@@ -10,12 +25,23 @@ export function parsePullRequestReference(input: string): string | null {
|
||||
}
|
||||
|
||||
const ghCliCheckoutMatch = GITHUB_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const normalizedInput = ghCliCheckoutMatch?.[1]?.trim() ?? trimmed;
|
||||
const glabCliCheckoutMatch = GITLAB_CLI_MR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const azureDevOpsCliCheckoutMatch = AZURE_DEVOPS_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const normalizedInput =
|
||||
ghCliCheckoutMatch?.[1]?.trim() ??
|
||||
glabCliCheckoutMatch?.[1]?.trim() ??
|
||||
(azureDevOpsCliCheckoutMatch?.[1]
|
||||
? parseAzureDevOpsCheckoutReference(azureDevOpsCliCheckoutMatch[1])
|
||||
: null) ??
|
||||
trimmed;
|
||||
if (normalizedInput.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
|
||||
const urlMatch =
|
||||
GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput) ??
|
||||
GITLAB_MERGE_REQUEST_URL_PATTERN.exec(normalizedInput) ??
|
||||
AZURE_DEVOPS_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
|
||||
if (urlMatch?.[1]) {
|
||||
return normalizedInput;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import { createWsRpcClient } from "./wsRpcClient";
|
||||
import { type WsTransport } from "./wsTransport";
|
||||
|
||||
const baseLocalStatus: VcsStatusLocalResult = {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
@@ -84,6 +83,7 @@ describe("wsRpcClient", () => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -71,6 +71,11 @@ export interface WsRpcClient {
|
||||
readonly filesystem: {
|
||||
readonly browse: RpcUnaryMethod<typeof WS_METHODS.filesystemBrowse>;
|
||||
};
|
||||
readonly sourceControl: {
|
||||
readonly lookupRepository: RpcUnaryMethod<typeof WS_METHODS.sourceControlLookupRepository>;
|
||||
readonly cloneRepository: RpcUnaryMethod<typeof WS_METHODS.sourceControlCloneRepository>;
|
||||
readonly publishRepository: RpcUnaryMethod<typeof WS_METHODS.sourceControlPublishRepository>;
|
||||
};
|
||||
readonly shell: {
|
||||
readonly openInEditor: (input: {
|
||||
readonly cwd: Parameters<LocalApi["shell"]["openInEditor"]>[0];
|
||||
@@ -165,6 +170,14 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
filesystem: {
|
||||
browse: (input) => transport.request((client) => client[WS_METHODS.filesystemBrowse](input)),
|
||||
},
|
||||
sourceControl: {
|
||||
lookupRepository: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.sourceControlLookupRepository](input)),
|
||||
cloneRepository: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.sourceControlCloneRepository](input)),
|
||||
publishRepository: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.sourceControlPublishRepository](input)),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.shellOpenInEditor](input)),
|
||||
|
||||
@@ -1,96 +1,62 @@
|
||||
import { GitPullRequestIcon } from "lucide-react";
|
||||
import type { ElementType } from "react";
|
||||
import type { SourceControlProviderInfo } from "@t3tools/contracts";
|
||||
export {
|
||||
DEFAULT_CHANGE_REQUEST_TERMINOLOGY,
|
||||
formatChangeRequestAction,
|
||||
formatCreateChangeRequestPhrase,
|
||||
getChangeRequestTerminology,
|
||||
resolveChangeRequestPresentation,
|
||||
type ChangeRequestPresentation,
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
import {
|
||||
getChangeRequestTerminology,
|
||||
resolveChangeRequestPresentation,
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./components/Icons";
|
||||
|
||||
export interface ChangeRequestPresentation {
|
||||
readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";
|
||||
export interface SourceControlPresentation {
|
||||
readonly providerName: string;
|
||||
readonly shortName: string;
|
||||
readonly longName: string;
|
||||
readonly pluralLongName: string;
|
||||
readonly providerLongName: string;
|
||||
readonly checkoutCommandExample: string;
|
||||
readonly urlExample: string;
|
||||
readonly terminology: ChangeRequestTerminology;
|
||||
readonly Icon: ElementType<{ className?: string }>;
|
||||
}
|
||||
|
||||
const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "github",
|
||||
providerName: "GitHub",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "GitHub pull request",
|
||||
checkoutCommandExample: "gh pr checkout 123",
|
||||
urlExample: "https://github.com/owner/repo/pull/42",
|
||||
};
|
||||
|
||||
const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "gitlab",
|
||||
providerName: "GitLab",
|
||||
shortName: "MR",
|
||||
longName: "merge request",
|
||||
pluralLongName: "merge requests",
|
||||
providerLongName: "GitLab merge request",
|
||||
checkoutCommandExample: "glab mr checkout 123",
|
||||
urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
|
||||
};
|
||||
|
||||
const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "azure-devops",
|
||||
providerName: "Azure DevOps",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Azure DevOps pull request",
|
||||
checkoutCommandExample: "az repos pr checkout --id 123",
|
||||
urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
|
||||
};
|
||||
|
||||
const BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "bitbucket",
|
||||
providerName: "Bitbucket",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Bitbucket pull request",
|
||||
checkoutCommandExample: "bb pr checkout 123",
|
||||
urlExample: "https://bitbucket.org/workspace/repo/pull-requests/42",
|
||||
};
|
||||
|
||||
const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "change-request",
|
||||
providerName: "source control",
|
||||
shortName: "change request",
|
||||
longName: "change request",
|
||||
pluralLongName: "change requests",
|
||||
providerLongName: "change request",
|
||||
checkoutCommandExample: "123",
|
||||
urlExample: "#42",
|
||||
};
|
||||
|
||||
export function resolveChangeRequestPresentation(
|
||||
export function getSourceControlPresentation(
|
||||
provider: SourceControlProviderInfo | null | undefined,
|
||||
): ChangeRequestPresentation {
|
||||
switch (provider?.kind) {
|
||||
): SourceControlPresentation {
|
||||
const presentation = resolveChangeRequestPresentation(provider);
|
||||
switch (presentation.icon) {
|
||||
case "github":
|
||||
case undefined:
|
||||
return GITHUB_CHANGE_REQUEST_PRESENTATION;
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: GitHubIcon,
|
||||
};
|
||||
case "gitlab":
|
||||
return GITLAB_CHANGE_REQUEST_PRESENTATION;
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: GitLabIcon,
|
||||
};
|
||||
case "azure-devops":
|
||||
return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: AzureDevOpsIcon,
|
||||
};
|
||||
case "bitbucket":
|
||||
return BITBUCKET_CHANGE_REQUEST_PRESENTATION;
|
||||
case "unknown":
|
||||
return GENERIC_CHANGE_REQUEST_PRESENTATION;
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: BitbucketIcon,
|
||||
};
|
||||
case "change-request":
|
||||
return {
|
||||
providerName: provider?.name || presentation.providerName,
|
||||
terminology: getChangeRequestTerminology(provider),
|
||||
Icon: GitPullRequestIcon,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function formatChangeRequestAction(
|
||||
verb: "View" | "Create",
|
||||
presentation: ChangeRequestPresentation,
|
||||
): string {
|
||||
return `${verb} ${presentation.shortName}`;
|
||||
}
|
||||
|
||||
export function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {
|
||||
return `create ${presentation.shortName}`;
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import type { VcsDriverKind } from "@t3tools/contracts";
|
||||
|
||||
export interface VcsTerms {
|
||||
readonly systemName: string;
|
||||
readonly repositoryNoun: string;
|
||||
readonly refNoun: string;
|
||||
readonly refNounPlural: string;
|
||||
readonly currentRefFallback: string;
|
||||
}
|
||||
|
||||
export interface VcsActionPresentation {
|
||||
readonly supportsGitWorkflowActions: boolean;
|
||||
readonly unsupportedGitWorkflowDescription: string;
|
||||
}
|
||||
|
||||
const gitLikeTerms: VcsTerms = {
|
||||
systemName: "Git",
|
||||
repositoryNoun: "repository",
|
||||
refNoun: "branch",
|
||||
refNounPlural: "branches",
|
||||
currentRefFallback: "checkout",
|
||||
};
|
||||
|
||||
const unknownTerms: VcsTerms = {
|
||||
systemName: "VCS",
|
||||
repositoryNoun: "repository",
|
||||
refNoun: "ref",
|
||||
refNounPlural: "refs",
|
||||
currentRefFallback: "checkout",
|
||||
};
|
||||
|
||||
export function resolveVcsTerms(kind: VcsDriverKind | null | undefined): VcsTerms {
|
||||
if (kind === "jj") {
|
||||
return {
|
||||
systemName: "JJ",
|
||||
repositoryNoun: "workspace",
|
||||
refNoun: "bookmark",
|
||||
refNounPlural: "bookmarks",
|
||||
currentRefFallback: "working copy",
|
||||
};
|
||||
}
|
||||
|
||||
if (kind === "git") {
|
||||
return gitLikeTerms;
|
||||
}
|
||||
|
||||
return unknownTerms;
|
||||
}
|
||||
|
||||
export function resolveVcsActionPresentation(
|
||||
kind: VcsDriverKind | null | undefined,
|
||||
): VcsActionPresentation {
|
||||
const terms = resolveVcsTerms(kind);
|
||||
const supportsGitWorkflowActions = kind === undefined || kind === null || kind === "git";
|
||||
|
||||
return {
|
||||
supportsGitWorkflowActions,
|
||||
unsupportedGitWorkflowDescription: `Git commit, push, and PR actions are not available for this ${terms.systemName} ${terms.repositoryNoun}.`,
|
||||
};
|
||||
}
|
||||
@@ -180,6 +180,7 @@ export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type;
|
||||
|
||||
export const VcsInitInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
kind: Schema.optional(VcsDriverKind),
|
||||
});
|
||||
export type VcsInitInput = typeof VcsInitInput.Type;
|
||||
|
||||
@@ -195,7 +196,6 @@ const VcsStatusChangeRequest = Schema.Struct({
|
||||
});
|
||||
|
||||
const VcsStatusLocalShape = {
|
||||
kind: VcsDriverKind,
|
||||
isRepo: Schema.Boolean,
|
||||
sourceControlProvider: Schema.optional(SourceControlProviderInfo),
|
||||
hasPrimaryRemote: Schema.Boolean,
|
||||
@@ -219,6 +219,7 @@ const VcsStatusRemoteShape = {
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
aheadOfDefaultCount: Schema.optional(NonNegativeInt),
|
||||
pr: Schema.NullOr(VcsStatusChangeRequest),
|
||||
};
|
||||
|
||||
@@ -328,16 +329,6 @@ export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()(
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
|
||||
"TextGenerationError",
|
||||
{
|
||||
@@ -364,7 +355,6 @@ export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()(
|
||||
export const GitManagerServiceError = Schema.Union([
|
||||
GitManagerError,
|
||||
GitCommandError,
|
||||
GitHubCliError,
|
||||
SourceControlProviderError,
|
||||
TextGenerationError,
|
||||
]);
|
||||
|
||||
@@ -55,7 +55,15 @@ import type {
|
||||
import type { EnvironmentId } from "./baseSchemas.ts";
|
||||
import { EditorId } from "./editor.ts";
|
||||
import { ServerSettings, type ClientSettings, type ServerSettingsPatch } from "./settings.ts";
|
||||
import type { SourceControlDiscoveryResult } from "./sourceControl.ts";
|
||||
import type {
|
||||
SourceControlCloneRepositoryInput,
|
||||
SourceControlCloneRepositoryResult,
|
||||
SourceControlDiscoveryResult,
|
||||
SourceControlPublishRepositoryInput,
|
||||
SourceControlPublishRepositoryResult,
|
||||
SourceControlRepositoryInfo,
|
||||
SourceControlRepositoryLookupInput,
|
||||
} from "./sourceControl.ts";
|
||||
|
||||
export interface ContextMenuItem<T extends string = string> {
|
||||
id: T;
|
||||
@@ -258,6 +266,17 @@ export interface EnvironmentApi {
|
||||
filesystem: {
|
||||
browse: (input: FilesystemBrowseInput) => Promise<FilesystemBrowseResult>;
|
||||
};
|
||||
sourceControl: {
|
||||
lookupRepository: (
|
||||
input: SourceControlRepositoryLookupInput,
|
||||
) => Promise<SourceControlRepositoryInfo>;
|
||||
cloneRepository: (
|
||||
input: SourceControlCloneRepositoryInput,
|
||||
) => Promise<SourceControlCloneRepositoryResult>;
|
||||
publishRepository: (
|
||||
input: SourceControlPublishRepositoryInput,
|
||||
) => Promise<SourceControlPublishRepositoryResult>;
|
||||
};
|
||||
vcs: {
|
||||
listRefs: (input: VcsListRefsInput) => Promise<VcsListRefsResult>;
|
||||
createWorktree: (input: VcsCreateWorktreeInput) => Promise<VcsCreateWorktreeResult>;
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ModelSelection,
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationLatestTurn,
|
||||
ProjectCreatedPayload,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput);
|
||||
const decodeFullThreadDiffInput = Schema.decodeUnknownEffect(OrchestrationGetFullThreadDiffInput);
|
||||
const decodeThreadTurnDiff = Schema.decodeUnknownEffect(ThreadTurnDiff);
|
||||
const decodeProjectCreateCommand = Schema.decodeUnknownEffect(ProjectCreateCommand);
|
||||
const decodeProjectCreatedPayload = Schema.decodeUnknownEffect(ProjectCreatedPayload);
|
||||
@@ -59,6 +61,29 @@ it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("parses turn diff input with whitespace ignoring enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeTurnDiffInput({
|
||||
threadId: "thread-1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
assert.strictEqual(parsed.ignoreWhitespace, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("parses full thread diff input with whitespace ignoring enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeFullThreadDiffInput({
|
||||
threadId: "thread-1",
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
assert.strictEqual(parsed.ignoreWhitespace, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects turn diff input when fromTurnCount > toTurnCount", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(
|
||||
|
||||
@@ -1171,7 +1171,10 @@ export const DispatchResult = Schema.Struct({
|
||||
export type DispatchResult = typeof DispatchResult.Type;
|
||||
|
||||
export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(
|
||||
Struct.assign({ threadId: ThreadId }),
|
||||
Struct.assign({
|
||||
threadId: ThreadId,
|
||||
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
}),
|
||||
{ unsafePreserveChecks: true },
|
||||
);
|
||||
export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type;
|
||||
@@ -1182,6 +1185,7 @@ export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResu
|
||||
export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
toTurnCount: NonNegativeInt,
|
||||
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
export type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type;
|
||||
|
||||
|
||||
@@ -77,7 +77,17 @@ import {
|
||||
ServerUpsertKeybindingResult,
|
||||
} from "./server.ts";
|
||||
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
|
||||
import { SourceControlDiscoveryResult } from "./sourceControl.ts";
|
||||
import {
|
||||
SourceControlCloneRepositoryInput,
|
||||
SourceControlCloneRepositoryResult,
|
||||
SourceControlDiscoveryResult,
|
||||
SourceControlPublishRepositoryInput,
|
||||
SourceControlPublishRepositoryResult,
|
||||
SourceControlRepositoryError,
|
||||
SourceControlRepositoryInfo,
|
||||
SourceControlRepositoryLookupInput,
|
||||
} from "./sourceControl.ts";
|
||||
import { VcsError } from "./vcs.ts";
|
||||
|
||||
export const WS_METHODS = {
|
||||
// Project registry methods
|
||||
@@ -124,6 +134,11 @@ export const WS_METHODS = {
|
||||
serverUpdateSettings: "server.updateSettings",
|
||||
serverDiscoverSourceControl: "server.discoverSourceControl",
|
||||
|
||||
// Source control methods
|
||||
sourceControlLookupRepository: "sourceControl.lookupRepository",
|
||||
sourceControlCloneRepository: "sourceControl.cloneRepository",
|
||||
sourceControlPublishRepository: "sourceControl.publishRepository",
|
||||
|
||||
// Streaming subscriptions
|
||||
subscribeVcsStatus: "subscribeVcsStatus",
|
||||
subscribeTerminalEvents: "subscribeTerminalEvents",
|
||||
@@ -174,6 +189,30 @@ export const WsServerDiscoverSourceControlRpc = Rpc.make(WS_METHODS.serverDiscov
|
||||
success: SourceControlDiscoveryResult,
|
||||
});
|
||||
|
||||
export const WsSourceControlLookupRepositoryRpc = Rpc.make(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
{
|
||||
payload: SourceControlRepositoryLookupInput,
|
||||
success: SourceControlRepositoryInfo,
|
||||
error: SourceControlRepositoryError,
|
||||
},
|
||||
);
|
||||
|
||||
export const WsSourceControlCloneRepositoryRpc = Rpc.make(WS_METHODS.sourceControlCloneRepository, {
|
||||
payload: SourceControlCloneRepositoryInput,
|
||||
success: SourceControlCloneRepositoryResult,
|
||||
error: SourceControlRepositoryError,
|
||||
});
|
||||
|
||||
export const WsSourceControlPublishRepositoryRpc = Rpc.make(
|
||||
WS_METHODS.sourceControlPublishRepository,
|
||||
{
|
||||
payload: SourceControlPublishRepositoryInput,
|
||||
success: SourceControlPublishRepositoryResult,
|
||||
error: SourceControlRepositoryError,
|
||||
},
|
||||
);
|
||||
|
||||
export const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntries, {
|
||||
payload: ProjectSearchEntriesInput,
|
||||
success: ProjectSearchEntriesResult,
|
||||
@@ -266,7 +305,7 @@ export const WsVcsSwitchRefRpc = Rpc.make(WS_METHODS.vcsSwitchRef, {
|
||||
|
||||
export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {
|
||||
payload: VcsInitInput,
|
||||
error: GitCommandError,
|
||||
error: VcsError,
|
||||
});
|
||||
|
||||
export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
|
||||
@@ -380,6 +419,9 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetSettingsRpc,
|
||||
WsServerUpdateSettingsRpc,
|
||||
WsServerDiscoverSourceControlRpc,
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
WsSourceControlCloneRepositoryRpc,
|
||||
WsSourceControlPublishRepositoryRpc,
|
||||
WsProjectsSearchEntriesRpc,
|
||||
WsProjectsWriteFileRpc,
|
||||
WsShellOpenInEditorRpc,
|
||||
|
||||
@@ -32,6 +32,7 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
// Model favorites. Historically keyed by provider kind, now
|
||||
// widened to `ProviderInstanceId` so users can favorite a specific model
|
||||
@@ -451,6 +452,7 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
autoOpenPlanSidebar: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
|
||||
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
diffWordWrap: Schema.optionalKey(Schema.Boolean),
|
||||
favorites: Schema.optionalKey(
|
||||
Schema.Array(
|
||||
|
||||
@@ -43,6 +43,66 @@ export const SourceControlRepositoryCloneUrls = Schema.Struct({
|
||||
});
|
||||
export type SourceControlRepositoryCloneUrls = typeof SourceControlRepositoryCloneUrls.Type;
|
||||
|
||||
export const SourceControlRepositoryVisibility = Schema.Literals(["private", "public"]);
|
||||
export type SourceControlRepositoryVisibility = typeof SourceControlRepositoryVisibility.Type;
|
||||
|
||||
export const SourceControlCloneProtocol = Schema.Literals(["auto", "ssh", "https"]);
|
||||
export type SourceControlCloneProtocol = typeof SourceControlCloneProtocol.Type;
|
||||
|
||||
export const SourceControlRepositoryInfo = Schema.Struct({
|
||||
provider: SourceControlProviderKind,
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
export type SourceControlRepositoryInfo = typeof SourceControlRepositoryInfo.Type;
|
||||
|
||||
export const SourceControlRepositoryLookupInput = Schema.Struct({
|
||||
provider: SourceControlProviderKind,
|
||||
repository: TrimmedNonEmptyString,
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type SourceControlRepositoryLookupInput = typeof SourceControlRepositoryLookupInput.Type;
|
||||
|
||||
export const SourceControlCloneRepositoryInput = Schema.Struct({
|
||||
provider: Schema.optional(SourceControlProviderKind),
|
||||
repository: Schema.optional(TrimmedNonEmptyString),
|
||||
remoteUrl: Schema.optional(TrimmedNonEmptyString),
|
||||
destinationPath: TrimmedNonEmptyString,
|
||||
protocol: Schema.optional(SourceControlCloneProtocol),
|
||||
});
|
||||
export type SourceControlCloneRepositoryInput = typeof SourceControlCloneRepositoryInput.Type;
|
||||
|
||||
export const SourceControlCloneRepositoryResult = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
remoteUrl: TrimmedNonEmptyString,
|
||||
repository: Schema.NullOr(SourceControlRepositoryInfo),
|
||||
});
|
||||
export type SourceControlCloneRepositoryResult = typeof SourceControlCloneRepositoryResult.Type;
|
||||
|
||||
export const SourceControlPublishRepositoryInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
provider: SourceControlProviderKind,
|
||||
repository: TrimmedNonEmptyString,
|
||||
visibility: SourceControlRepositoryVisibility,
|
||||
remoteName: Schema.optional(TrimmedNonEmptyString),
|
||||
protocol: Schema.optional(SourceControlCloneProtocol),
|
||||
});
|
||||
export type SourceControlPublishRepositoryInput = typeof SourceControlPublishRepositoryInput.Type;
|
||||
|
||||
export const SourceControlPublishStatus = Schema.Literals(["pushed", "remote_added"]);
|
||||
export type SourceControlPublishStatus = typeof SourceControlPublishStatus.Type;
|
||||
|
||||
export const SourceControlPublishRepositoryResult = Schema.Struct({
|
||||
repository: SourceControlRepositoryInfo,
|
||||
remoteName: TrimmedNonEmptyString,
|
||||
remoteUrl: TrimmedNonEmptyString,
|
||||
branch: TrimmedNonEmptyString,
|
||||
upstreamBranch: Schema.optional(TrimmedNonEmptyString),
|
||||
status: SourceControlPublishStatus,
|
||||
});
|
||||
export type SourceControlPublishRepositoryResult = typeof SourceControlPublishRepositoryResult.Type;
|
||||
|
||||
export const SourceControlDiscoveryStatus = Schema.Literals(["available", "missing"]);
|
||||
export type SourceControlDiscoveryStatus = typeof SourceControlDiscoveryStatus.Type;
|
||||
|
||||
@@ -63,7 +123,7 @@ export type SourceControlProviderAuth = typeof SourceControlProviderAuth.Type;
|
||||
|
||||
const SourceControlDiscoveryItemFields = {
|
||||
label: TrimmedNonEmptyString,
|
||||
executable: TrimmedNonEmptyString,
|
||||
executable: Schema.optional(TrimmedNonEmptyString),
|
||||
implemented: Schema.Boolean,
|
||||
status: SourceControlDiscoveryStatus,
|
||||
version: Schema.Option(TrimmedNonEmptyString),
|
||||
@@ -109,3 +169,17 @@ export class SourceControlProviderError extends Schema.TaggedErrorClass<SourceCo
|
||||
return `Source control provider ${this.provider} failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SourceControlRepositoryError extends Schema.TaggedErrorClass<SourceControlRepositoryError>()(
|
||||
"SourceControlRepositoryError",
|
||||
{
|
||||
provider: SourceControlProviderKind,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Source control repository operation ${this.operation} failed for ${this.provider}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,6 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
};
|
||||
|
||||
expect(applyGitStatusStreamEvent(null, { _tag: "remoteUpdated", remote })).toEqual({
|
||||
kind: "unknown",
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
@@ -97,7 +96,6 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
|
||||
it("preserves local-only fields when applying a remote update", () => {
|
||||
const current: VcsStatusResult = {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
sourceControlProvider: {
|
||||
kind: "github",
|
||||
|
||||
@@ -202,6 +202,7 @@ const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
@@ -220,13 +221,15 @@ function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
|
||||
hasUpstream: status.hasUpstream,
|
||||
aheadCount: status.aheadCount,
|
||||
behindCount: status.behindCount,
|
||||
...(status.aheadOfDefaultCount === undefined
|
||||
? {}
|
||||
: { aheadOfDefaultCount: status.aheadOfDefaultCount }),
|
||||
pr: status.pr,
|
||||
};
|
||||
}
|
||||
|
||||
function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
|
||||
return {
|
||||
kind: status.kind,
|
||||
isRepo: status.isRepo,
|
||||
...(status.sourceControlProvider
|
||||
? { sourceControlProvider: status.sourceControlProvider }
|
||||
@@ -252,7 +255,6 @@ export function applyGitStatusStreamEvent(
|
||||
if (current === null) {
|
||||
return mergeGitStatusParts(
|
||||
{
|
||||
kind: "unknown",
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
detectSourceControlProviderFromRemoteUrl,
|
||||
getChangeRequestTerminologyForKind,
|
||||
resolveChangeRequestPresentation,
|
||||
} from "./sourceControl.ts";
|
||||
|
||||
describe("source control presentation", () => {
|
||||
it("uses merge request terminology for GitLab", () => {
|
||||
expect(getChangeRequestTerminologyForKind("gitlab")).toEqual({
|
||||
shortLabel: "MR",
|
||||
singular: "merge request",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses pull request terminology for GitHub-compatible providers", () => {
|
||||
expect(getChangeRequestTerminologyForKind("github")).toEqual({
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
});
|
||||
expect(getChangeRequestTerminologyForKind("azure-devops")).toEqual({
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
});
|
||||
expect(getChangeRequestTerminologyForKind("bitbucket")).toEqual({
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to generic change request copy for unknown providers", () => {
|
||||
expect(
|
||||
resolveChangeRequestPresentation({ kind: "unknown", name: "forge", baseUrl: "" }),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
shortName: "change request",
|
||||
longName: "change request",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectSourceControlProviderFromRemoteUrl", () => {
|
||||
it("detects common source control hosts", () => {
|
||||
expect(detectSourceControlProviderFromRemoteUrl("[email protected]:owner/repo.git")?.kind).toBe(
|
||||
"github",
|
||||
);
|
||||
expect(
|
||||
detectSourceControlProviderFromRemoteUrl("https://gitlab.com/group/repo.git")?.kind,
|
||||
).toBe("gitlab");
|
||||
expect(
|
||||
detectSourceControlProviderFromRemoteUrl("https://dev.azure.com/org/project/_git/repo")?.kind,
|
||||
).toBe("azure-devops");
|
||||
expect(
|
||||
detectSourceControlProviderFromRemoteUrl("[email protected]:workspace/repo.git")?.kind,
|
||||
).toBe("bitbucket");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,139 @@
|
||||
import type { SourceControlProviderInfo } from "@t3tools/contracts";
|
||||
import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";
|
||||
|
||||
export interface ChangeRequestPresentation {
|
||||
readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";
|
||||
readonly providerName: string;
|
||||
readonly shortName: string;
|
||||
readonly longName: string;
|
||||
readonly pluralLongName: string;
|
||||
readonly providerLongName: string;
|
||||
readonly checkoutCommandExample: string;
|
||||
readonly urlExample: string;
|
||||
}
|
||||
|
||||
export interface ChangeRequestTerminology {
|
||||
readonly shortLabel: string;
|
||||
readonly singular: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_CHANGE_REQUEST_TERMINOLOGY: ChangeRequestTerminology = {
|
||||
shortLabel: "PR",
|
||||
singular: "pull request",
|
||||
};
|
||||
|
||||
const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "github",
|
||||
providerName: "GitHub",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "GitHub pull request",
|
||||
checkoutCommandExample: "gh pr checkout 123",
|
||||
urlExample: "https://github.com/owner/repo/pull/42",
|
||||
};
|
||||
|
||||
const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "gitlab",
|
||||
providerName: "GitLab",
|
||||
shortName: "MR",
|
||||
longName: "merge request",
|
||||
pluralLongName: "merge requests",
|
||||
providerLongName: "GitLab merge request",
|
||||
checkoutCommandExample: "glab mr checkout 123",
|
||||
urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
|
||||
};
|
||||
|
||||
const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "azure-devops",
|
||||
providerName: "Azure DevOps",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Azure DevOps pull request",
|
||||
checkoutCommandExample: "az repos pr checkout --id 123",
|
||||
urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
|
||||
};
|
||||
|
||||
const BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "bitbucket",
|
||||
providerName: "Bitbucket",
|
||||
shortName: "PR",
|
||||
longName: "pull request",
|
||||
pluralLongName: "pull requests",
|
||||
providerLongName: "Bitbucket pull request",
|
||||
checkoutCommandExample: "bb pr checkout 123",
|
||||
urlExample: "https://bitbucket.org/workspace/repo/pull-requests/42",
|
||||
};
|
||||
|
||||
const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
|
||||
icon: "change-request",
|
||||
providerName: "source control",
|
||||
shortName: "change request",
|
||||
longName: "change request",
|
||||
pluralLongName: "change requests",
|
||||
providerLongName: "change request",
|
||||
checkoutCommandExample: "123",
|
||||
urlExample: "#42",
|
||||
};
|
||||
|
||||
export function resolveChangeRequestPresentation(
|
||||
provider: SourceControlProviderInfo | null | undefined,
|
||||
): ChangeRequestPresentation {
|
||||
switch (provider?.kind) {
|
||||
case "github":
|
||||
case undefined:
|
||||
return GITHUB_CHANGE_REQUEST_PRESENTATION;
|
||||
case "gitlab":
|
||||
return GITLAB_CHANGE_REQUEST_PRESENTATION;
|
||||
case "azure-devops":
|
||||
return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
|
||||
case "bitbucket":
|
||||
return BITBUCKET_CHANGE_REQUEST_PRESENTATION;
|
||||
case "unknown":
|
||||
return GENERIC_CHANGE_REQUEST_PRESENTATION;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveChangeRequestPresentationForKind(
|
||||
kind: SourceControlProviderKind,
|
||||
): ChangeRequestPresentation {
|
||||
return resolveChangeRequestPresentation({ kind, name: "", baseUrl: "" });
|
||||
}
|
||||
|
||||
export function formatChangeRequestAction(
|
||||
verb: "View" | "Create",
|
||||
presentation: ChangeRequestPresentation,
|
||||
): string {
|
||||
return `${verb} ${presentation.shortName}`;
|
||||
}
|
||||
|
||||
export function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {
|
||||
return `create ${presentation.shortName}`;
|
||||
}
|
||||
|
||||
export function getChangeRequestTerminology(
|
||||
provider: SourceControlProviderInfo | null | undefined,
|
||||
): ChangeRequestTerminology {
|
||||
if (!provider) {
|
||||
return DEFAULT_CHANGE_REQUEST_TERMINOLOGY;
|
||||
}
|
||||
|
||||
const presentation = resolveChangeRequestPresentation(provider);
|
||||
return {
|
||||
shortLabel: presentation.shortName,
|
||||
singular: presentation.longName,
|
||||
};
|
||||
}
|
||||
|
||||
export function getChangeRequestTerminologyForKind(
|
||||
kind: SourceControlProviderKind,
|
||||
): ChangeRequestTerminology {
|
||||
const presentation = resolveChangeRequestPresentationForKind(kind);
|
||||
return {
|
||||
shortLabel: presentation.shortName,
|
||||
singular: presentation.longName,
|
||||
};
|
||||
}
|
||||
|
||||
function parseRemoteHost(remoteUrl: string): string | null {
|
||||
const trimmed = remoteUrl.trim();
|
||||
|
||||
Reference in new issue
Block a user