From 2717ab49dc12753ddb0c4d76aad997b75c52f48d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=85=E8=86=80?= Date: Sat, 17 Oct 2026 07:21:36 +0800 Subject: [PATCH] fix(filters): adapt suggestions to the selected operator Offer literal prefixes and suffixes for substring operators, escaped anchored patterns for regex, and numeric suggestions only for comparisons. Suggestion syntax must mean what the selected matcher actually reads. --- app/utils/filter-catalog.ts | 52 ++++++++++++++++++++++++++++++-- docs/guide/filters.md | 2 +- docs/zh/guide/filters.md | 2 +- tests/filter-catalog.test.ts | 58 ++++++++++++++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 4 deletions(-) diff --git a/app/utils/filter-catalog.ts b/app/utils/filter-catalog.ts index c1a6e24..b9767d3 100644 --- a/app/utils/filter-catalog.ts +++ b/app/utils/filter-catalog.ts @@ -1126,6 +1126,38 @@ const BRANCH_SUGGESTIONS: Array<[string, Bilingual]> = [ ["release/*", { en: "Any release/ branch", zh: "所有 release/ 分支" }], ]; +/** + * Glob suggestions adapted to the substring operators, which compare text + * literally: each becomes the text the glob implies (`release/*` → + * `release/` for startsWith, `*[bot]` → `[bot]` for endsWith) or is dropped. + */ +function suggestionsFor( + list: Array<[string, Bilingual]>, + op: FilterOp, +): Array<[string, Bilingual]> { + if (op !== "contains" && op !== "startsWith" && op !== "endsWith") return list; + return list.flatMap(([value, label]): Array<[string, Bilingual]> => { + if (!isGlob(value)) return [[value, label]]; + const prefix = /^[^*?]+\*$/.test(value) ? value.slice(0, -1) : null; + const suffix = /^\*[^*?]+$/.test(value) ? value.slice(1) : null; + const literal = op === "startsWith" ? prefix : op === "endsWith" ? suffix : (prefix ?? suffix); + return literal ? [[literal, label]] : []; + }); +} + +/** + * A suggestion as a raw pattern: metacharacters escaped + * (`dependabot\[bot\]`), `*`/`?` globs turned into `.*`/`.`, anchored at the + * ends the glob fixes (`^main$`, `^release/`, `\[bot\]$`). + */ +function suggestionRegex(value: string): string { + const body = value + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, "."); + return `^${body}$`.replace(/^\^\.\*/, "").replace(/\.\*\$$/, "") || ".*"; +} + /** Value suggestions for a leaf of `type` and `op` (`path` and `events` add context). */ export function valueOptions( locale: Locale, @@ -1133,6 +1165,22 @@ export function valueOptions( op: FilterOp, path: string, events: string[], +): ComboOption[] { + const options = typeValueOptions(locale, type, op, path, events); + // `regex` reads a raw pattern: offer each suggestion as the regex it means. + if (op === "regex") return options.map((o) => ({ ...o, value: suggestionRegex(o.value) })); + // Comparison operators need numbers, which no suggestion is. + if (op === "gt" || op === "gte" || op === "lt" || op === "lte") + return options.filter((o) => Number.isFinite(Number(o.value))); + return options; +} + +function typeValueOptions( + locale: Locale, + type: FilterType, + op: FilterOp, + path: string, + events: string[], ): ComboOption[] { switch (type) { case "event": @@ -1140,9 +1188,9 @@ export function valueOptions( case "action": return actionOptions(locale, events); case "actor": - return ACTOR_SUGGESTIONS.map(([v, label]) => toOption(v, label, locale)); + return suggestionsFor(ACTOR_SUGGESTIONS, op).map(([v, label]) => toOption(v, label, locale)); case "branch": - return BRANCH_SUGGESTIONS.map(([v, label]) => toOption(v, label, locale)); + return suggestionsFor(BRANCH_SUGGESTIONS, op).map(([v, label]) => toOption(v, label, locale)); case "field": return fieldValueOptions(locale, path); default: diff --git a/docs/guide/filters.md b/docs/guide/filters.md index 8e09a9e..b02f913 100644 --- a/docs/guide/filters.md +++ b/docs/guide/filters.md @@ -256,7 +256,7 @@ A route can use a nested `ast` to combine filters with explicit grouping instead When `ast` is present it takes precedence over `filters`. The admin console's route editor builds `ast` visually (all/any/not groups), shows a live explanation of the tree, and can test it against a pasted JSON payload via the **Test match** panel. -Values, field paths and the test event use searchable dropdowns. Suggestions come from GitHub's and Gitea's webhook definitions — events, the actions of the events the route filters on, common payload paths and their known values — each shown as its English key with a description in the console language; search matches the key first, then the English or Chinese description. Anything outside the list can still be typed and is validated before it is added; only values that can never match are rejected (an event name with spaces, a branch with characters git forbids, invalid regex syntax, a non-number for a comparison operator, …). Repository and actor values stay free-form because custom webhooks may carry any string. Text that is typed but not added with Enter blocks saving, fragment saving and test runs instead of being added or dropped silently. Several values can be typed or pasted at once, separated by commas or new lines; a `/regex/` keeps its own commas, and with the **matches regex** (`regex`) operator only new lines separate values (a raw pattern such as `^v{1,3}` may contain commas). Arrays are expanded along a `field` path, but a path that **ends** on an array (e.g. `commits.modified`) is compared as a whole — match one of its elements with `contains`; the editor switches to `contains` when such a suggested path is picked. +Values, field paths and the test event use searchable dropdowns. Suggestions come from GitHub's and Gitea's webhook definitions — events, the actions of the events the route filters on, common payload paths and their known values — each shown as its English key with a description in the console language; search matches the key first, then the English or Chinese description. Anything outside the list can still be typed and is validated before it is added; only values that can never match are rejected (an event name with spaces, a branch with characters git forbids, invalid regex syntax, a non-number for a comparison operator, …). Repository and actor values stay free-form because custom webhooks may carry any string. Text that is typed but not added with Enter blocks saving, fragment saving and test runs instead of being added or dropped silently. Several values can be typed or pasted at once, separated by commas or new lines; a `/regex/` keeps its own commas, and with the **matches regex** (`regex`) operator only new lines separate values (a raw pattern such as `^v{1,3}` may contain commas). Suggestions follow the operator: the substring operators compare text literally, so a glob suggestion becomes the text it implies (`release/*` → `release/` for **starts with**, `*[bot]` → `[bot]` for **ends with**), **matches regex** offers each suggestion as the escaped, anchored pattern it means (`^dependabot\[bot\]$`, `^release/`), and comparison operators get no suggestions. Arrays are expanded along a `field` path, but a path that **ends** on an array (e.g. `commits.modified`) is compared as a whole — match one of its elements with `contains`; the editor switches to `contains` when such a suggested path is picked. ### Named filter fragments diff --git a/docs/zh/guide/filters.md b/docs/zh/guide/filters.md index e5c7c72..33f9edc 100644 --- a/docs/zh/guide/filters.md +++ b/docs/zh/guide/filters.md @@ -256,7 +256,7 @@ 当 `ast` 存在时,它优先于 `filters`。管理后台的路由编辑器会以可视化方式构建 `ast`(all/any/not 分组)、实时展示树状解释,并可通过「测试匹配」面板粘贴 JSON 载荷进行试匹配。 -匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按回车添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。可一次输入或粘贴多个值,以逗号或换行分隔;`/正则/` 内的逗号会保留,选择「正则匹配」运算符时只按换行分隔(如 `^v{1,3}` 这样的原始模式可以包含逗号)。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。 +匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按回车添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。可一次输入或粘贴多个值,以逗号或换行分隔;`/正则/` 内的逗号会保留,选择「正则匹配」运算符时只按换行分隔(如 `^v{1,3}` 这样的原始模式可以包含逗号)。候选值会随运算符调整:「包含 / 开头是 / 结尾是」按字面比较,因此通配候选会换成其对应的文本(「开头是」用 `release/` 代替 `release/*`,「结尾是」用 `[bot]` 代替 `*[bot]`);「正则匹配」会把候选换成已转义并加锚点的等价正则(如 `^dependabot\[bot\]$`、`^release/`);比较运算符不提供候选。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。 ### 命名过滤器片段 diff --git a/tests/filter-catalog.test.ts b/tests/filter-catalog.test.ts index 1f68c36..91bdd1d 100644 --- a/tests/filter-catalog.test.ts +++ b/tests/filter-catalog.test.ts @@ -11,6 +11,9 @@ import { valueOptions, } from "../app/utils/filter-catalog"; +import { evaluateFilterNode } from "../server/lib/events/filter-ast"; +import type { WebhookEvent } from "../server/lib/types"; + function values(opts: { value: string }[]): string[] { return opts.map((o) => o.value); } @@ -83,6 +86,61 @@ describe("filter catalog options", () => { expect(valueOptions("en", "keyword", "eq", "", [])).toEqual([]); }); + it("turns glob suggestions into the literal text the operator compares", () => { + const branch = (op: "startsWith" | "endsWith" | "contains"): string[] => + values(valueOptions("en", "branch", op, "", [])); + expect(branch("startsWith")).toContain("release/"); + expect(branch("startsWith")).not.toContain("release/*"); + expect(branch("endsWith")).not.toContain("release/"); + expect(branch("contains")).toContain("release/"); + const actor = (op: "startsWith" | "endsWith"): string[] => + values(valueOptions("en", "actor", op, "", [])); + expect(actor("endsWith")).toContain("[bot]"); + expect(actor("startsWith")).not.toContain("[bot]"); + }); + + it("offers regex suggestions that match exactly what the suggestion means", () => { + const sender = (login: string): WebhookEvent => ({ + event: "push", + payload: { sender: { login } }, + }); + const matches = (pattern: string, login: string): boolean => + evaluateFilterNode({ type: "actor", op: "regex", match: pattern }, sender(login)); + const actor = values(valueOptions("en", "actor", "regex", "", [])); + expect(actor).toEqual([ + "\\[bot\\]$", + "^dependabot\\[bot\\]$", + "^github-actions\\[bot\\]$", + "^renovate\\[bot\\]$", + ]); + for (const login of ["dependabot[bot]", "github-actions[bot]", "renovate[bot]"]) { + expect(matches(actor[0]!, login)).toBe(true); + expect(actor.slice(1).filter((p) => matches(p, login))).toHaveLength(1); + } + expect(matches("^dependabot\\[bot\\]$", "dependabotb")).toBe(false); + expect(values(valueOptions("en", "branch", "regex", "", []))).toEqual([ + "^main$", + "^master$", + "^develop$", + "^release/", + ]); + // Anchored: `pull_request` must not also match `pull_request_review`. + const events = values(valueOptions("en", "event", "regex", "", [])); + expect(events).toContain("^pull_request$"); + const review: WebhookEvent = { event: "pull_request_review", payload: {} }; + expect( + evaluateFilterNode({ type: "event", op: "regex", match: "^pull_request$" }, review), + ).toBe(false); + for (const pattern of events) { + expect(validateFilterValue("event", "regex", pattern)).toBeNull(); + } + }); + + it("offers no non-numeric suggestion to comparison operators", () => { + expect(valueOptions("en", "field", "gt", "pull_request.draft", [])).toEqual([]); + expect(valueOptions("en", "event", "lte", "", [])).toEqual([]); + }); + it("ignores typed event names that are not catalog entries", () => { for (const name of ["constructor", "__proto__", "toString"]) { const opts = actionOptions("en", [name]);