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