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

pullRequestQuery.ts

265 lines10.0 KB

1import type { PullRequestListFilters } from "@t3tools/contracts";
2import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations";
3​
4const REVIEW_VALUES: Record<string, PullRequestListFilters["review"]> = {
5 approved: "approved",
6 changes_requested: "changes-requested",
7 "changes-requested": "changes-requested",
8 required: "review-required",
9 "review-required": "review-required",
10 none: "none",
11};
12const CHECKS_VALUES: Record<string, PullRequestListFilters["checks"]> = {
13 success: "passing",
14 passing: "passing",
15 failure: "failing",
16 failing: "failing",
17};
18// GitHub's own PR search qualifiers the list cannot apply: dropped, not read as namespaced
19// labels, so a pasted GitHub query keeps its results. `label:team:x` still reaches such labels.
20const IGNORED_QUALIFIERS = new Set(
21 `archived assignee base closed commenter comments created head in interactions involves
22 language linked mentions merged milestone no org project reactions repo review-involves
23 review-requested reviewed-by sort state team team-review-requested
24 team-review-requested-user updated user user-review-requested`
25 .trim()
26 .split(/\s+/),
27);
28​
29// `\"` escapes a quote unless a space, comma or the end follows: then it closes after a literal `\`.
30const QUOTED = String.raw`"((?:[^"\\]|\\"(?![\s,]|$)|\\)*)"`;
31const QUERY_TOKEN = new RegExp(String.raw`(?:[^\s"]|${QUOTED})+`, "g");
32const QUOTED_OR_STRAY_QUOTE = new RegExp(String.raw`${QUOTED}|"`, "g");
33const LIST_ITEM = new RegExp(String.raw`(?:[^,"]|${QUOTED})+`, "g");
34const MAX_QUALIFIER_VALUES = 10;
35const MAX_QUALIFIER_LENGTH = 200;
36const MAX_TEXT_LENGTH = 200;
37​
38function boundedText(value: string, limit: number): string {
39 return value.slice(0, splitsSurrogatePair(value, limit) ? limit - 1 : limit).trim();
41​
42function qualifierValue(raw: string): string {
43 return raw
44 .replace(QUOTED_OR_STRAY_QUOTE, (_, quoted?: string) => (quoted ?? "").replaceAll('\\"', '"'))
45 .trim();
47​
48function splitQualifierList(raw: string): string[] {
49 return (raw.match(LIST_ITEM) ?? [])
50 .map((part) => qualifierValue(part))
51 .filter((part) => part.length > 0);
53​
54/** `me` and `@me` both name the viewer; logins are case-insensitive. */
55function authorKey(login: string): string {
56 return login.toLowerCase().replace(/^@me$/, "me");
58​
59function boundedNames(names: ReadonlyArray<string>): string[] {
60 return names
61 .slice(0, MAX_QUALIFIER_VALUES)
62 .map((name) => boundedText(name, MAX_QUALIFIER_LENGTH))
63 .filter((name) => name.length > 0);
65​
66export function parsePullRequestQuery(raw: string): {
67 readonly text: string;
68 readonly filters: PullRequestListFilters;
69} {
70 const text: string[] = [];
71 const labels: string[][] = [];
72 const excludedLabels: string[] = [];
73 // `null` once two different logins are named: GitHub ORs them, the contract carries one.
74 let author: string | null | undefined;
75 let draft: PullRequestListFilters["draft"];
76 let review: PullRequestListFilters["review"];
77 let checks: PullRequestListFilters["checks"];
78 for (const [token] of raw.matchAll(QUERY_TOKEN)) {
79 const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);
80 const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");
81 const negated = qualifier?.[1] === "-";
82 const qualifierKey = value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "");
83 switch (qualifierKey) {
84 case "label": {
85 const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));
86 if (names.length === 0) break;
87 if (negated) excludedLabels.push(...names);
88 else labels.push(names);
89 continue;
90 }
91 case "author": {
92 if (negated) break;
93 const login = boundedText(value, MAX_QUALIFIER_LENGTH);
94 if (author === undefined) author = login;
95 else if (author === null || authorKey(author) !== authorKey(login)) author = null;
96 continue;
97 }
98 case "draft":
99 if (value.toLowerCase() !== "true" && value.toLowerCase() !== "false") break;
100 draft = (value.toLowerCase() === "true") !== negated ? "only" : "hide";
101 continue;
102 case "review": {
103 const key = value.toLowerCase();
104 const decision =
105 !negated && Object.hasOwn(REVIEW_VALUES, key) ? REVIEW_VALUES[key] : undefined;
106 if (decision === undefined) break;
107 review = decision;
108 continue;
109 }
110 case "status":
111 case "checks": {
112 const key = value.toLowerCase();
113 const state =
114 !negated && Object.hasOwn(CHECKS_VALUES, key) ? CHECKS_VALUES[key] : undefined;
115 if (state === undefined) break;
116 checks = state;
117 continue;
118 }
119 // GitHub's own scope qualifier; only is:draft maps to a filter.
120 case "is":
121 if (value.toLowerCase() === "draft") draft = negated ? "hide" : "only";
122 continue;
123 case "":
124 break;
125 default:
126 if (IGNORED_QUALIFIERS.has(qualifierKey)) continue;
127 // GitHub also scopes PR searches with `type:pr`; keep other `type:*` tokens as labels.
128 if (!negated && qualifierKey === "type" && value.toLowerCase() === "pr") continue;
129 if (!value.startsWith("/")) {
130 const namespace = `${qualifier?.[2] ?? ""}:`;
131 const names = boundedNames(
132 splitQualifierList(`${namespace}${qualifier?.[3] ?? ""}`)
133 .map((name, index) =>
134 index === 0 || name.includes(":") ? name : `${namespace}${name}`,
135 )
136 .filter((name, index) => index > 0 || name !== namespace),
137 );
138 if (names.length === 0) break;
139 if (negated) excludedLabels.push(...names);
140 else labels.push(names);
141 continue;
142 }
143 }
144 text.push(token);
145 }
146 return {
147 text: boundedText(text.join(" "), MAX_TEXT_LENGTH),
148 filters: {
149 ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),
150 ...(excludedLabels.length === 0
151 ? {}
152 : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),
153 ...(typeof author === "string" ? { author } : {}),
154 ...(draft === undefined ? {} : { draft }),
155 ...(review === undefined ? {} : { review }),
156 ...(checks === undefined ? {} : { checks }),
157 },
158 };
160​
161function uniqueBy<T>(values: ReadonlyArray<T>, key: (value: T) => string): T[] {
162 const byKey = new Map<string, T>();
163 for (const value of values) if (!byKey.has(key(value))) byKey.set(key(value), value);
164 return [...byKey.values()];
166​
167const labelKey = (name: string) => name.trim().toLowerCase();
168​
169/**
170 * Typed qualifiers outrank the menu's values, but label groups from both apply together. Not
171 * capped, so local filtering keeps every group; `boundPullRequestFilters` fits it to a request.
172 */
173export function combinePullRequestFilters(
174 menuFilters: PullRequestListFilters,
175 typed: PullRequestListFilters,
176): PullRequestListFilters {
177 const labels = uniqueBy([...(menuFilters.labels ?? []), ...(typed.labels ?? [])], (group) =>
178 JSON.stringify([...new Set(group.map(labelKey))].sort()),
179 );
180 const excludedLabels = uniqueBy(
181 [...(menuFilters.excludedLabels ?? []), ...(typed.excludedLabels ?? [])],
182 labelKey,
183 );
184 return {
185 ...menuFilters,
186 ...typed,
187 ...(labels.length === 0 ? {} : { labels }),
188 ...(excludedLabels.length === 0 ? {} : { excludedLabels }),
189 };
191​
192/** Cuts combined filters to what a list request carries; the client still applies the rest. */
193export function boundPullRequestFilters(filters: PullRequestListFilters): PullRequestListFilters {
194 return {
195 ...filters,
196 ...(filters.labels ? { labels: filters.labels.slice(0, MAX_QUALIFIER_VALUES) } : {}),
197 ...(filters.excludedLabels
198 ? { excludedLabels: filters.excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }
199 : {}),
200 };
202​
203/** The Filters menu's radio qualifiers: it shows a typed one in place of its own value. */
204const MENU_QUALIFIERS = ["author", "draft", "review", "checks"] as const;
205type MenuQualifier = (typeof MENU_QUALIFIERS)[number];
206​
207function menuAuthor(author: string | undefined): string | undefined {
208 return author !== undefined && authorKey(author) === "me" ? "me" : author;
210​
211export function pullRequestMenuFilters(
212 typed: PullRequestListFilters,
213 menuFilters: PullRequestListFilters,
214): PullRequestListFilters {
215 return {
216 ...menuFilters,
217 author: menuAuthor(typed.author ?? menuFilters.author),
218 draft: typed.draft ?? menuFilters.draft,
219 review: typed.review ?? menuFilters.review,
220 checks: typed.checks ?? menuFilters.checks,
221 };
223​
224/**
225 * Picking another menu value takes the matching typed qualifier out of the query: left in, it
226 * would keep outranking whatever the menu stores.
227 */
228export function applyPullRequestFilterChange(
229 query: string,
230 menuFilters: PullRequestListFilters,
231 next: PullRequestListFilters,
232) {
233 const typed = parsePullRequestQuery(query).filters;
234 const shown = pullRequestMenuFilters(typed, menuFilters);
235 const changed = (key: MenuQualifier) =>
236 (key === "author" ? menuAuthor(next.author) : next[key]) !== shown[key];
237 const replaced = MENU_QUALIFIERS.filter((key) => typed[key] !== undefined && changed(key));
238 const removes = (token: string) => {
239 const filters = parsePullRequestQuery(token).filters;
240 return replaced.some((key) => filters[key] !== undefined);
241 };
242 return {
243 // Cut by source span so text the tokenizer skips, like an unclosed quote, stays as typed.
244 query:
245 replaced.length === 0
246 ? query
247 : [...query.matchAll(QUERY_TOKEN)]
248 .reduceRight(
249 (rest, match) =>
250 removes(match[0])
251 ? rest.slice(0, match.index) +
252 rest.slice(match.index + match[0].length).trimStart()
253 : rest,
254 query,
255 )
256 .trim(),
257 filters: {
258 ...next,
259 author: changed("author") ? next.author : menuFilters.author,
260 draft: changed("draft") ? next.draft : menuFilters.draft,
261 review: changed("review") ? next.review : menuFilters.review,
262 checks: changed("checks") ? next.checks : menuFilters.checks,
263 },
264 };