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