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

azureDevOpsPullRequests.ts

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