Open History to see the last commit
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();
40}
41
42function qualifierValue(raw: string): string {
43 return raw
44 .replace(QUOTED_OR_STRAY_QUOTE, (_, quoted?: string) => (quoted ?? "").replaceAll('\\"', '"'))
45 .trim();
46}
47
48function splitQualifierList(raw: string): string[] {
49 return (raw.match(LIST_ITEM) ?? [])
50 .map((part) => qualifierValue(part))
51 .filter((part) => part.length > 0);
52}
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");
57}
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);
64}
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) continue;
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 if (!Object.hasOwn(REVIEW_VALUES, key)) break;
105 // The list has no "not" for a scalar filter, so a negated one is dropped, not searched.
106 if (!negated) review = REVIEW_VALUES[key];
107 continue;
108 }
109 case "status":
110 case "checks": {
111 const key = value.toLowerCase();
112 if (!Object.hasOwn(CHECKS_VALUES, key)) break;
113 if (!negated) checks = CHECKS_VALUES[key];
114 continue;
115 }
116 // GitHub's own scope qualifier; only is:draft maps to a filter.
117 case "is":
118 if (value.toLowerCase() === "draft") draft = negated ? "hide" : "only";
119 continue;
120 case "":
121 break;
122 default:
123 if (IGNORED_QUALIFIERS.has(qualifierKey)) continue;
124 // GitHub also scopes PR searches with `type:pr`; keep other `type:*` tokens as labels.
125 if (!negated && qualifierKey === "type" && value.toLowerCase() === "pr") continue;
126 if (!value.startsWith("/")) {
127 const namespace = `${qualifier?.[2] ?? ""}:`;
128 const names = boundedNames(
129 splitQualifierList(`${namespace}${qualifier?.[3] ?? ""}`)
130 .map((name, index) =>
131 index === 0 || name.includes(":") ? name : `${namespace}${name}`,
132 )
133 .filter((name, index) => index > 0 || name !== namespace),
134 );
135 if (names.length === 0) break;
136 if (negated) excludedLabels.push(...names);
137 else labels.push(names);
138 continue;
139 }
140 }
141 text.push(token);
142 }
143 return {
144 text: boundedText(text.join(" "), MAX_TEXT_LENGTH),
145 filters: {
146 ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),
147 ...(excludedLabels.length === 0
148 ? {}
149 : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),
150 ...(typeof author === "string" ? { author } : {}),
151 ...(draft === undefined ? {} : { draft }),
152 ...(review === undefined ? {} : { review }),
153 ...(checks === undefined ? {} : { checks }),
154 },
155 };
156}
157
158function uniqueBy<T>(values: ReadonlyArray<T>, key: (value: T) => string): T[] {
159 const byKey = new Map<string, T>();
160 for (const value of values) if (!byKey.has(key(value))) byKey.set(key(value), value);
161 return [...byKey.values()];
162}
163
164const labelKey = (name: string) => name.trim().toLowerCase();
165
166/**
167 * Typed qualifiers outrank the menu's values, but label groups from both apply together. Not
168 * capped, so local filtering keeps every group; `boundPullRequestFilters` fits it to a request.
169 */
170export function combinePullRequestFilters(
171 menuFilters: PullRequestListFilters,
172 typed: PullRequestListFilters,
173): PullRequestListFilters {
174 const labels = uniqueBy([...(menuFilters.labels ?? []), ...(typed.labels ?? [])], (group) =>
175 JSON.stringify([...new Set(group.map(labelKey))].sort()),
176 );
177 const excludedLabels = uniqueBy(
178 [...(menuFilters.excludedLabels ?? []), ...(typed.excludedLabels ?? [])],
179 labelKey,
180 );
181 return {
182 ...menuFilters,
183 ...typed,
184 ...(labels.length === 0 ? {} : { labels }),
185 ...(excludedLabels.length === 0 ? {} : { excludedLabels }),
186 };
187}
188
189/** Cuts combined filters to what a list request carries; the client still applies the rest. */
190export function boundPullRequestFilters(filters: PullRequestListFilters): PullRequestListFilters {
191 return {
192 ...filters,
193 ...(filters.labels ? { labels: filters.labels.slice(0, MAX_QUALIFIER_VALUES) } : {}),
194 ...(filters.excludedLabels
195 ? { excludedLabels: filters.excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }
196 : {}),
197 };
198}
199
200/** The Filters menu's radio qualifiers: it shows a typed one in place of its own value. */
201const MENU_QUALIFIERS = ["author", "draft", "review", "checks"] as const;
202type MenuQualifier = (typeof MENU_QUALIFIERS)[number];
203
204function menuAuthor(author: string | undefined): string | undefined {
205 return author !== undefined && authorKey(author) === "me" ? "me" : author;
206}
207
208export function pullRequestMenuFilters(
209 typed: PullRequestListFilters,
210 menuFilters: PullRequestListFilters,
211): PullRequestListFilters {
212 return {
213 ...menuFilters,
214 author: menuAuthor(typed.author ?? menuFilters.author),
215 draft: typed.draft ?? menuFilters.draft,
216 review: typed.review ?? menuFilters.review,
217 checks: typed.checks ?? menuFilters.checks,
218 };
219}
220
221/**
222 * Picking another menu value takes the matching typed qualifier out of the query: left in, it
223 * would keep outranking whatever the menu stores.
224 */
225export function applyPullRequestFilterChange(
226 query: string,
227 menuFilters: PullRequestListFilters,
228 next: PullRequestListFilters,
229) {
230 const typed = parsePullRequestQuery(query).filters;
231 const shown = pullRequestMenuFilters(typed, menuFilters);
232 const changed = (key: MenuQualifier) =>
233 (key === "author" ? menuAuthor(next.author) : next[key]) !== shown[key];
234 const replaced = MENU_QUALIFIERS.filter((key) => typed[key] !== undefined && changed(key));
235 const removes = (token: string) => {
236 const filters = parsePullRequestQuery(token).filters;
237 return replaced.some((key) => filters[key] !== undefined);
238 };
239 return {
240 // Cut by source span so text the tokenizer skips, like an unclosed quote, stays as typed.
241 query:
242 replaced.length === 0
243 ? query
244 : [...query.matchAll(QUERY_TOKEN)]
245 .reduceRight(
246 (rest, match) =>
247 removes(match[0])
248 ? rest.slice(0, match.index) +
249 rest.slice(match.index + match[0].length).trimStart()
250 : rest,
251 query,
252 )
253 .trim(),
254 filters: {
255 ...next,
256 author: changed("author") ? next.author : menuFilters.author,
257 draft: changed("draft") ? next.draft : menuFilters.draft,
258 review: changed("review") ? next.review : menuFilters.review,
259 checks: changed("checks") ? next.checks : menuFilters.checks,
260 },
261 };
262}