Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TanStackSourceSourceControlProvider.test.ts

279 lines10.5 KB

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