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

azureDevOpsPullRequests.ts

215 lines7.2 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, formatSchemaError } 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 updatedAt: Option.Option<DateTime.Utc>;
20​
21const AzureDevOpsPullRequestSchema = Schema.Struct({
22 pullRequestId: PositiveInt,
23 title: TrimmedNonEmptyString,
24 url: Schema.optional(Schema.String),
25 repository: Schema.optional(
26 Schema.Struct({
27 name: Schema.optional(Schema.String),
28 webUrl: Schema.optional(Schema.String),
29 project: Schema.optional(
30 Schema.Struct({
31 name: Schema.optional(Schema.String),
32 }),
33 ),
34 }),
35 ),
36 sourceRefName: TrimmedNonEmptyString,
37 targetRefName: TrimmedNonEmptyString,
38 status: Schema.String,
39 isDraft: Schema.optional(Schema.Boolean),
40 creationDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
41 closedDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
42 _links: Schema.optional(
43 Schema.Struct({
44 web: Schema.optional(
45 Schema.Struct({
46 href: Schema.String,
47 }),
48 ),
49 }),
50 ),
51});
52​
53function trimOptionalString(value: string | null | undefined): string | null {
54 const trimmed = value?.trim() ?? "";
55 return trimmed.length > 0 ? trimmed : null;
57​
58function normalizeRefName(refName: string): string {
59 return refName.trim().replace(/^refs\/heads\//, "");
61​
62function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed" | "merged" {
63 switch (status.trim().toLowerCase()) {
64 case "completed":
65 return "merged";
66 case "abandoned":
67 return "closed";
68 default:
69 return "open";
70 }
72​
73function encodeAzureDevOpsPathSegment(segment: string): string {
74 return encodeURIComponent(segment);
76​
77/**
78 * The organization root a REST url belongs to, which is where a browser url and any further
79 * REST call have to be hung. Exported because the pull requests page derives its own urls from
80 * whatever Azure returned rather than from the local remote, whose shape varies.
81 */
82export function 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​
114/**
115 * Where a pull request lives in a browser. Azure answers with a web link when asked for one and
116 * otherwise leaves it to be assembled, so all three routes are tried in the order they can be
117 * trusted. Takes plain fields so both the source control provider and the pull requests page
118 * can share it.
119 */
120export function azureDevOpsPullRequestWebUrl(input: {
121 readonly pullRequestId: number;
122 readonly webLink?: string | null | undefined;
123 readonly repositoryWebUrl?: string | null | undefined;
124 readonly restApiUrl?: string | null | undefined;
125 readonly projectName?: string | null | undefined;
126 readonly repositoryName?: string | null | undefined;
127}): string {
128 const webLink = trimOptionalString(input.webLink);
129 if (webLink) {
130 return webLink;
131 }
132​
133 const repositoryWebUrl = trimOptionalString(input.repositoryWebUrl);
134 if (repositoryWebUrl) {
135 return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${input.pullRequestId}`;
136 }
137​
138 const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(input.restApiUrl);
139 const projectName = trimOptionalString(input.projectName);
140 const repositoryName = trimOptionalString(input.repositoryName);
141 if (organizationBase && projectName && repositoryName) {
142 const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);
143 const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);
144 return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${input.pullRequestId}`;
145 }
146​
147 return trimOptionalString(input.restApiUrl) ?? "";
149​
150function normalizeAzureDevOpsPullRequestUrl(
151 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
152): string {
153 return azureDevOpsPullRequestWebUrl({
154 pullRequestId: raw.pullRequestId,
155 webLink: raw._links?.web?.href,
156 repositoryWebUrl: raw.repository?.webUrl,
157 restApiUrl: raw.url,
158 projectName: raw.repository?.project?.name,
159 repositoryName: raw.repository?.name,
160 });
162​
163function normalizeAzureDevOpsPullRequestRecord(
164 raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
165): NormalizedAzureDevOpsPullRequestRecord {
166 return {
167 number: raw.pullRequestId,
168 title: raw.title,
169 url: normalizeAzureDevOpsPullRequestUrl(raw),
170 baseRefName: normalizeRefName(raw.targetRefName),
171 headRefName: normalizeRefName(raw.sourceRefName),
172 state: normalizeAzureDevOpsPullRequestState(raw.status),
173 ...(raw.isDraft === true ? { isDraft: true } : {}),
174 updatedAt: (raw.closedDate ?? Option.none()).pipe(
175 Option.orElse(() => raw.creationDate ?? Option.none()),
176 ),
177 };
179​
180const decodeAzureDevOpsPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
181const decodeAzureDevOpsPullRequest = decodeJsonResult(AzureDevOpsPullRequestSchema);
182const decodeAzureDevOpsPullRequestEntry = Schema.decodeUnknownExit(AzureDevOpsPullRequestSchema);
183​
184export const formatAzureDevOpsJsonDecodeError = formatSchemaError;
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);