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
19// `\"` escapes a quote unless a space, comma or the end follows: then it closes after a literal `\`.
20const QUOTED = String.raw`"((?:[^"\\]|\\"(?![\s,]|$)|\\)*)"`;
21const QUERY_TOKEN = new RegExp(String.raw`(?:[^\s"]|${QUOTED})+`, "g");
22const QUOTED_OR_STRAY_QUOTE = new RegExp(String.raw`${QUOTED}|"`, "g");
23const LIST_ITEM = new RegExp(String.raw`(?:[^,"]|${QUOTED})+`, "g");
24const MAX_QUALIFIER_VALUES = 10;
25const MAX_QUALIFIER_LENGTH = 200;
26const MAX_TEXT_LENGTH = 200;
27
28function boundedText(value: string, limit: number): string {
29 return value.slice(0, splitsSurrogatePair(value, limit) ? limit - 1 : limit).trim();
30}
31
32function qualifierValue(raw: string): string {
33 return raw
34 .replace(QUOTED_OR_STRAY_QUOTE, (_, quoted?: string) => (quoted ?? "").replaceAll('\\"', '"'))
35 .trim();
36}
37
38function splitQualifierList(raw: string): string[] {
39 return (raw.match(LIST_ITEM) ?? [])
40 .map((part) => qualifierValue(part))
41 .filter((part) => part.length > 0);
42}
43
44/** `me` and `@me` both name the viewer; logins are case-insensitive. */
45function authorKey(login: string): string {
46 return login.toLowerCase().replace(/^@me$/, "me");
47}
48
49function boundedNames(names: ReadonlyArray<string>): string[] {
50 return names
51 .slice(0, MAX_QUALIFIER_VALUES)
52 .map((name) => boundedText(name, MAX_QUALIFIER_LENGTH))
53 .filter((name) => name.length > 0);
54}
55
56export function parsePullRequestQuery(raw: string): {
57 readonly text: string;
58 readonly filters: PullRequestListFilters;
59} {
60 const text: string[] = [];
61 const labels: string[][] = [];
62 const excludedLabels: string[] = [];
63 // `null` once two different logins are named: GitHub ORs them, the contract carries one.
64 let author: string | null | undefined;
65 let draft: PullRequestListFilters["draft"];
66 let review: PullRequestListFilters["review"];
67 let checks: PullRequestListFilters["checks"];
68 for (const [token] of raw.matchAll(QUERY_TOKEN)) {
69 const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);
70 const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");
71 const negated = qualifier?.[1] === "-";
72 const qualifierKey = value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "");
73 switch (qualifierKey) {
74 case "label": {
75 const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));
76 if (names.length === 0) break;
77 if (negated) excludedLabels.push(...names);
78 else labels.push(names);
79 continue;
80 }
81 case "author": {
82 if (negated) break;
83 const login = boundedText(value, MAX_QUALIFIER_LENGTH);
84 if (author === undefined) author = login;
85 else if (author === null || authorKey(author) !== authorKey(login)) author = null;
86 continue;
87 }
88 case "draft":
89 if (value.toLowerCase() !== "true" && value.toLowerCase() !== "false") break;
90 draft = (value.toLowerCase() === "true") !== negated ? "only" : "hide";
91 continue;
92 case "review": {
93 const key = value.toLowerCase();
94 const decision =
95 !negated && Object.hasOwn(REVIEW_VALUES, key) ? REVIEW_VALUES[key] : undefined;
96 if (decision === undefined) break;
97 review = decision;
98 continue;
99 }
100 case "status":
101 case "checks": {
102 const key = value.toLowerCase();
103 const state =
104 !negated && Object.hasOwn(CHECKS_VALUES, key) ? CHECKS_VALUES[key] : undefined;
105 if (state === undefined) break;
106 checks = state;
107 continue;
108 }
109 // GitHub's own search qualifiers, not labels: the list sets scope and order itself.
110 case "is":
111 if (value.toLowerCase() === "draft") draft = negated ? "hide" : "only";
112 continue;
113 case "archived":
114 case "state":
115 case "repo":
116 case "org":
117 case "user":
118 case "sort":
119 continue;
120 case "":
121 break;
122 default:
123 // GitHub also scopes PR searches with `type:pr`; keep other `type:*` tokens as labels.
124 if (!negated && qualifierKey === "type" && value.toLowerCase() === "pr") continue;
125 if (!value.startsWith("/")) {
126 const namespace = `${qualifier?.[2] ?? ""}:`;
127 const names = boundedNames(
128 splitQualifierList(`${namespace}${qualifier?.[3] ?? ""}`)
129 .map((name, index) =>
130 index === 0 || name.includes(":") ? name : `${namespace}${name}`,
131 )
132 .filter((name, index) => index > 0 || name !== namespace),
133 );
134 if (names.length === 0) break;
135 if (negated) excludedLabels.push(...names);
136 else labels.push(names);
137 continue;
138 }
139 }
140 text.push(token);
141 }
142 return {
143 text: boundedText(text.join(" "), MAX_TEXT_LENGTH),
144 filters: {
145 ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),
146 ...(excludedLabels.length === 0
147 ? {}
148 : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),
149 ...(typeof author === "string" ? { author } : {}),
150 ...(draft === undefined ? {} : { draft }),
151 ...(review === undefined ? {} : { review }),
152 ...(checks === undefined ? {} : { checks }),
153 },
154 };
155}
156
157/** The Filters menu's radio qualifiers: it shows a typed one in place of its own value. */
158const MENU_QUALIFIERS = ["draft", "review", "checks"] as const;
159type MenuQualifier = (typeof MENU_QUALIFIERS)[number];
160
161export function pullRequestMenuFilters(
162 typed: PullRequestListFilters,
163 menuFilters: PullRequestListFilters,
164): PullRequestListFilters {
165 return {
166 ...menuFilters,
167 draft: typed.draft ?? menuFilters.draft,
168 review: typed.review ?? menuFilters.review,
169 checks: typed.checks ?? menuFilters.checks,
170 };
171}
172
173/**
174 * Picking another menu value takes the matching typed qualifier out of the query: left in, it
175 * would keep outranking whatever the menu stores.
176 */
177export function applyPullRequestFilterChange(
178 query: string,
179 menuFilters: PullRequestListFilters,
180 next: PullRequestListFilters,
181) {
182 const typed = parsePullRequestQuery(query).filters;
183 const changed = (key: MenuQualifier) => next[key] !== (typed[key] ?? menuFilters[key]);
184 const replaced = MENU_QUALIFIERS.filter((key) => typed[key] !== undefined && changed(key));
185 const removes = (token: string) => {
186 const filters = parsePullRequestQuery(token).filters;
187 return replaced.some((key) => filters[key] !== undefined);
188 };
189 return {
190 // Cut by source span so text the tokenizer skips, like an unclosed quote, stays as typed.
191 query:
192 replaced.length === 0
193 ? query
194 : [...query.matchAll(QUERY_TOKEN)]
195 .reduceRight(
196 (rest, match) =>
197 removes(match[0])
198 ? rest.slice(0, match.index) +
199 rest.slice(match.index + match[0].length).trimStart()
200 : rest,
201 query,
202 )
203 .trim(),
204 filters: {
205 ...next,
206 draft: changed("draft") ? next.draft : menuFilters.draft,
207 review: changed("review") ? next.review : menuFilters.review,
208 checks: changed("checks") ? next.checks : menuFilters.checks,
209 },
210 };
211}