Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as DateTime from "effect/DateTime";
3import * as Exit from "effect/Exit";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
8import { decodeJsonResult } from "@t3tools/shared/schemaJson";
9
10export interface NormalizedAzureDevOpsPullRequestRecord {
11 readonly number: number;
12 readonly title: string;
13 readonly url: string;
14 readonly baseRefName: string;
15 readonly headRefName: string;
16 readonly state: "open" | "closed" | "merged";
17 readonly isDraft?: boolean;
18 readonly closedAt?: string | null;
19 readonly mergedAt?: string | null;
20 readonly updatedAt: Option.Option<DateTime.Utc>;
21}
22
23const AzureDevOpsPullRequestSchema = Schema.Struct({
24 pullRequestId: PositiveInt,
25 title: TrimmedNonEmptyString,
26 url: Schema.optional(Schema.String),
27 repository: Schema.optional(
28 Schema.Struct({
29 name: Schema.optional(Schema.String),
30 webUrl: Schema.optional(Schema.String),
31 project: Schema.optional(
32 Schema.Struct({
33 name: Schema.optional(Schema.String),
34 }),
35 ),
36 }),
37 ),
38 sourceRefName: TrimmedNonEmptyString,
39 targetRefName: TrimmedNonEmptyString,
40 status: Schema.String,
41 isDraft: Schema.optional(Schema.Boolean),
42 creationDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
43 closedDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
44 _links: Schema.optional(
45 Schema.Struct({
46 web: Schema.optional(
47 Schema.Struct({
48 href: Schema.String,
49 }),
50 ),
51 }),
52 ),
53});
54
55function trimOptionalString(value: string | null | undefined): string | null {
56 const trimmed = value?.trim() ?? "";
57 return trimmed.length > 0 ? trimmed : null;
58}
59
60function normalizeRefName(refName: string): string {
61 return refName.trim().replace(/^refs\/heads\//, "");
62}
63
64function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed" | "merged" {
65 switch (status.trim().toLowerCase()) {
66 case "completed":
67 return "merged";
68 case "abandoned":
69 return "closed";
70 default:
71 return "open";
72 }
73}
74
75function encodeAzureDevOpsPathSegment(segment: string): string {
76 return encodeURIComponent(segment);
77}
78
79/**
80 * The organization root a REST url belongs to, which is where a browser url has to be hung when
81 * Azure answered with neither a web link nor a repository url. Read from what Azure returned
82 * rather than from the local remote, whose shape varies.
83 */
84function azureDevOpsOrganizationBaseFromRestApiUrl(
85 value: string | null | undefined,
86): string | null {
87 const rawUrl = trimOptionalString(value);
88 if (!rawUrl) {
89 return null;
90 }
91
92 try {
93 const url = new URL(rawUrl);
94 const hostname = url.hostname.toLowerCase();
95 const pathSegments = url.pathname.split("/").filter((segment) => segment.length > 0);
96 const isAzureRestUrl = pathSegments.some((segment) => segment.toLowerCase() === "_apis");
97 if (!isAzureRestUrl) {
98 return null;
99 }
100
101 if (hostname === "dev.azure.com") {
102 const organization = pathSegments[0];
103 return organization ? `${url.origin}/${organization}` : null;
104 }
105
106 if (hostname.endsWith(".visualstudio.com")) {
107 return url.origin;
108 }
109
110 return null;
111 } catch {
112 return null;
113 }
114}
115
116/**
117 * Where a pull request lives in a browser. Azure answers with a web link when asked for one and
118 * otherwise leaves it to be assembled, so all three routes are tried in the order they can be
119 * trusted. Takes plain fields so both the source control provider and the pull requests page
120 * can share it.
121 */
122export function azureDevOpsPullRequestWebUrl(input: {
123 readonly pullRequestId: number;
124 readonly webLink?: string | null | undefined;
125 readonly repositoryWebUrl?: string | null | undefined;
126 readonly restApiUrl?: string | null | undefined;
127 readonly projectName?: string | null | undefined;
128 readonly repositoryName?: string | null | undefined;
129}): string {
130 const webLink = trimOptionalString(input.webLink);
131 if (webLink) {
132 return webLink;
133 }
134
135 const repositoryWebUrl = trimOptionalString(input.repositoryWebUrl);
136 if (repositoryWebUrl) {
137 return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${input.pullRequestId}`;
138 }
139
140 const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(input.restApiUrl);
141 const projectName = trimOptionalString(input.projectName);
142 const repositoryName = trimOptionalString(input.repositoryName);
143 if (organizationBase && projectName && repositoryName) {
144 const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);
145 const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);
146 return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${input.pullRequestId}`;
147 }
148
149 return trimOptionalString(input.restApiUrl) ?? "";
150}
151
152function normalizeAzureDevOpsPullRequestUrl(
153 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
154): string {
155 return azureDevOpsPullRequestWebUrl({
156 pullRequestId: raw.pullRequestId,
157 webLink: raw._links?.web?.href,
158 repositoryWebUrl: raw.repository?.webUrl,
159 restApiUrl: raw.url,
160 projectName: raw.repository?.project?.name,
161 repositoryName: raw.repository?.name,
162 });
163}
164
165function normalizeAzureDevOpsPullRequestRecord(
166 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
167): NormalizedAzureDevOpsPullRequestRecord {
168 const state = normalizeAzureDevOpsPullRequestState(raw.status);
169 const terminalAt = Option.match(raw.closedDate ?? Option.none(), {
170 onNone: () => null,
171 onSome: DateTime.formatIso,
172 });
173 return {
174 number: raw.pullRequestId,
175 title: raw.title,
176 url: normalizeAzureDevOpsPullRequestUrl(raw),
177 baseRefName: normalizeRefName(raw.targetRefName),
178 headRefName: normalizeRefName(raw.sourceRefName),
179 state,
180 ...(raw.isDraft === true ? { isDraft: true } : {}),
181 closedAt: state === "closed" ? terminalAt : null,
182 mergedAt: state === "merged" ? terminalAt : null,
183 updatedAt: (raw.closedDate ?? Option.none()).pipe(
184 Option.orElse(() => raw.creationDate ?? Option.none()),
185 ),
186 };
187}
188
189const decodeAzureDevOpsPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
190const decodeAzureDevOpsPullRequest = decodeJsonResult(AzureDevOpsPullRequestSchema);
191const decodeAzureDevOpsPullRequestEntry = Schema.decodeUnknownExit(AzureDevOpsPullRequestSchema);
192
193export function decodeAzureDevOpsPullRequestListJson(
194 raw: string,
195): Result.Result<
196 ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>,
197 Cause.Cause<Schema.SchemaError>
198> {
199 const result = decodeAzureDevOpsPullRequestList(raw);
200 if (Result.isSuccess(result)) {
201 const pullRequests: NormalizedAzureDevOpsPullRequestRecord[] = [];
202 for (const entry of result.success) {
203 const decodedEntry = decodeAzureDevOpsPullRequestEntry(entry);
204 if (Exit.isFailure(decodedEntry)) {
205 continue;
206 }
207 pullRequests.push(normalizeAzureDevOpsPullRequestRecord(decodedEntry.value));
208 }
209 return Result.succeed(pullRequests);
210 }
211 return Result.fail(result.failure);
212}
213
214export function decodeAzureDevOpsPullRequestJson(
215 raw: string,
216): Result.Result<NormalizedAzureDevOpsPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
217 const result = decodeAzureDevOpsPullRequest(raw);
218 if (Result.isSuccess(result)) {
219 return Result.succeed(normalizeAzureDevOpsPullRequestRecord(result.success));
220 }
221 return Result.fail(result.failure);
222}