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

azureDevOpsPullRequests.ts

222 lines7.5 KB

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 headSha?: string;
17 readonly state: "open" | "closed" | "merged";
18 readonly isDraft?: boolean;
19 readonly isCrossRepository: boolean;
20 readonly closedAt?: string | null;
21 readonly mergedAt?: string | null;
22 readonly updatedAt: Option.Option<DateTime.Utc>;
24​
25const AzureDevOpsPullRequestSchema = Schema.Struct({
26 pullRequestId: PositiveInt,
27 title: TrimmedNonEmptyString,
28 url: Schema.optional(Schema.String),
29 repository: Schema.optional(
30 Schema.Struct({
31 name: Schema.optional(Schema.String),
32 webUrl: Schema.optional(Schema.String),
33 project: Schema.optional(
34 Schema.Struct({
35 name: Schema.optional(Schema.String),
36 }),
37 ),
38 }),
39 ),
40 sourceRefName: TrimmedNonEmptyString,
41 targetRefName: TrimmedNonEmptyString,
42 /** The source branch's tip as of Azure's last merge evaluation: the pull request's head. */
43 lastMergeSourceCommit: Schema.optional(
44 Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),
45 ),
46 status: Schema.String,
47 isDraft: Schema.optional(Schema.Boolean),
48 /** `az` prints `null` for a pull request from the same repo. */
49 forkSource: Schema.optional(Schema.Unknown),
50 creationDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
51 closedDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
52 _links: Schema.optional(
53 Schema.Struct({
54 web: Schema.optional(
55 Schema.Struct({
56 href: Schema.String,
57 }),
58 ),
59 }),
60 ),
61});
62​
63function trimOptionalString(value: string | null | undefined): string | null {
64 const trimmed = value?.trim() ?? "";
65 return trimmed.length > 0 ? trimmed : null;
67​
68function normalizeRefName(refName: string): string {
69 return refName.trim().replace(/^refs\/heads\//, "");
71​
72function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed" | "merged" {
73 switch (status.trim().toLowerCase()) {
74 case "completed":
75 return "merged";
76 case "abandoned":
77 return "closed";
78 default:
79 return "open";
80 }
82​
83function encodeAzureDevOpsPathSegment(segment: string): string {
84 return encodeURIComponent(segment);
86​
87function azureDevOpsOrganizationBaseFromRestApiUrl(
88 value: string | null | undefined,
89): string | null {
90 const rawUrl = trimOptionalString(value);
91 if (!rawUrl) {
92 return null;
93 }
94​
95 try {
96 const url = new URL(rawUrl);
97 const hostname = url.hostname.toLowerCase();
98 const pathSegments = url.pathname.split("/").filter((segment) => segment.length > 0);
99 const isAzureRestUrl = pathSegments.some((segment) => segment.toLowerCase() === "_apis");
100 if (!isAzureRestUrl) {
101 return null;
102 }
103​
104 if (hostname === "dev.azure.com") {
105 const organization = pathSegments[0];
106 return organization ? `${url.origin}/${organization}` : null;
107 }
108​
109 if (hostname.endsWith(".visualstudio.com")) {
110 return url.origin;
111 }
112​
113 return null;
114 } catch {
115 return null;
116 }
118​
119export function azureDevOpsPullRequestWebUrl(input: {
120 readonly pullRequestId: number;
121 readonly webLink?: string | null | undefined;
122 readonly repositoryWebUrl?: string | null | undefined;
123 readonly restApiUrl?: string | null | undefined;
124 readonly projectName?: string | null | undefined;
125 readonly repositoryName?: string | null | undefined;
126}): string {
127 const webLink = trimOptionalString(input.webLink);
128 if (webLink) {
129 return webLink;
130 }
131​
132 const repositoryWebUrl = trimOptionalString(input.repositoryWebUrl);
133 if (repositoryWebUrl) {
134 return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${input.pullRequestId}`;
135 }
136​
137 const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(input.restApiUrl);
138 const projectName = trimOptionalString(input.projectName);
139 const repositoryName = trimOptionalString(input.repositoryName);
140 if (organizationBase && projectName && repositoryName) {
141 const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);
142 const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);
143 return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${input.pullRequestId}`;
144 }
145​
146 return trimOptionalString(input.restApiUrl) ?? "";
148​
149function normalizeAzureDevOpsPullRequestUrl(
150 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
151): string {
152 return azureDevOpsPullRequestWebUrl({
153 pullRequestId: raw.pullRequestId,
154 webLink: raw._links?.web?.href,
155 repositoryWebUrl: raw.repository?.webUrl,
156 restApiUrl: raw.url,
157 projectName: raw.repository?.project?.name,
158 repositoryName: raw.repository?.name,
159 });
161​
162function normalizeAzureDevOpsPullRequestRecord(
163 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
164): NormalizedAzureDevOpsPullRequestRecord {
165 const state = normalizeAzureDevOpsPullRequestState(raw.status);
166 const headSha = trimOptionalString(raw.lastMergeSourceCommit?.commitId);
167 const terminalAt = Option.match(raw.closedDate ?? Option.none(), {
168 onNone: () => null,
169 onSome: DateTime.formatIso,
170 });
171 return {
172 number: raw.pullRequestId,
173 title: raw.title,
174 url: normalizeAzureDevOpsPullRequestUrl(raw),
175 baseRefName: normalizeRefName(raw.targetRefName),
176 headRefName: normalizeRefName(raw.sourceRefName),
177 ...(headSha ? { headSha } : {}),
178 state,
179 ...(raw.isDraft === true ? { isDraft: true } : {}),
180 isCrossRepository: raw.forkSource != null,
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 };
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);
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);