Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import { GitCommandError } from "@t3tools/contracts";
3import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7
8import * as TanStackSourceApi from "./TanStackSourceApi.ts";
9import * as TanStackSourceSourceControlProvider from "./TanStackSourceSourceControlProvider.ts";
10
11const REMOTE = "https://source.tanstack.com/@acme/web.git";
12const OWNER_KEY = "branch.pr-42.t3TanstackSourcePull";
13
14/** Pull request #42 of acme/web, opened from a fork, so it checks out as `pr-42`. */
15const PULL = {
16 number: 42,
17 title: "Fix the thing",
18 state: "open",
19 draft: false,
20 author: "bob",
21 head: "fix-thing",
22 createdAt: 1_000,
23 body: null,
24 base: "main",
25 headRepo: "bob/web",
26 headSha: "c".repeat(40),
27 baseSha: "b".repeat(40),
28 mergeCommitSha: null,
29 mergedAt: null,
30 mergedBy: null,
31 mergeable: null,
32 changedFiles: null,
33};
34
35function checkout(options: {
36 readonly recordedOwner: string | null;
37 readonly isAncestor: boolean;
38 readonly pull?: Partial<typeof PULL>;
39 readonly force?: boolean;
40}) {
41 const git: Array<string> = [];
42 const config = new Map<string, string>(
43 options.recordedOwner === null ? [] : [[OWNER_KEY, options.recordedOwner]],
44 );
45 const api = TanStackSourceApi.TanStackSourceApi.of({
46 request: (input) =>
47 input.path === "/repos/acme/web/pulls/42"
48 ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull }))
49 : Effect.die(`unexpected ${input.path}`),
50 response: () => Effect.die("unexpected response read"),
51 });
52 const host = TestSourceControlHost.layer({
53 git: {
54 resolvePrimaryRemoteName: () => Effect.succeed("origin"),
55 ensureRemote: (input) =>
56 Effect.sync(() => {
57 git.push(`remote ${input.preferredName} ${input.url}`);
58 return input.url === REMOTE ? "origin" : input.preferredName;
59 }),
60 fetchRemoteBranch: (input) =>
61 Effect.sync(
62 () =>
63 void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`),
64 ),
65 fetchRemoteTrackingBranch: () => Effect.void,
66 setBranchUpstream: (input) =>
67 Effect.sync(
68 () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`),
69 ),
70 readConfigValue: (_cwd, key) =>
71 Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)),
72 writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)),
73 listLocalBranchNames: () => Effect.succeed(["main", "pr-42"]),
74 createBranch: (input) => Effect.sync(() => void git.push(`create ${input.branch}`)),
75 switchRef: (input) =>
76 Effect.sync(() => {
77 git.push(`switch ${input.refName}`);
78 return { refName: input.refName };
79 }),
80 execute: (input) =>
81 input.args[0] === "merge-base" && !options.isAncestor
82 ? Effect.fail(
83 new GitCommandError({
84 operation: input.operation,
85 command: "git",
86 cwd: input.cwd,
87 argumentCount: input.args.length,
88 exitCode: 1,
89 detail: "not an ancestor",
90 }),
91 )
92 : Effect.sync(() => {
93 git.push(input.args.join(" "));
94 return {
95 exitCode: 0,
96 stdout: "",
97 stderr: "",
98 stdoutTruncated: false,
99 stderrTruncated: false,
100 } as never;
101 }),
102 },
103 });
104 const run = TanStackSourceSourceControlProvider.make.pipe(
105 Effect.flatMap((provider) =>
106 provider.checkoutChangeRequest({
107 cwd: "/repo",
108 reference: "42",
109 ...(options.force === undefined ? {} : { force: options.force }),
110 }),
111 ),
112 Effect.provideService(TanStackSourceApi.TanStackSourceApi, api),
113 Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))),
114 );
115 return { run, git, config };
116}
117
118describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => {
119 it.effect(
120 "refuses a pr-<n> branch T3 did not make for this pull request, and leaves it alone",
121 () => {
122 // An unrelated branch at the pull request's base is an ancestor of its head.
123 const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true });
124 return Effect.gen(function* () {
125 const error = yield* Effect.flip(run);
126 assert.include(error.detail, "pr-42 was not made for pull request #42");
127 assert.isFalse(
128 git.some((command) => command.startsWith("checkout") || command.startsWith("switch")),
129 );
130 assert.isFalse(config.has(OWNER_KEY));
131 });
132 },
133 );
134
135 it.effect("moves the branch it made for the pull request up to the new head", () => {
136 const { run, git } = checkout({ recordedOwner: "acme/web#42", isAncestor: true });
137 return Effect.gen(function* () {
138 yield* run;
139 assert.deepStrictEqual(
140 git.filter((command) => /^(checkout|switch|create) /u.test(command)),
141 ["checkout --no-track -B pr-42 refs/remotes/origin/pull/42 --", "switch pr-42"],
142 );
143 });
144 });
145
146 it.effect("keeps local commits on its own branch rather than moving it", () => {
147 const { run, git } = checkout({ recordedOwner: "acme/web#42", isAncestor: false });
148 return Effect.gen(function* () {
149 const error = yield* Effect.flip(run);
150 assert.include(error.detail, "has commits pull request #42 does not");
151 assert.isFalse(git.some((command) => command.startsWith("checkout")));
152 });
153 });
154
155 // Source publishes no `refs/pull/<n>/head` for a private pull request, on either repository.
156 it.effect("takes a private pull request's branch from the companion repository", () => {
157 const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" };
158 const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull });
159 const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true });
160 return Effect.gen(function* () {
161 yield* forced.run;
162 assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --");
163 yield* run;
164 assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme");
165 assert.deepStrictEqual(git, [
166 `remote source ${REMOTE}`,
167 "remote acme https://source.tanstack.com/@acme/web.private.git",
168 "fetch acme fix-thing:fix-thing",
169 "upstream fix-thing acme/fix-thing",
170 "switch fix-thing",
171 ]);
172 });
173 });
174});
175
176describe("TanStackSourceSourceControlProvider private pull requests", () => {
177 it.effect("asks Source for the companion and opens the pull request as private", () => {
178 const requests: Array<{ method: string; path: string; body: unknown }> = [];
179 const api = TanStackSourceApi.TanStackSourceApi.of({
180 request: (input) => {
181 requests.push({ method: input.method ?? "GET", path: input.path, body: input.body });
182 return Effect.succeed(
183 JSON.stringify({
184 owner: "acme",
185 name: "web.private",
186 defaultBranch: null,
187 cloneUrl: "https://source.tanstack.com/@acme/web.private.git",
188 }),
189 );
190 },
191 response: () => Effect.die("unexpected response read"),
192 });
193 const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") });
194 return Effect.gen(function* () {
195 const provider = yield* TanStackSourceSourceControlProvider.make;
196 const companion = provider.privateChangeRequestRemote;
197 assert.isDefined(companion);
198 assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), {
199 url: "https://source.tanstack.com/@acme/web.private.git",
200 repository: "acme/web.private",
201 });
202 yield* provider.createChangeRequest({
203 cwd: "/repo",
204 baseRefName: "main",
205 headSelector: "sec/fix",
206 title: "Fix",
207 bodyFile: "/tmp/body.md",
208 private: true,
209 });
210 assert.deepStrictEqual(requests, [
211 { method: "POST", path: "/repos/acme/web/private-remote", body: undefined },
212 {
213 method: "POST",
214 path: "/repos/acme/web/pulls",
215 body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true },
216 },
217 ]);
218 }).pipe(
219 Effect.provideService(TanStackSourceApi.TanStackSourceApi, api),
220 Effect.provide(
221 Layer.merge(
222 TestSourceControlHost.layer({
223 git: {
224 resolvePrimaryRemoteName: () => Effect.succeed("origin"),
225 readConfigValue: () => Effect.succeed(REMOTE),
226 },
227 }),
228 files,
229 ),
230 ),
231 );
232 });
233});