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

AzureDevOpsCli.test.ts

726 lines26.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as PlatformError from "effect/PlatformError";
7import { ChildProcessSpawner } from "effect/process";
8import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
9​
10import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
11import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { SpawnExecutableResolution } from "@t3tools/shared/shell";
14import { AzureCliInstallLocation, type AzureCliInstall } from "./azureCliLauncher.ts";
15import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
16import { primaryRemoteUrl, scopeAzureCliArgs } from "./AzureDevOpsCli.ts";
17​
18const processOutput = (stdout: string): SourceControlHost.SourceControlProcessOutput => ({
19 exitCode: ChildProcessSpawner.ExitCode(0),
20 stdout,
21 stderr: "",
22 stdoutTruncated: false,
23 stderrTruncated: false,
24});
25​
26const mockRun = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
27​
28// The CLI layer is exercised on a host that spawns `az` itself, so the launcher upgrade stays out of these assertions.
29const layerSupport = Layer.mergeAll(
30 TestSourceControlHost.layer({
31 // No remotes: these cases leave `--detect true` to az.
32 process: {
33 run: (input) =>
34 input.command === "git" ? Effect.succeed(processOutput("")) : mockRun(input),
35 },
36 }),
37 NodeServices.layer,
38 Layer.succeed(HostProcess.Platform, "linux"),
39);
40const layer = Layer.mergeAll(AzureDevOpsCli.layer.pipe(Layer.provide(layerSupport)), layerSupport);
41​
42afterEach(() => {
43 mockRun.mockReset();
44});
45​
46describe("AzureDevOpsCli.layer", () => {
47 it.effect("parses pull request view output", () =>
48 Effect.gen(function* () {
49 mockRun.mockReturnValueOnce(
50 Effect.succeed(
51 processOutput(
52 JSON.stringify({
53 pullRequestId: 42,
54 title: "Add Azure provider",
55 sourceRefName: "refs/heads/feature/source-control",
56 targetRefName: "refs/heads/main",
57 lastMergeSourceCommit: { commitId: "a".repeat(40) },
58 status: "active",
59 creationDate: "2026-01-02T00:00:00.000Z",
60 closedDate: null,
61 _links: {
62 web: {
63 href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
64 },
65 },
66 }),
67 ),
68 ),
69 );
70​
71 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
72 const result = yield* az.getPullRequest({
73 cwd: "/repo",
74 reference: "#42",
75 // The selected remote numbers the pull request, whatever the checkout's primary remote.
76 remoteUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
77 });
78​
79 assert.strictEqual(result.number, 42);
80 assert.strictEqual(result.title, "Add Azure provider");
81 assert.strictEqual(result.url, "https://dev.azure.com/acme/project/_git/repo/pullrequest/42");
82 assert.strictEqual(result.baseRefName, "main");
83 assert.strictEqual(result.headRefName, "feature/source-control");
84 assert.strictEqual(result.headSha, "a".repeat(40));
85 assert.strictEqual(result.state, "open");
86 assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
87 const { classifyFailure, ...call } = mockRun.mock.calls.at(-1)?.[0] ?? {};
88 assert.strictEqual(
89 classifyFailure?.("Please run az login to setup account."),
90 "authentication",
91 );
92 assert.strictEqual(
93 classifyFailure?.("Please run 'az login' to setup account."),
94 "authentication",
95 );
96 assert.strictEqual(
97 classifyFailure?.("TF401180: The requested pull request was not found."),
98 "not-found",
99 );
100 assert.strictEqual(
101 classifyFailure?.(
102 "ERROR: TF400733: The request has been canceled: Request was blocked due to exceeding usage of resource 'Global' in namespace 'User'.",
103 ),
104 "rate-limited",
105 );
106 assert.deepStrictEqual(call, {
107 operation: "AzureDevOpsCli.execute",
108 command: "az",
109 args: [
110 "repos",
111 "pr",
112 "show",
113 "--detect",
114 "false",
115 "--id",
116 "42",
117 "--only-show-errors",
118 "--output",
119 "json",
120 "--organization",
121 "https://dev.azure.com/acme",
122 ],
123 cwd: "/repo",
124 notFoundDetail: "Pull request not found.",
125 timeoutMs: AzureDevOpsCli.AZ_TIMEOUT_MS,
126 });
127 assert.strictEqual(result.isCrossRepository, false);
128 }).pipe(Effect.provide(layer)),
129 );
130​
131 it.effect("marks a pull request from a fork as cross-repository", () =>
132 Effect.gen(function* () {
133 mockRun.mockReturnValueOnce(
134 Effect.succeed(
135 processOutput(
136 JSON.stringify({
137 pullRequestId: 43,
138 title: "From a fork",
139 sourceRefName: "refs/heads/main",
140 targetRefName: "refs/heads/main",
141 status: "active",
142 forkSource: { name: "refs/heads/main", repository: { name: "repo-fork" } },
143 }),
144 ),
145 ),
146 );
147​
148 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
149 const result = yield* az.getPullRequest({ cwd: "/repo", reference: "43" });
150​
151 assert.strictEqual(result.isCrossRepository, true);
152 }).pipe(Effect.provide(layer)),
153 );
154​
155 it.effect("builds a web URL when Azure returns only the pull request REST URL", () =>
156 Effect.gen(function* () {
157 mockRun.mockReturnValueOnce(
158 Effect.succeed(
159 processOutput(
160 JSON.stringify({
161 pullRequestId: 863,
162 title: "Fix Azure link",
163 url: "https://dev.azure.com/saplyai/a8fe4088-ad76-4eda-aaaa-e3329713a097/_apis/git/repositories/16108a25-93a3-4eff-b77d-85e894ee0fe4/pullRequests/863",
164 repository: {
165 name: "CV-engine",
166 project: {
167 name: "CV-engine",
168 },
169 },
170 sourceRefName: "refs/heads/feature/azure-pr-link",
171 targetRefName: "refs/heads/main",
172 status: "active",
173 }),
174 ),
175 ),
176 );
177​
178 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
179 const result = yield* az.getPullRequest({
180 cwd: "/repo",
181 reference: "863",
182 });
183​
184 assert.strictEqual(
185 result.url,
186 "https://dev.azure.com/saplyai/CV-engine/_git/CV-engine/pullrequest/863",
187 );
188 }).pipe(Effect.provide(layer)),
189 );
190​
191 it.effect("reads repository clone URLs", () =>
192 Effect.gen(function* () {
193 mockRun.mockReturnValueOnce(
194 Effect.succeed(
195 processOutput(
196 JSON.stringify({
197 name: "repo",
198 webUrl: "https://dev.azure.com/acme/project/_git/repo",
199 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
200 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
201 project: {
202 name: "project",
203 },
204 }),
205 ),
206 ),
207 );
208​
209 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
210 const result = yield* az.getRepositoryCloneUrls({
211 cwd: "/repo",
212 repository: "repo",
213 });
214​
215 assert.deepStrictEqual(result, {
216 nameWithOwner: "project/repo",
217 url: "https://dev.azure.com/acme/project/_git/repo",
218 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
219 });
220 }).pipe(Effect.provide(layer)),
221 );
222​
223 it.effect("keeps a nonbreaking space at the end of the default branch", () =>
224 Effect.gen(function* () {
225 mockRun.mockReturnValueOnce(
226 Effect.succeed(
227 processOutput(
228 JSON.stringify({
229 name: "repo",
230 webUrl: "https://dev.azure.com/acme/project/_git/repo",
231 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
232 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
233 defaultBranch: "refs/heads/release\u00a0",
234 }),
235 ),
236 ),
237 );
238​
239 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
240 const branch = yield* az.getDefaultBranch({ cwd: "/repo", repository: "repo" });
241​
242 assert.strictEqual(branch, "release\u00a0");
243 }).pipe(Effect.provide(layer)),
244 );
245​
246 it.effect("looks up a project/repository path as that project's repository", () =>
247 Effect.gen(function* () {
248 mockRun.mockReturnValueOnce(
249 Effect.succeed(
250 processOutput(
251 JSON.stringify({
252 name: "repo",
253 webUrl: "https://dev.azure.com/acme/project/_git/repo",
254 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
255 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
256 project: { name: "project" },
257 }),
258 ),
259 ),
260 );
261​
262 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
263 yield* az.getRepositoryCloneUrls({ cwd: "/somewhere", repository: "project/repo" });
264​
265 assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0].args, [
266 "repos",
267 "show",
268 "--detect",
269 "true",
270 "--repository=repo",
271 "--project=project",
272 "--only-show-errors",
273 "--output",
274 "json",
275 ]);
276 }).pipe(Effect.provide(layer)),
277 );
278​
279 it.effect("sends repository and project names that look like `@path` as text", () =>
280 Effect.gen(function* () {
281 const repository = JSON.stringify({
282 name: "repo",
283 webUrl: "https://dev.azure.com/acme/project/_git/repo",
284 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
285 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
286 });
287 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
288 const callsFor = (
289 outputs: ReadonlyArray<string>,
290 run: Effect.Effect<unknown, AzureDevOpsCli.AzureDevOpsCliError>,
291 ) =>
292 Effect.gen(function* () {
293 mockRun.mockReset();
294 for (const stdout of outputs) {
295 mockRun.mockReturnValueOnce(Effect.succeed(processOutput(stdout)));
296 }
297 yield* run;
298 return mockRun.mock.calls.map(([call]) => ({
299 args: call.args.slice(0, -3),
300 stdin: call.stdin,
301 }));
302 });
303 const show = (specifier: string) =>
304 callsFor(
305 [repository],
306 az.getRepositoryCloneUrls({ cwd: "/somewhere", repository: specifier }),
307 );
308 const repos = ["repos", "show", "--detect", "true"];
309​
310 assert.deepStrictEqual(yield* show("project/@repo"), [
311 { args: [...repos, "--repository=@-", "--project=project"], stdin: "@repo" },
312 ]);
313 assert.deepStrictEqual(yield* show("@project/-repo"), [
314 { args: [...repos, "--repository=-repo", "--project=@-"], stdin: "@project" },
315 ]);
316​
317 // az has one stdin: the project is read first and named by its ID in the lookup.
318 const projectId = "d18445d6-86b1-4b1d-88aa-bc6d45d8b9b0";
319 const withProjectId = (run: Effect.Effect<unknown, AzureDevOpsCli.AzureDevOpsCliError>) =>
320 callsFor([JSON.stringify({ id: projectId }), repository], run);
321 const project = {
322 args: ["devops", "project", "show", "--detect", "true", "--project=@-"],
323 stdin: "@project",
324 };
325 assert.deepStrictEqual(
326 yield* withProjectId(
327 az.getDefaultBranch({ cwd: "/somewhere", repository: "@project/@repo" }),
328 ),
329 [
330 project,
331 { args: [...repos, "--repository=@-", `--project=${projectId}`], stdin: "@repo" },
332 ],
333 );
334 assert.deepStrictEqual(
335 yield* withProjectId(
336 az.createRepository({
337 cwd: "/somewhere",
338 repository: "@project/@repo",
339 visibility: "private",
340 }),
341 ),
342 [
343 project,
344 {
345 args: ["repos", "create", "--detect", "true", "--name=@-", `--project=${projectId}`],
346 stdin: "@repo",
347 },
348 ],
349 );
350 }).pipe(Effect.provide(layer)),
351 );
352​
353 it.effect("runs az only for a reference that holds a pull request number", () =>
354 Effect.gen(function* () {
355 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
356 // az would read `@notes.txt` as a file and `--help` as an option.
357 for (const reference of ["@notes.txt", "--help", "feature"]) {
358 const error = yield* az.getPullRequest({ cwd: "/repo", reference }).pipe(Effect.flip);
359 assert.strictEqual(error._tag, "AzureDevOpsPullRequestNotFoundError");
360 }
361 expect(mockRun).not.toHaveBeenCalled();
362 }).pipe(Effect.provide(layer)),
363 );
364​
365 // az can spend 30+ seconds just loading itself when endpoint security scans every file it opens.
366 it.effect("gives a pull request list longer than a slow az start-up takes", () =>
367 Effect.gen(function* () {
368 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
369​
370 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
371 yield* az.listPullRequests({ cwd: "/repo", headSelector: "feature", state: "all" });
372​
373 expect(mockRun.mock.calls.at(-1)?.[0].timeoutMs).toBeGreaterThan(34_000);
374 }).pipe(Effect.provide(layer)),
375 );
376​
377 it.effect("percent-encodes the source branch while preserving recognized ref prefixes", () =>
378 Effect.gen(function* () {
379 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
380​
381 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
382 yield* az.listPullRequests({
383 cwd: "/somewhere",
384 headSelector: "user/feat/1-(#2)-slug",
385 state: "open",
386 });
387​
388 // Joined so a branch starting with `-` stays the option's value.
389 expect(mockRun.mock.calls.at(-1)?.[0].args).toContain(
390 "--source-branch=user%2Ffeat%2F1-(%232)-slug",
391 );
392​
393 for (const prefix of ["refs/heads/", "refs/pull/", "refs/tags/"]) {
394 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
395 yield* az.listPullRequests({
396 cwd: "/somewhere",
397 headSelector: "fallback",
398 source: { refName: `${prefix}user/feat/1-(#2)-slug` },
399 state: "open",
400 });
401​
402 expect(mockRun.mock.calls.at(-1)?.[0].args).toContain(
403 `--source-branch=${prefix}user%2Ffeat%2F1-(%232)-slug`,
404 );
405 }
406 }).pipe(Effect.provide(layer)),
407 );
408​
409 it.effect("sends a title that looks like `@path` as text, not as a file for az to read", () =>
410 Effect.gen(function* () {
411 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
412 for (const title of ["@notes.txt", "a=@notes.txt"]) {
413 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
414 yield* az.createPullRequest({
415 cwd: "/somewhere",
416 baseBranch: "main",
417 headSelector: "feature",
418 title,
419 bodyFile: "/tmp/body.md",
420 });
421​
422 // az replaces an argument that starts with `@`, or whose text after the first `=` does, with that file's contents.
423 const fileReads = (mockRun.mock.calls.at(-1)?.[0].args ?? []).flatMap((arg) => {
424 const value = arg.startsWith("@") ? arg : arg.slice(arg.indexOf("=") + 1);
425 return (arg.startsWith("@") || arg.includes("=")) && value.startsWith("@")
426 ? [value.slice(1)]
427 : [];
428 });
429 expect(fileReads).not.toContain("notes.txt");
430 expect(mockRun.mock.calls.at(-1)?.[0].stdin).toBe(
431 title.startsWith("@") ? title : undefined,
432 );
433 // az expands a separate `@file` value a second time, so a body of `@notes.txt` read notes.txt.
434 expect(mockRun.mock.calls.at(-1)?.[0].args).toContain("--description=@/tmp/body.md");
435 }
436​
437 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
438 yield* az.createPullRequest({
439 cwd: "/somewhere",
440 baseBranch: "main",
441 headSelector: "feature",
442 title: "Draft",
443 bodyFile: "/tmp/body.md",
444 draft: true,
445 });
446 expect(mockRun.mock.calls.at(-1)?.[0].args.join(" ")).toContain("--draft true");
447 }).pipe(Effect.provide(layer)),
448 );
449​
450 it.effect("preserves VCS causes without copying upstream details into messages", () =>
451 Effect.gen(function* () {
452 const cause = new VcsProcessExitError({
453 operation: "AzureDevOpsCli.execute",
454 command: "az repos list --organization sensitive-upstream-detail",
455 cwd: "/repo",
456 exitCode: 1,
457 detail: "sensitive-upstream-detail",
458 });
459 mockRun.mockReturnValueOnce(Effect.fail(cause));
460​
461 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
462 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
463​
464 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
465 assert.strictEqual(error.operation, "execute");
466 assert.strictEqual(error.command, "az");
467 assert.strictEqual(error.cwd, "/repo");
468 assert.strictEqual(error.argumentCount, 2);
469 assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
470 assert.strictEqual(error.cause, cause);
471 assert.equal(error.message.includes("sensitive-upstream-detail"), false);
472 }).pipe(Effect.provide(layer)),
473 );
474​
475 it.effect("does not report a missing working directory as a missing Azure CLI", () =>
476 Effect.gen(function* () {
477 const cwd = "/missing/repo";
478 const platformCause = PlatformError.systemError({
479 _tag: "NotFound",
480 module: "ChildProcess",
481 method: "spawn",
482 syscall: "chdir",
483 pathOrDescriptor: cwd,
484 });
485 const cause = new VcsProcessSpawnError({
486 operation: "AzureDevOpsCli.execute",
487 command: "az",
488 cwd,
489 argumentCount: 2,
490 cause: platformCause,
491 });
492 mockRun.mockReturnValueOnce(Effect.fail(cause));
493​
494 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
495 const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
496​
497 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
498 assert.strictEqual(error.cwd, cwd);
499 assert.strictEqual(error.cause, cause);
500 }).pipe(Effect.provide(layer)),
501 );
502​
503 it.effect("preserves rate-limit failures as a distinct error", () =>
504 Effect.gen(function* () {
505 const cause = new VcsProcessExitError({
506 operation: "AzureDevOpsCli.execute",
507 command: "az",
508 cwd: "/repo",
509 argumentCount: 2,
510 exitCode: 1,
511 detail: "API rate limit exceeded.",
512 failureKind: "rate-limited",
513 });
514 mockRun.mockReturnValueOnce(Effect.fail(cause));
515​
516 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
517 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
518​
519 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCliRateLimitError);
520 assert.strictEqual(error.cause, cause);
521 }).pipe(Effect.provide(layer)),
522 );
523});
524​
525describe("azureCliInvocation", () => {
526 const launcher = "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd";
527 const msi: AzureCliInstall = {
528 interpreter: "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\python.exe",
529 installer: "MSI",
530 };
531​
532 const invocationFor = (install: AzureCliInstall | undefined) =>
533 AzureDevOpsCli.azureCliInvocation().pipe(
534 Effect.provideService(HostProcess.Platform, "win32"),
535 Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }),
536 Effect.provideService(SpawnExecutableResolution, async () => launcher),
537 Effect.provideService(AzureCliInstallLocation, () => install),
538 );
539​
540 it.effect("runs the install's interpreter in UTF-8 mode", () =>
541 Effect.gen(function* () {
542 assert.deepStrictEqual(yield* invocationFor(msi), {
543 command: msi.interpreter,
544 args: ["-X", "utf8", "-IBm", "azure.cli"],
545 env: { AZ_INSTALLER: "MSI" },
546 });
547 }),
548 );
549​
550 it.effect("keeps the launcher when the install is not recognized", () =>
551 Effect.gen(function* () {
552 assert.deepStrictEqual(yield* invocationFor(undefined), {
553 command: "az",
554 args: [],
555 });
556 }),
557 );
558​
559 it.effect("spawns az directly off Windows", () =>
560 Effect.gen(function* () {
561 const invocation = yield* AzureDevOpsCli.azureCliInvocation().pipe(
562 Effect.provideService(HostProcess.Platform, "linux"),
563 );
564​
565 assert.deepStrictEqual(invocation, { command: "az", args: [] });
566 }),
567 );
568});
569​
570describe("scopeAzureCliArgs", () => {
571 const origin = "https://dev.azure.com/acme/Project/_git/Repo";
572 const show = ["repos", "show", "--detect", "true"];
573​
574 it.each([
575 [
576 ["repos", "show"],
577 ["--project=Project", "--repository=Repo"],
578 ],
579 [["repos", "create", "--name", "New"], ["--project=Project"]],
580 [
581 ["repos", "pr", "list"],
582 ["--project=Project", "--repository=Repo"],
583 ],
584 [
585 ["repos", "pr", "create"],
586 ["--project=Project", "--repository=Repo"],
587 ],
588 [["repos", "pr", "show", "--id", "42"], []],
589 [["devops", "invoke", "--area", "git"], []],
590 ])("scopes %j to the commands' supported arguments", (command, scope) => {
591 expect(scopeAzureCliArgs([...command, "--detect", "true"], origin)).toEqual([
592 ...command,
593 "--detect",
594 "false",
595 "--organization",
596 "https://dev.azure.com/acme",
597 ...scope,
598 ]);
599 });
600​
601 it.each([
602 ["https://dev.azure.com/acme/My%20Project/_git/My%20Repo", "https://dev.azure.com/acme"],
603 ["https://user@dev.azure.com/acme/My%20Project/_git/My%20Repo", "https://dev.azure.com/acme"],
604 [
605 "https://acme.visualstudio.com/DefaultCollection/My%20Project/_git/My%20Repo",
606 "https://acme.visualstudio.com",
607 ],
608 ["https://acme.visualstudio.com/My%20Project/_git/My%20Repo", "https://acme.visualstudio.com"],
609 ["git@ssh.dev.azure.com:v3/acme/My%20Project/My%20Repo", "https://dev.azure.com/acme"],
610 ["ssh://git@ssh.dev.azure.com:22/v3/acme/My%20Project/My%20Repo", "https://dev.azure.com/acme"],
611 ["git@vs-ssh.visualstudio.com:v3/acme/My%20Project/My%20Repo", "https://acme.visualstudio.com"],
612 ["https://dev.azure.com/acme/My%20Project/_git/My%20Repo/", "https://dev.azure.com/acme"],
613 ["git@ssh.dev.azure.com:v3/acme/My%20Project/My%20Repo/", "https://dev.azure.com/acme"],
614 ])("reads the organization of %s", (url, organization) => {
615 expect(scopeAzureCliArgs(show, url)).toEqual([
616 "repos",
617 "show",
618 "--detect",
619 "false",
620 "--organization",
621 organization,
622 "--project=My Project",
623 "--repository=My Repo",
624 ]);
625 });
626​
627 it.each([
628 ["https://dev.azure.com/acme/_git/My%20Repo", "https://dev.azure.com/acme", "My Repo"],
629 ["https://acme.visualstudio.com/_git/My%20Repo", "https://acme.visualstudio.com", "My Repo"],
630 [
631 "https://acme.visualstudio.com/DefaultCollection/_git/My%20Repo",
632 "https://acme.visualstudio.com",
633 "My Repo",
634 ],
635 ])("reads shorthand %s as a project named after its repository", (url, organization, name) => {
636 expect(scopeAzureCliArgs(show, url)).toEqual([
637 "repos",
638 "show",
639 "--detect",
640 "false",
641 "--organization",
642 organization,
643 `--project=${name}`,
644 `--repository=${name}`,
645 ]);
646 });
647​
648 it("joins names starting with `-` to their options", () => {
649 expect(
650 scopeAzureCliArgs(
651 ["repos", "pr", "list", "--detect", "true"],
652 "https://dev.azure.com/acme/-Project/_git/-Repo",
653 ),
654 ).toEqual(expect.arrayContaining(["--project=-Project", "--repository=-Repo"]));
655 });
656​
657 it("keeps the caller's project and repository", () => {
658 for (const selection of [
659 ["--project", "Chosen", "--repository", "Chosen"],
660 ["-p", "Chosen", "-r", "Chosen"],
661 ["--repository=Chosen", "--project", "Chosen"],
662 ]) {
663 expect(
664 scopeAzureCliArgs(["repos", "show", ...selection, "--detect", "true"], origin),
665 ).toEqual([
666 "repos",
667 "show",
668 ...selection,
669 "--detect",
670 "false",
671 "--organization",
672 "https://dev.azure.com/acme",
673 ]);
674 }
675 });
676​
677 it.each([
678 [["account", "show", "--detect", "true"], origin],
679 [["repos", "show"], origin],
680 [["repos", "show", "--detect", "false"], origin],
681 [["repos", "show", "--detect", "true", "--org", "https://dev.azure.com/explicit"], origin],
682 [show, "https://github.com/acme/repo"],
683 [show, "https://dev.azure.com/acme"],
684 [show, "https://dev.azure.com/acme/%XX/_git/Repo"],
685 [show, "git@ssh.dev.azure.com:v4/acme/Project/Repo"],
686 [show, "git@vs-ssh.visualstudio.com:v3/acme.invalid/Project/Repo"],
687 // az would replace the value with the contents of a local file.
688 [show, "https://dev.azure.com/acme/Project/_git/%40.env"],
689 ])("leaves %j to az when %s gives no scope", (args, url) => {
690 expect(scopeAzureCliArgs(args, url)).toEqual(args);
691 });
692});
693​
694describe("primaryRemoteUrl", () => {
695 const remotes = (...entries: ReadonlyArray<readonly [string, string]>) =>
696 entries.map(([name, url]) => `${name}\t${url} (fetch)\n${name}\tpush-url (push)\n`).join("");
697 const azure = (name: string) => [name, `https://dev.azure.com/${name}/P/_git/R`] as const;
698​
699 it.each([
700 // Where T3 publishes the branch and creates its pull requests.
701 [remotes(azure("upstream"), azure("origin")), azure("origin")[1]],
702 [
703 remotes(["github", "https://github.com/acme/repo"], azure("zebra"), azure("alpha")),
704 azure("zebra")[1],
705 ],
706 // A non-Azure origin leaves detection to az rather than scoping another repository.
707 [
708 remotes(azure("upstream"), ["origin", "https://github.com/acme/repo"]),
709 "https://github.com/acme/repo",
710 ],
711 [
712 `origin\t${azure("origin")[1]} (fetch) [blob:none]\norigin\tpush-url (push)\n`,
713 azure("origin")[1],
714 ],
715 [
716 remotes(["origin", "https://dev.azure.com/acme/My Project/_git/My Repo"]),
717 "https://dev.azure.com/acme/My Project/_git/My Repo",
718 ],
719 [remotes(["backup", "/Users/alice/My Repos/app"], azure("origin")), azure("origin")[1]],
720 [remotes(), null],
721 [`origin\t${azure("origin")[1]} (fetch)`, null],
722 [remotes(["origin", "https://dev.azure.com/acme/My\tProject/_git/Repo"]), null],
723 ])("picks the scoping remote from %j", (output, url) => {
724 expect(primaryRemoteUrl(output)).toBe(url);
725 });
726});