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

azureDevOpsPullRequests.ts

215 lines7.1 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 state: "open" | "closed" | "merged";
17 readonly isDraft?: boolean;
18 readonly isCrossRepository: boolean;
19 readonly closedAt?: string | null;
20 readonly mergedAt?: string | null;
21 readonly updatedAt: Option.Option<DateTime.Utc>;
23​
24const AzureDevOpsPullRequestSchema = Schema.Struct({
25 pullRequestId: PositiveInt,
26 title: TrimmedNonEmptyString,
27 url: Schema.optional(Schema.String),
28 repository: Schema.optional(
29 Schema.Struct({
30 name: Schema.optional(Schema.String),
31 webUrl: Schema.optional(Schema.String),
32 project: Schema.optional(
33 Schema.Struct({
34 name: Schema.optional(Schema.String),
35 }),
36 ),
37 }),
38 ),
39 sourceRefName: TrimmedNonEmptyString,
40 targetRefName: TrimmedNonEmptyString,
41 status: Schema.String,
42 isDraft: Schema.optional(Schema.Boolean),
43 /** `az` prints `null` for a pull request from the same repo. */
44 forkSource: Schema.optional(Schema.Unknown),
45 creationDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
46 closedDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
47 _links: Schema.optional(
48 Schema.Struct({
49 web: Schema.optional(
50 Schema.Struct({
51 href: Schema.String,
52 }),
53 ),
54 }),
55 ),
56});
57​
58function trimOptionalString(value: string | null | undefined): string | null {
59 const trimmed = value?.trim() ?? "";
60 return trimmed.length > 0 ? trimmed : null;
62​
63function normalizeRefName(refName: string): string {
64 return refName.trim().replace(/^refs\/heads\//, "");
66​
67function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed" | "merged" {
68 switch (status.trim().toLowerCase()) {
69 case "completed":
70 return "merged";
71 case "abandoned":
72 return "closed";
73 default:
74 return "open";
75 }
77​
78function encodeAzureDevOpsPathSegment(segment: string): string {
79 return encodeURIComponent(segment);
81​
82function azureDevOpsOrganizationBaseFromRestApiUrl(
83 value: string | null | undefined,
84): string | null {
85 const rawUrl = trimOptionalString(value);
86 if (!rawUrl) {
87 return null;
88 }
89​
90 try {
91 const url = new URL(rawUrl);
92 const hostname = url.hostname.toLowerCase();
93 const pathSegments = url.pathname.split("/").filter((segment) => segment.length > 0);
94 const isAzureRestUrl = pathSegments.some((segment) => segment.toLowerCase() === "_apis");
95 if (!isAzureRestUrl) {
96 return null;
97 }
98​
99 if (hostname === "dev.azure.com") {
100 const organization = pathSegments[0];
101 return organization ? `${url.origin}/${organization}` : null;
102 }
103​
104 if (hostname.endsWith(".visualstudio.com")) {
105 return url.origin;
106 }
107​
108 return null;
109 } catch {
110 return null;
111 }
113​
114export function azureDevOpsPullRequestWebUrl(input: {
115 readonly pullRequestId: number;
116 readonly webLink?: string | null | undefined;
117 readonly repositoryWebUrl?: string | null | undefined;
118 readonly restApiUrl?: string | null | undefined;
119 readonly projectName?: string | null | undefined;
120 readonly repositoryName?: string | null | undefined;
121}): string {
122 const webLink = trimOptionalString(input.webLink);
123 if (webLink) {
124 return webLink;
125 }
126​
127 const repositoryWebUrl = trimOptionalString(input.repositoryWebUrl);
128 if (repositoryWebUrl) {
129 return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${input.pullRequestId}`;
130 }
131​
132 const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(input.restApiUrl);
133 const projectName = trimOptionalString(input.projectName);
134 const repositoryName = trimOptionalString(input.repositoryName);
135 if (organizationBase && projectName && repositoryName) {
136 const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);
137 const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);
138 return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${input.pullRequestId}`;
139 }
140​
141 return trimOptionalString(input.restApiUrl) ?? "";
143​
144function normalizeAzureDevOpsPullRequestUrl(
145 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
146): string {
147 return azureDevOpsPullRequestWebUrl({
148 pullRequestId: raw.pullRequestId,
149 webLink: raw._links?.web?.href,
150 repositoryWebUrl: raw.repository?.webUrl,
151 restApiUrl: raw.url,
152 projectName: raw.repository?.project?.name,
153 repositoryName: raw.repository?.name,
154 });
156​
157function normalizeAzureDevOpsPullRequestRecord(
158 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
159): NormalizedAzureDevOpsPullRequestRecord {
160 const state = normalizeAzureDevOpsPullRequestState(raw.status);
161 const terminalAt = Option.match(raw.closedDate ?? Option.none(), {
162 onNone: () => null,
163 onSome: DateTime.formatIso,
164 });
165 return {
166 number: raw.pullRequestId,
167 title: raw.title,
168 url: normalizeAzureDevOpsPullRequestUrl(raw),
169 baseRefName: normalizeRefName(raw.targetRefName),
170 headRefName: normalizeRefName(raw.sourceRefName),
171 state,
172 ...(raw.isDraft === true ? { isDraft: true } : {}),
173 isCrossRepository: raw.forkSource != null,
174 closedAt: state === "closed" ? terminalAt : null,
175 mergedAt: state === "merged" ? terminalAt : null,
176 updatedAt: (raw.closedDate ?? Option.none()).pipe(
177 Option.orElse(() => raw.creationDate ?? Option.none()),
178 ),
179 };
181​
182const decodeAzureDevOpsPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
183const decodeAzureDevOpsPullRequest = decodeJsonResult(AzureDevOpsPullRequestSchema);
184const decodeAzureDevOpsPullRequestEntry = Schema.decodeUnknownExit(AzureDevOpsPullRequestSchema);
185​
186export function decodeAzureDevOpsPullRequestListJson(
187 raw: string,
188): Result.Result<
189 ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>,
190 Cause.Cause<Schema.SchemaError>
191> {
192 const result = decodeAzureDevOpsPullRequestList(raw);
193 if (Result.isSuccess(result)) {
194 const pullRequests: NormalizedAzureDevOpsPullRequestRecord[] = [];
195 for (const entry of result.success) {
196 const decodedEntry = decodeAzureDevOpsPullRequestEntry(entry);
197 if (Exit.isFailure(decodedEntry)) {
198 continue;
199 }
200 pullRequests.push(normalizeAzureDevOpsPullRequestRecord(decodedEntry.value));
201 }
202 return Result.succeed(pullRequests);
203 }
204 return Result.fail(result.failure);
206​
207export function decodeAzureDevOpsPullRequestJson(
208 raw: string,
209): Result.Result<NormalizedAzureDevOpsPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
210 const result = decodeAzureDevOpsPullRequest(raw);
211 if (Result.isSuccess(result)) {
212 return Result.succeed(normalizeAzureDevOpsPullRequestRecord(result.success));
213 }
214 return Result.fail(result.failure);